001/** 002 * 003 * Copyright 2003-2007 Jive Software. 2020-2024 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.jivesoftware.smackx.muc; 019 020import java.util.ArrayList; 021import java.util.Collection; 022import java.util.List; 023import java.util.Map; 024import java.util.Set; 025import java.util.concurrent.ConcurrentHashMap; 026import java.util.concurrent.CopyOnWriteArrayList; 027import java.util.concurrent.CopyOnWriteArraySet; 028import java.util.concurrent.atomic.AtomicInteger; 029import java.util.logging.Level; 030import java.util.logging.Logger; 031 032import org.jivesoftware.smack.MessageListener; 033import org.jivesoftware.smack.PresenceListener; 034import org.jivesoftware.smack.SmackException; 035import org.jivesoftware.smack.SmackException.NoResponseException; 036import org.jivesoftware.smack.SmackException.NotConnectedException; 037import org.jivesoftware.smack.StanzaCollector; 038import org.jivesoftware.smack.StanzaListener; 039import org.jivesoftware.smack.XMPPConnection; 040import org.jivesoftware.smack.XMPPException; 041import org.jivesoftware.smack.XMPPException.XMPPErrorException; 042import org.jivesoftware.smack.chat.ChatMessageListener; 043import org.jivesoftware.smack.filter.AndFilter; 044import org.jivesoftware.smack.filter.FromMatchesFilter; 045import org.jivesoftware.smack.filter.MessageTypeFilter; 046import org.jivesoftware.smack.filter.MessageWithBodiesFilter; 047import org.jivesoftware.smack.filter.MessageWithSubjectFilter; 048import org.jivesoftware.smack.filter.MessageWithThreadFilter; 049import org.jivesoftware.smack.filter.NotFilter; 050import org.jivesoftware.smack.filter.OrFilter; 051import org.jivesoftware.smack.filter.PossibleFromTypeFilter; 052import org.jivesoftware.smack.filter.PresenceTypeFilter; 053import org.jivesoftware.smack.filter.StanzaExtensionFilter; 054import org.jivesoftware.smack.filter.StanzaFilter; 055import org.jivesoftware.smack.filter.StanzaIdFilter; 056import org.jivesoftware.smack.filter.StanzaTypeFilter; 057import org.jivesoftware.smack.filter.ToMatchesFilter; 058import org.jivesoftware.smack.packet.IQ; 059import org.jivesoftware.smack.packet.Message; 060import org.jivesoftware.smack.packet.MessageBuilder; 061import org.jivesoftware.smack.packet.MessageView; 062import org.jivesoftware.smack.packet.Presence; 063import org.jivesoftware.smack.packet.PresenceBuilder; 064import org.jivesoftware.smack.packet.Stanza; 065import org.jivesoftware.smack.util.Consumer; 066import org.jivesoftware.smack.util.Objects; 067 068import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; 069import org.jivesoftware.smackx.disco.packet.DiscoverInfo; 070import org.jivesoftware.smackx.iqregister.packet.Registration; 071import org.jivesoftware.smackx.muc.MultiUserChatException.MissingMucCreationAcknowledgeException; 072import org.jivesoftware.smackx.muc.MultiUserChatException.MucAlreadyJoinedException; 073import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException; 074import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException; 075import org.jivesoftware.smackx.muc.filter.MUCUserStatusCodeFilter; 076import org.jivesoftware.smackx.muc.packet.Destroy; 077import org.jivesoftware.smackx.muc.packet.GroupChatInvitation; 078import org.jivesoftware.smackx.muc.packet.MUCAdmin; 079import org.jivesoftware.smackx.muc.packet.MUCInitialPresence; 080import org.jivesoftware.smackx.muc.packet.MUCItem; 081import org.jivesoftware.smackx.muc.packet.MUCOwner; 082import org.jivesoftware.smackx.muc.packet.MUCUser; 083import org.jivesoftware.smackx.muc.packet.MUCUser.Status; 084import org.jivesoftware.smackx.xdata.FormField; 085import org.jivesoftware.smackx.xdata.TextSingleFormField; 086import org.jivesoftware.smackx.xdata.form.FillableForm; 087import org.jivesoftware.smackx.xdata.form.Form; 088import org.jivesoftware.smackx.xdata.packet.DataForm; 089 090import org.jxmpp.jid.DomainBareJid; 091import org.jxmpp.jid.EntityBareJid; 092import org.jxmpp.jid.EntityFullJid; 093import org.jxmpp.jid.EntityJid; 094import org.jxmpp.jid.Jid; 095import org.jxmpp.jid.impl.JidCreate; 096import org.jxmpp.jid.parts.Resourcepart; 097 098/** 099 * A MultiUserChat room (XEP-45), created with {@link MultiUserChatManager#getMultiUserChat(EntityBareJid)}. 100 * <p> 101 * A MultiUserChat is a conversation that takes place among many users in a virtual 102 * room. A room could have many occupants with different affiliation and roles. 103 * Possible affiliations are "owner", "admin", "member", and "outcast". Possible roles 104 * are "moderator", "participant", and "visitor". Each role and affiliation guarantees 105 * different privileges (e.g. Send messages to all occupants, Kick participants and visitors, 106 * Grant voice, Edit member list, etc.). 107 * </p> 108 * <p> 109 * <b>Note:</b> Make sure to leave the MUC ({@link #leave()}) when you don't need it anymore or 110 * otherwise you may leak the instance. 111 * </p> 112 * 113 * @author Gaston Dombiak 114 * @author Larry Kirschner 115 * @author Florian Schmaus 116 */ 117public class MultiUserChat { 118 private static final Logger LOGGER = Logger.getLogger(MultiUserChat.class.getName()); 119 120 private final XMPPConnection connection; 121 private final EntityBareJid room; 122 private final MultiUserChatManager multiUserChatManager; 123 private final Map<EntityFullJid, Presence> occupantsMap = new ConcurrentHashMap<>(); 124 125 private final Set<InvitationRejectionListener> invitationRejectionListeners = new CopyOnWriteArraySet<InvitationRejectionListener>(); 126 private final Set<SubjectUpdatedListener> subjectUpdatedListeners = new CopyOnWriteArraySet<SubjectUpdatedListener>(); 127 private final Set<UserStatusListener> userStatusListeners = new CopyOnWriteArraySet<UserStatusListener>(); 128 private final Set<ParticipantStatusListener> participantStatusListeners = new CopyOnWriteArraySet<ParticipantStatusListener>(); 129 private final Set<MessageListener> messageListeners = new CopyOnWriteArraySet<MessageListener>(); 130 private final Set<PresenceListener> presenceListeners = new CopyOnWriteArraySet<PresenceListener>(); 131 private final Set<Consumer<PresenceBuilder>> presenceInterceptors = new CopyOnWriteArraySet<>(); 132 133 /** 134 * This filter will match all stanzas send from the groupchat or from one if 135 * the groupchat participants, i.e. it filters only the bare JID of the from 136 * attribute against the JID of the MUC. 137 */ 138 private final StanzaFilter fromRoomFilter; 139 140 /** 141 * Same as {@link #fromRoomFilter} together with {@link MessageTypeFilter#GROUPCHAT}. 142 */ 143 private final StanzaFilter fromRoomGroupchatFilter; 144 145 private final AtomicInteger presenceInterceptorCount = new AtomicInteger(); 146 // We want to save the presence interceptor in a variable, using a lambda, (and not use a method reference) to be 147 // able to dynamically add and remove it from the connection. 148 @SuppressWarnings("UnnecessaryLambda") 149 private final Consumer<PresenceBuilder> presenceInterceptor = presenceBuilder -> { 150 for (Consumer<PresenceBuilder> interceptor : presenceInterceptors) { 151 interceptor.accept(presenceBuilder); 152 } 153 }; 154 155 private final StanzaListener messageListener; 156 private final StanzaListener presenceListener; 157 private final StanzaListener subjectListener; 158 159 private static final StanzaFilter DECLINE_FILTER = new AndFilter(MessageTypeFilter.NORMAL, 160 new StanzaExtensionFilter(MUCUser.ELEMENT, MUCUser.NAMESPACE)); 161 private final StanzaListener declinesListener; 162 163 private String subject; 164 private EntityFullJid myRoomJid; 165 private StanzaCollector messageCollector; 166 167 private DiscoverInfo mucServiceDiscoInfo; 168 169 /** 170 * Used to signal that the reflected self-presence was received <b>and</b> processed by us. 171 */ 172 private volatile boolean processedReflectedSelfPresence; 173 174 private CopyOnWriteArrayList<MucMessageInterceptor> messageInterceptors; 175 176 MultiUserChat(XMPPConnection connection, EntityBareJid room, MultiUserChatManager multiUserChatManager) { 177 this.connection = connection; 178 this.room = room; 179 this.multiUserChatManager = multiUserChatManager; 180 this.messageInterceptors = MultiUserChatManager.getMessageInterceptors(); 181 182 fromRoomFilter = FromMatchesFilter.create(room); 183 fromRoomGroupchatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT); 184 185 messageListener = new StanzaListener() { 186 @Override 187 public void processStanza(Stanza packet) throws NotConnectedException { 188 final Message message = (Message) packet; 189 190 for (MessageListener listener : messageListeners) { 191 listener.processMessage(message); 192 } 193 } 194 }; 195 196 // Create a listener for subject updates. 197 subjectListener = new StanzaListener() { 198 @Override 199 public void processStanza(Stanza packet) { 200 final Message msg = (Message) packet; 201 final EntityFullJid from = msg.getFrom().asEntityFullJidIfPossible(); 202 // Update the room subject 203 subject = msg.getSubject(); 204 205 // Fire event for subject updated listeners 206 for (SubjectUpdatedListener listener : subjectUpdatedListeners) { 207 listener.subjectUpdated(msg.getSubject(), from); 208 } 209 } 210 }; 211 212 // Create a listener for all presence updates. 213 presenceListener = new StanzaListener() { 214 @Override 215 public void processStanza(final Stanza packet) { 216 final Presence presence = (Presence) packet; 217 final EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible(); 218 if (from == null) { 219 return; 220 } 221 final EntityFullJid myRoomJID = getMyRoomJid(); 222 final boolean isUserStatusModification = presence.getFrom().equals(myRoomJID); 223 final MUCUser mucUser = MUCUser.from(packet); 224 225 switch (presence.getType()) { 226 case available: 227 if (!processedReflectedSelfPresence 228 && mucUser.getStatus().contains(MUCUser.Status.PRESENCE_TO_SELF_110)) { 229 processedReflectedSelfPresence = true; 230 synchronized (this) { 231 notify(); 232 } 233 } 234 235 Presence oldPresence = occupantsMap.put(from, presence); 236 if (oldPresence != null) { 237 // Get the previous occupant's affiliation & role 238 MUCUser mucExtension = MUCUser.from(oldPresence); 239 MUCAffiliation oldAffiliation = mucExtension.getItem().getAffiliation(); 240 MUCRole oldRole = mucExtension.getItem().getRole(); 241 // Get the new occupant's affiliation & role 242 MUCAffiliation newAffiliation = mucUser.getItem().getAffiliation(); 243 MUCRole newRole = mucUser.getItem().getRole(); 244 // Fire role modification events 245 checkRoleModifications(oldRole, newRole, isUserStatusModification, from); 246 // Fire affiliation modification events 247 checkAffiliationModifications( 248 oldAffiliation, 249 newAffiliation, 250 isUserStatusModification, 251 from); 252 } else { 253 // A new occupant has joined the room 254 for (ParticipantStatusListener listener : participantStatusListeners) { 255 listener.joined(from); 256 } 257 } 258 break; 259 case unavailable: 260 occupantsMap.remove(from); 261 Set<Status> status = mucUser.getStatus(); 262 if (mucUser != null && !status.isEmpty()) { 263 if (isUserStatusModification && !status.contains(MUCUser.Status.NEW_NICKNAME_303)) { 264 userHasLeft(); 265 } 266 // Fire events according to the received presence code 267 checkPresenceCode( 268 status, 269 isUserStatusModification, 270 mucUser, 271 from); 272 } else { 273 // An occupant has left the room 274 if (!isUserStatusModification) { 275 for (ParticipantStatusListener listener : participantStatusListeners) { 276 listener.left(from); 277 } 278 } 279 } 280 281 Destroy destroy = mucUser == null ? null : mucUser.getDestroy(); 282 // The room has been destroyed. 283 if (destroy != null) { 284 EntityBareJid alternateMucJid = destroy.getJid(); 285 final MultiUserChat alternateMuc; 286 if (alternateMucJid == null) { 287 alternateMuc = null; 288 } else { 289 alternateMuc = multiUserChatManager.getMultiUserChat(alternateMucJid); 290 } 291 292 for (UserStatusListener listener : userStatusListeners) { 293 listener.roomDestroyed(alternateMuc, destroy.getPassword(), destroy.getReason()); 294 } 295 userHasLeft(); 296 } 297 298 if (isUserStatusModification) { 299 for (UserStatusListener listener : userStatusListeners) { 300 listener.removed(mucUser, presence); 301 } 302 } else { 303 for (ParticipantStatusListener listener : participantStatusListeners) { 304 listener.parted(from); 305 } 306 } 307 break; 308 default: 309 break; 310 } 311 for (PresenceListener listener : presenceListeners) { 312 listener.processPresence(presence); 313 } 314 } 315 }; 316 317 // Listens for all messages that include a MUCUser extension and fire the invitation 318 // rejection listeners if the message includes an invitation rejection. 319 declinesListener = new StanzaListener() { 320 @Override 321 public void processStanza(Stanza packet) { 322 Message message = (Message) packet; 323 // Get the MUC User extension 324 MUCUser mucUser = MUCUser.from(packet); 325 MUCUser.Decline rejection = mucUser.getDecline(); 326 // Check if the MUCUser informs that the invitee has declined the invitation 327 if (rejection == null) { 328 return; 329 } 330 // Fire event for invitation rejection listeners 331 fireInvitationRejectionListeners(message, rejection); 332 } 333 }; 334 } 335 336 337 /** 338 * Returns the name of the room this MultiUserChat object represents. 339 * 340 * @return the multi user chat room name. 341 */ 342 public EntityBareJid getRoom() { 343 return room; 344 } 345 346 /** 347 * Enter a room, as described in XEP-45 7.2. 348 * 349 * @param conf the configuration used to enter the room. 350 * @return the returned presence by the service after the client send the initial presence in order to enter the room. 351 * @throws NotConnectedException if the XMPP connection is not connected. 352 * @throws NoResponseException if there was no response from the remote entity. 353 * @throws XMPPErrorException if there was an XMPP error returned. 354 * @throws InterruptedException if the calling thread was interrupted. 355 * @throws NotAMucServiceException if the entity is not a MUC service. 356 * @see <a href="http://xmpp.org/extensions/xep-0045.html#enter">XEP-45 7.2 Entering a Room</a> 357 */ 358 private Presence enter(MucEnterConfiguration conf) throws NotConnectedException, NoResponseException, 359 XMPPErrorException, InterruptedException, NotAMucServiceException { 360 final DomainBareJid mucService = room.asDomainBareJid(); 361 mucServiceDiscoInfo = multiUserChatManager.getMucServiceDiscoInfo(mucService); 362 if (mucServiceDiscoInfo == null) { 363 throw new NotAMucServiceException(this); 364 } 365 // We enter a room by sending a presence packet where the "to" 366 // field is in the form "roomName@service/nickname" 367 Presence joinPresence = conf.getJoinPresence(this); 368 369 // Set up the messageListeners and presenceListeners *before* the join presence is sent. 370 connection.addStanzaListener(messageListener, fromRoomGroupchatFilter); 371 StanzaFilter presenceFromRoomFilter = new AndFilter(fromRoomFilter, 372 StanzaTypeFilter.PRESENCE, 373 PossibleFromTypeFilter.ENTITY_FULL_JID); 374 connection.addStanzaListener(presenceListener, presenceFromRoomFilter); 375 // @formatter:off 376 connection.addStanzaListener(subjectListener, 377 new AndFilter(fromRoomFilter, 378 MessageWithSubjectFilter.INSTANCE, 379 new NotFilter(MessageTypeFilter.ERROR), 380 // According to XEP-0045 § 8.1 "A message with a <subject/> and a <body/> or a <subject/> and a <thread/> is a 381 // legitimate message, but it SHALL NOT be interpreted as a subject change." 382 new NotFilter(MessageWithBodiesFilter.INSTANCE), 383 new NotFilter(MessageWithThreadFilter.INSTANCE)) 384 ); 385 // @formatter:on 386 connection.addStanzaListener(declinesListener, new AndFilter(fromRoomFilter, DECLINE_FILTER)); 387 messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter); 388 389 // Wait for a presence packet back from the server. 390 // @formatter:off 391 StanzaFilter responseFilter = new AndFilter(StanzaTypeFilter.PRESENCE, 392 new OrFilter( 393 // We use a bare JID filter for positive responses, since the MUC service/room may rewrite the nickname. 394 new AndFilter(FromMatchesFilter.createBare(getRoom()), MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF), 395 // In case there is an error reply, we match on an error presence with the same stanza id and from the full 396 // JID we send the join presence to. 397 new AndFilter(FromMatchesFilter.createFull(joinPresence.getTo()), new StanzaIdFilter(joinPresence), PresenceTypeFilter.ERROR) 398 ) 399 ); 400 // @formatter:on 401 processedReflectedSelfPresence = false; 402 StanzaCollector presenceStanzaCollector = null; 403 final Presence reflectedSelfPresence; 404 try { 405 // This stanza collector will collect the final self presence from the MUC, which also signals that we have successfully entered the MUC. 406 StanzaCollector selfPresenceCollector = connection.createStanzaCollectorAndSend(responseFilter, joinPresence); 407 StanzaCollector.Configuration presenceStanzaCollectorConfiguration = StanzaCollector.newConfiguration().setCollectorToReset( 408 selfPresenceCollector).setStanzaFilter(presenceFromRoomFilter); 409 // This stanza collector is used to reset the timeout of the selfPresenceCollector. 410 presenceStanzaCollector = connection.createStanzaCollector(presenceStanzaCollectorConfiguration); 411 reflectedSelfPresence = selfPresenceCollector.nextResultOrThrow(conf.getTimeout()); 412 } 413 catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) { 414 // Ensure that all callbacks are removed if there is an exception 415 removeConnectionCallbacks(); 416 throw e; 417 } 418 finally { 419 if (presenceStanzaCollector != null) { 420 presenceStanzaCollector.cancel(); 421 } 422 } 423 424 synchronized (presenceListener) { 425 // Only continue after we have received *and* processed the reflected self-presence. Since presences are 426 // handled in an extra listener, we may return from enter() without having processed all presences of the 427 // participants, resulting in a e.g. to low participant counter after enter(). Hence, we wait here until the 428 // processing is done. 429 while (!processedReflectedSelfPresence) { 430 presenceListener.wait(); 431 } 432 } 433 434 // This presence must be sent from a full JID. We use the resourcepart of this JID as nick, since the room may 435 // have performed roomnick rewriting 436 Resourcepart receivedNickname = reflectedSelfPresence.getFrom().getResourceOrThrow(); 437 setNickname(receivedNickname); 438 439 // Update the list of joined rooms 440 multiUserChatManager.addJoinedRoom(room); 441 return reflectedSelfPresence; 442 } 443 444 private void setNickname(Resourcepart nickname) { 445 this.myRoomJid = JidCreate.entityFullFrom(room, nickname); 446 } 447 448 /** 449 * Get a new MUC enter configuration builder. 450 * 451 * @param nickname the nickname used when entering the MUC room. 452 * @return a new MUC enter configuration builder. 453 * @since 4.2 454 */ 455 public MucEnterConfiguration.Builder getEnterConfigurationBuilder(Resourcepart nickname) { 456 return new MucEnterConfiguration.Builder(nickname, connection); 457 } 458 459 /** 460 * Creates the room according to some default configuration, assign the requesting user as the 461 * room owner, and add the owner to the room but not allow anyone else to enter the room 462 * (effectively "locking" the room). The requesting user will join the room under the specified 463 * nickname as soon as the room has been created. 464 * <p> 465 * To create an "Instant Room", that means a room with some default configuration that is 466 * available for immediate access, the room's owner should send an empty form after creating the 467 * room. Simply call {@link MucCreateConfigFormHandle#makeInstant()} on the returned {@link MucCreateConfigFormHandle}. 468 * </p> 469 * <p> 470 * To create a "Reserved Room", that means a room manually configured by the room creator before 471 * anyone is allowed to enter, the room's owner should complete and send a form after creating 472 * the room. Once the completed configuration form is sent to the server, the server will unlock 473 * the room. You can use the returned {@link MucCreateConfigFormHandle} to configure the room. 474 * </p> 475 * 476 * @param nickname the nickname to use. 477 * @return a handle to the MUC create configuration form API. 478 * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if 479 * the user is not allowed to create the room) 480 * @throws NoResponseException if there was no response from the server. 481 * @throws InterruptedException if the calling thread was interrupted. 482 * @throws NotConnectedException if the XMPP connection is not connected. 483 * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y 484 * @throws MissingMucCreationAcknowledgeException if there MUC creation was not acknowledged by the service. 485 * @throws NotAMucServiceException if the entity is not a MUC service. 486 */ 487 public synchronized MucCreateConfigFormHandle create(Resourcepart nickname) throws NoResponseException, 488 XMPPErrorException, InterruptedException, MucAlreadyJoinedException, 489 NotConnectedException, MissingMucCreationAcknowledgeException, NotAMucServiceException { 490 if (isJoined()) { 491 throw new MucAlreadyJoinedException(); 492 } 493 494 MucCreateConfigFormHandle mucCreateConfigFormHandle = createOrJoin(nickname); 495 if (mucCreateConfigFormHandle != null) { 496 // We successfully created a new room 497 return mucCreateConfigFormHandle; 498 } 499 // We need to leave the room since it seems that the room already existed 500 try { 501 leave(); 502 } 503 catch (MucNotJoinedException e) { 504 LOGGER.log(Level.INFO, "Unexpected MucNotJoinedException", e); 505 } 506 throw new MissingMucCreationAcknowledgeException(); 507 } 508 509 /** 510 * Create or join the MUC room with the given nickname. 511 * 512 * @param nickname the nickname to use in the MUC room. 513 * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined. 514 * @throws NoResponseException if there was no response from the remote entity. 515 * @throws XMPPErrorException if there was an XMPP error returned. 516 * @throws InterruptedException if the calling thread was interrupted. 517 * @throws NotConnectedException if the XMPP connection is not connected. 518 * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y 519 * @throws NotAMucServiceException if the entity is not a MUC service. 520 */ 521 public synchronized MucCreateConfigFormHandle createOrJoin(Resourcepart nickname) throws NoResponseException, XMPPErrorException, 522 InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException { 523 MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).build(); 524 return createOrJoin(mucEnterConfiguration); 525 } 526 527 /** 528 * Like {@link #create(Resourcepart)}, but will return a {@link MucCreateConfigFormHandle} if the room creation was acknowledged by 529 * the service (with an 201 status code). It's up to the caller to decide, based on the return 530 * value, if he needs to continue sending the room configuration. If {@code null} is returned, the room 531 * already existed and the user is able to join right away, without sending a form. 532 * 533 * @param mucEnterConfiguration the configuration used to enter the MUC. 534 * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined. 535 * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if 536 * the user is not allowed to create the room) 537 * @throws NoResponseException if there was no response from the server. 538 * @throws InterruptedException if the calling thread was interrupted. 539 * @throws MucAlreadyJoinedException if the MUC is already joined 540 * @throws NotConnectedException if the XMPP connection is not connected. 541 * @throws NotAMucServiceException if the entity is not a MUC service. 542 */ 543 public synchronized MucCreateConfigFormHandle createOrJoin(MucEnterConfiguration mucEnterConfiguration) 544 throws NoResponseException, XMPPErrorException, InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException { 545 if (isJoined()) { 546 throw new MucAlreadyJoinedException(); 547 } 548 549 Presence presence = enter(mucEnterConfiguration); 550 551 // Look for confirmation of room creation from the server 552 MUCUser mucUser = MUCUser.from(presence); 553 if (mucUser != null && mucUser.getStatus().contains(Status.ROOM_CREATED_201)) { 554 // Room was created and the user has joined the room 555 return new MucCreateConfigFormHandle(); 556 } 557 return null; 558 } 559 560 /** 561 * A handle used to configure a newly created room. As long as the room is not configured it will be locked, which 562 * means that no one is able to join. The room will become unlocked as soon it got configured. In order to create an 563 * instant room, use {@link #makeInstant()}. 564 * <p> 565 * For advanced configuration options, use {@link MultiUserChat#getConfigurationForm()}, get the answer form with 566 * {@link Form#getFillableForm()}, fill it out and send it back to the room with 567 * {@link MultiUserChat#sendConfigurationForm(FillableForm)}. 568 * </p> 569 */ 570 public class MucCreateConfigFormHandle { 571 572 /** 573 * Create an instant room. The default configuration will be accepted and the room will become unlocked, i.e. 574 * other users are able to join. 575 * 576 * @throws NoResponseException if there was no response from the remote entity. 577 * @throws XMPPErrorException if there was an XMPP error returned. 578 * @throws NotConnectedException if the XMPP connection is not connected. 579 * @throws InterruptedException if the calling thread was interrupted. 580 * @see <a href="http://www.xmpp.org/extensions/xep-0045.html#createroom-instant">XEP-45 § 10.1.2 Creating an 581 * Instant Room</a> 582 */ 583 public void makeInstant() throws NoResponseException, XMPPErrorException, NotConnectedException, 584 InterruptedException { 585 sendConfigurationForm(null); 586 } 587 588 /** 589 * Alias for {@link MultiUserChat#getConfigFormManager()}. 590 * 591 * @return a MUC configuration form manager for this room. 592 * @throws NoResponseException if there was no response from the remote entity. 593 * @throws XMPPErrorException if there was an XMPP error returned. 594 * @throws NotConnectedException if the XMPP connection is not connected. 595 * @throws InterruptedException if the calling thread was interrupted. 596 * @see MultiUserChat#getConfigFormManager() 597 */ 598 public MucConfigFormManager getConfigFormManager() throws NoResponseException, 599 XMPPErrorException, NotConnectedException, InterruptedException { 600 return MultiUserChat.this.getConfigFormManager(); 601 } 602 } 603 604 /** 605 * Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined. 606 * 607 * @param nickname the required nickname to use. 608 * @param password the optional password required to join 609 * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined. 610 * @throws NoResponseException if there was no response from the remote entity. 611 * @throws XMPPErrorException if there was an XMPP error returned. 612 * @throws NotConnectedException if the XMPP connection is not connected. 613 * @throws InterruptedException if the calling thread was interrupted. 614 * @throws NotAMucServiceException if the entity is not a MUC service. 615 */ 616 public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException, 617 XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException { 618 if (isJoined()) { 619 return null; 620 } 621 MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword( 622 password).build(); 623 try { 624 return createOrJoin(mucEnterConfiguration); 625 } 626 catch (MucAlreadyJoinedException e) { 627 return null; 628 } 629 } 630 631 /** 632 * Joins the chat room using the specified nickname. If already joined 633 * using another nickname, this method will first leave the room and then 634 * re-join using the new nickname. The default connection timeout for a reply 635 * from the group chat server that the join succeeded will be used. After 636 * joining the room, the room will decide the amount of history to send. 637 * 638 * @param nickname the nickname to use. 639 * @return the leave self-presence as reflected by the MUC. 640 * @throws NoResponseException if there was no response from the remote entity. 641 * @throws XMPPErrorException if an error occurs joining the room. In particular, a 642 * 401 error can occur if no password was provided and one is required; or a 643 * 403 error can occur if the user is banned; or a 644 * 404 error can occur if the room does not exist or is locked; or a 645 * 407 error can occur if user is not on the member list; or a 646 * 409 error can occur if someone is already in the group chat with the same nickname. 647 * @throws NoResponseException if there was no response from the server. 648 * @throws NotConnectedException if the XMPP connection is not connected. 649 * @throws InterruptedException if the calling thread was interrupted. 650 * @throws NotAMucServiceException if the entity is not a MUC service. 651 */ 652 public Presence join(Resourcepart nickname) throws NoResponseException, XMPPErrorException, 653 NotConnectedException, InterruptedException, NotAMucServiceException { 654 MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname); 655 Presence reflectedJoinPresence = join(builder.build()); 656 return reflectedJoinPresence; 657 } 658 659 /** 660 * Joins the chat room using the specified nickname and password. If already joined 661 * using another nickname, this method will first leave the room and then 662 * re-join using the new nickname. The default connection timeout for a reply 663 * from the group chat server that the join succeeded will be used. After 664 * joining the room, the room will decide the amount of history to send.<p> 665 * 666 * A password is required when joining password protected rooms. If the room does 667 * not require a password there is no need to provide one. 668 * 669 * @param nickname the nickname to use. 670 * @param password the password to use. 671 * @throws XMPPErrorException if an error occurs joining the room. In particular, a 672 * 401 error can occur if no password was provided and one is required; or a 673 * 403 error can occur if the user is banned; or a 674 * 404 error can occur if the room does not exist or is locked; or a 675 * 407 error can occur if user is not on the member list; or a 676 * 409 error can occur if someone is already in the group chat with the same nickname. 677 * @throws InterruptedException if the calling thread was interrupted. 678 * @throws NotConnectedException if the XMPP connection is not connected. 679 * @throws NoResponseException if there was no response from the server. 680 * @throws NotAMucServiceException if the entity is not a MUC service. 681 */ 682 public void join(Resourcepart nickname, String password) throws XMPPErrorException, InterruptedException, NoResponseException, NotConnectedException, NotAMucServiceException { 683 MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname).withPassword( 684 password); 685 join(builder.build()); 686 } 687 688 /** 689 * Joins the chat room using the specified nickname and password. If already joined 690 * using another nickname, this method will first leave the room and then 691 * re-join using the new nickname.<p> 692 * 693 * To control the amount of history to receive while joining a room you will need to provide 694 * a configured DiscussionHistory object.<p> 695 * 696 * A password is required when joining password protected rooms. If the room does 697 * not require a password there is no need to provide one.<p> 698 * 699 * If the room does not already exist when the user seeks to enter it, the server will 700 * decide to create a new room or not. 701 * 702 * @param mucEnterConfiguration the configuration used to enter the MUC. 703 * @return the join self-presence as reflected by the MUC. 704 * @throws XMPPErrorException if an error occurs joining the room. In particular, a 705 * 401 error can occur if no password was provided and one is required; or a 706 * 403 error can occur if the user is banned; or a 707 * 404 error can occur if the room does not exist or is locked; or a 708 * 407 error can occur if user is not on the member list; or a 709 * 409 error can occur if someone is already in the group chat with the same nickname. 710 * @throws NoResponseException if there was no response from the server. 711 * @throws NotConnectedException if the XMPP connection is not connected. 712 * @throws InterruptedException if the calling thread was interrupted. 713 * @throws NotAMucServiceException if the entity is not a MUC service. 714 */ 715 public synchronized Presence join(MucEnterConfiguration mucEnterConfiguration) 716 throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException, NotAMucServiceException { 717 // If we've already joined the room, leave it before joining under a new 718 // nickname. 719 if (isJoined()) { 720 try { 721 leaveSync(); 722 } 723 catch (XMPPErrorException | NoResponseException | MucNotJoinedException e) { 724 LOGGER.log(Level.WARNING, "Could not leave MUC prior joining, assuming we are not joined", e); 725 } 726 } 727 Presence reflectedJoinPresence = enter(mucEnterConfiguration); 728 return reflectedJoinPresence; 729 } 730 731 /** 732 * Returns true if currently in the multi user chat (after calling the {@link 733 * #join(Resourcepart)} method). 734 * 735 * @return true if currently in the multi user chat room. 736 */ 737 public boolean isJoined() { 738 return getMyRoomJid() != null; 739 } 740 741 /** 742 * Leave the chat room. 743 * 744 * @return the leave presence as reflected by the MUC. 745 * @throws NotConnectedException if the XMPP connection is not connected. 746 * @throws InterruptedException if the calling thread was interrupted. 747 * @throws XMPPErrorException if there was an XMPP error returned. 748 * @throws NoResponseException if there was no response from the remote entity. 749 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 750 * @deprecated use {@link #leave()} instead. 751 */ 752 @Deprecated 753 // TODO: Remove in Smack 4.5. 754 public synchronized Presence leaveSync() throws NotConnectedException, InterruptedException, MucNotJoinedException, NoResponseException, XMPPErrorException { 755 return leave(); 756 } 757 758 /** 759 * Leave the chat room. 760 * 761 * @return the leave presence as reflected by the MUC. 762 * @throws NotConnectedException if the XMPP connection is not connected. 763 * @throws InterruptedException if the calling thread was interrupted. 764 * @throws XMPPErrorException if there was an XMPP error returned. 765 * @throws NoResponseException if there was no response from the remote entity. 766 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 767 */ 768 public synchronized Presence leave() 769 throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException, MucNotJoinedException { 770 // Note that this method is intentionally not guarded by 771 // "if (!joined) return" because it should be always be possible to leave the room in case the instance's 772 // state does not reflect the actual state. 773 774 final EntityFullJid myRoomJid = getMyRoomJid(); 775 if (myRoomJid == null) { 776 throw new MucNotJoinedException(this); 777 } 778 779 // TODO: Consider adding a origin-id to the presence, once it is moved form smack-experimental into 780 // smack-extensions, in case the MUC service does not support stable IDs, and modify 781 // reflectedLeavePresenceFilters accordingly. 782 783 // We leave a room by sending a presence packet where the "to" 784 // field is in the form "roomName@service/nickname" 785 Presence leavePresence = connection.getStanzaFactory().buildPresenceStanza() 786 .ofType(Presence.Type.unavailable) 787 .to(myRoomJid) 788 .build(); 789 790 List<StanzaFilter> reflectedLeavePresenceFilters = new ArrayList<>(3); 791 reflectedLeavePresenceFilters.add(StanzaTypeFilter.PRESENCE); 792 reflectedLeavePresenceFilters.add(new OrFilter( 793 new AndFilter(FromMatchesFilter.createFull(myRoomJid), PresenceTypeFilter.UNAVAILABLE, 794 MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF), 795 new AndFilter(fromRoomFilter, PresenceTypeFilter.ERROR))); 796 797 if (serviceSupportsStableIds()) { 798 reflectedLeavePresenceFilters.add(new StanzaIdFilter(leavePresence)); 799 } 800 801 StanzaFilter reflectedLeavePresenceFilter = new AndFilter(reflectedLeavePresenceFilters); 802 803 Presence reflectedLeavePresence; 804 try { 805 reflectedLeavePresence = connection.createStanzaCollectorAndSend(reflectedLeavePresenceFilter, leavePresence).nextResultOrThrow(); 806 } finally { 807 // Reset occupant information after we send the leave presence. This ensures that we only call userHasLeft() 808 // and reset the local MUC state after we successfully left the MUC (or if an exception occurred). 809 userHasLeft(); 810 } 811 812 return reflectedLeavePresence; 813 } 814 815 /** 816 * Get a {@link MucConfigFormManager} to configure this room. 817 * <p> 818 * Only room owners are able to configure a room. 819 * </p> 820 * 821 * @return a MUC configuration form manager for this room. 822 * @throws NoResponseException if there was no response from the remote entity. 823 * @throws XMPPErrorException if there was an XMPP error returned. 824 * @throws NotConnectedException if the XMPP connection is not connected. 825 * @throws InterruptedException if the calling thread was interrupted. 826 * @see <a href="http://xmpp.org/extensions/xep-0045.html#roomconfig">XEP-45 § 10.2 Subsequent Room Configuration</a> 827 * @since 4.2 828 */ 829 public MucConfigFormManager getConfigFormManager() throws NoResponseException, 830 XMPPErrorException, NotConnectedException, InterruptedException { 831 return new MucConfigFormManager(this); 832 } 833 834 /** 835 * Returns the room's configuration form that the room's owner can use. 836 * The configuration form allows to set the room's language, 837 * enable logging, specify room's type, etc. 838 * 839 * @return the Form that contains the fields to complete together with the instructions or 840 * <code>null</code> if no configuration is possible. 841 * @throws XMPPErrorException if an error occurs asking the configuration form for the room. 842 * @throws NoResponseException if there was no response from the server. 843 * @throws NotConnectedException if the XMPP connection is not connected. 844 * @throws InterruptedException if the calling thread was interrupted. 845 */ 846 public Form getConfigurationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 847 MUCOwner iq = new MUCOwner(); 848 iq.setTo(room); 849 iq.setType(IQ.Type.get); 850 851 IQ answer = connection.sendIqRequestAndWaitForResponse(iq); 852 DataForm dataForm = DataForm.from(answer, MucConfigFormManager.FORM_TYPE); 853 return new Form(dataForm); 854 } 855 856 /** 857 * Sends the completed configuration form to the server. The room will be configured 858 * with the new settings defined in the form. 859 * 860 * @param form the form with the new settings. 861 * @throws XMPPErrorException if an error occurs setting the new rooms' configuration. 862 * @throws NoResponseException if there was no response from the server. 863 * @throws NotConnectedException if the XMPP connection is not connected. 864 * @throws InterruptedException if the calling thread was interrupted. 865 */ 866 public void sendConfigurationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 867 final DataForm dataForm; 868 if (form != null) { 869 dataForm = form.getDataFormToSubmit(); 870 } else { 871 // Instant room, cf. XEP-0045 § 10.1.2 872 dataForm = DataForm.builder().build(); 873 } 874 875 MUCOwner iq = new MUCOwner(); 876 iq.setTo(room); 877 iq.setType(IQ.Type.set); 878 iq.addExtension(dataForm); 879 880 connection.sendIqRequestAndWaitForResponse(iq); 881 } 882 883 /** 884 * Returns the room's registration form that an unaffiliated user, can use to become a member 885 * of the room or <code>null</code> if no registration is possible. Some rooms may restrict the 886 * privilege to register members and allow only room admins to add new members.<p> 887 * 888 * If the user requesting registration requirements is not allowed to register with the room 889 * (e.g. because that privilege has been restricted), the room will return a "Not Allowed" 890 * error to the user (error code 405). 891 * 892 * @return the registration Form that contains the fields to complete together with the 893 * instructions or <code>null</code> if no registration is possible. 894 * @throws XMPPErrorException if an error occurs asking the registration form for the room or a 895 * 405 error if the user is not allowed to register with the room. 896 * @throws NoResponseException if there was no response from the server. 897 * @throws NotConnectedException if the XMPP connection is not connected. 898 * @throws InterruptedException if the calling thread was interrupted. 899 */ 900 public Form getRegistrationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 901 Registration reg = new Registration(); 902 reg.setType(IQ.Type.get); 903 reg.setTo(room); 904 905 IQ result = connection.sendIqRequestAndWaitForResponse(reg); 906 DataForm dataForm = DataForm.from(result); 907 return new Form(dataForm); 908 } 909 910 /** 911 * Sends the completed registration form to the server. After the user successfully submits 912 * the form, the room may queue the request for review by the room admins or may immediately 913 * add the user to the member list by changing the user's affiliation from "none" to "member.<p> 914 * 915 * If the desired room nickname is already reserved for that room, the room will return a 916 * "Conflict" error to the user (error code 409). If the room does not support registration, 917 * it will return a "Service Unavailable" error to the user (error code 503). 918 * 919 * @param form the completed registration form. 920 * @throws XMPPErrorException if an error occurs submitting the registration form. In particular, a 921 * 409 error can occur if the desired room nickname is already reserved for that room; 922 * or a 503 error can occur if the room does not support registration. 923 * @throws NoResponseException if there was no response from the server. 924 * @throws NotConnectedException if the XMPP connection is not connected. 925 * @throws InterruptedException if the calling thread was interrupted. 926 */ 927 public void sendRegistrationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 928 Registration reg = new Registration(); 929 reg.setType(IQ.Type.set); 930 reg.setTo(room); 931 reg.addExtension(form.getDataFormToSubmit()); 932 933 connection.sendIqRequestAndWaitForResponse(reg); 934 } 935 936 /** 937 * Sends a request to destroy the room. 938 * 939 * @throws XMPPErrorException if an error occurs while trying to destroy the room. 940 * An error can occur which will be wrapped by an XMPPException -- 941 * XMPP error code 403. The error code can be used to present more 942 * appropriate error messages to end-users. 943 * @throws NoResponseException if there was no response from the server. 944 * @throws NotConnectedException if the XMPP connection is not connected. 945 * @throws InterruptedException if the calling thread was interrupted. 946 * @see #destroy(String, EntityBareJid) 947 * @since 4.5 948 */ 949 public void destroy() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 950 destroy(null, null); 951 } 952 953 /** 954 * Sends a request to the server to destroy the room. The sender of the request 955 * should be the room's owner. If the sender of the destroy request is not the room's owner 956 * then the server will answer a "Forbidden" error (403). 957 * 958 * @param reason an optional reason for the room destruction. 959 * @param alternateJID an optional JID of an alternate location. 960 * @throws XMPPErrorException if an error occurs while trying to destroy the room. 961 * An error can occur which will be wrapped by an XMPPException -- 962 * XMPP error code 403. The error code can be used to present more 963 * appropriate error messages to end-users. 964 * @throws NoResponseException if there was no response from the server. 965 * @throws NotConnectedException if the XMPP connection is not connected. 966 * @throws InterruptedException if the calling thread was interrupted. 967 */ 968 public void destroy(String reason, EntityBareJid alternateJID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 969 destroy(reason, alternateJID, null); 970 } 971 972 /** 973 * Sends a request to the server to destroy the room. The sender of the request 974 * should be the room's owner. If the sender of the destroy request is not the room's owner 975 * then the server will answer a "Forbidden" error (403). 976 * 977 * @param reason an optional reason for the room destruction. 978 * @param alternateJID an optional JID of an alternate location. 979 * @param password an optional password for the alternate location 980 * @throws XMPPErrorException if an error occurs while trying to destroy the room. 981 * An error can occur which will be wrapped by an XMPPException -- 982 * XMPP error code 403. The error code can be used to present more 983 * appropriate error messages to end-users. 984 * @throws NoResponseException if there was no response from the server. 985 * @throws NotConnectedException if the XMPP connection is not connected. 986 * @throws InterruptedException if the calling thread was interrupted. 987 */ 988 public void destroy(String reason, EntityBareJid alternateJID, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 989 MUCOwner iq = new MUCOwner(); 990 iq.setTo(room); 991 iq.setType(IQ.Type.set); 992 993 // Create the reason for the room destruction 994 Destroy destroy = new Destroy(alternateJID, password, reason); 995 iq.setDestroy(destroy); 996 997 try { 998 connection.sendIqRequestAndWaitForResponse(iq); 999 } 1000 catch (XMPPErrorException e) { 1001 // Note that we do not call userHasLeft() here because an XMPPErrorException would usually indicate that the 1002 // room was not destroyed and we therefore we also did not leave the room. 1003 throw e; 1004 } 1005 catch (NoResponseException | NotConnectedException | InterruptedException e) { 1006 // Reset occupant information. 1007 userHasLeft(); 1008 throw e; 1009 } 1010 1011 // Reset occupant information. 1012 userHasLeft(); 1013 } 1014 1015 /** 1016 * Invites another user to the room in which one is an occupant. The invitation 1017 * will be sent to the room which in turn will forward the invitation to the invitee.<p> 1018 * 1019 * If the room is password-protected, the invitee will receive a password to use to join 1020 * the room. If the room is members-only, the invitee may be added to the member list. 1021 * 1022 * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit) 1023 * @param reason the reason why the user is being invited. 1024 * @throws NotConnectedException if the XMPP connection is not connected. 1025 * @throws InterruptedException if the calling thread was interrupted. 1026 */ 1027 public void invite(EntityBareJid user, String reason) throws NotConnectedException, InterruptedException { 1028 invite(connection.getStanzaFactory().buildMessageStanza(), user, reason); 1029 } 1030 1031 /** 1032 * Invites another user to the room in which one is an occupant using a given Message. The invitation 1033 * will be sent to the room which in turn will forward the invitation to the invitee.<p> 1034 * 1035 * If the room is password-protected, the invitee will receive a password to use to join 1036 * the room. If the room is members-only, the invitee may be added to the member list. 1037 * 1038 * @param message the message to use for sending the invitation. 1039 * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit) 1040 * @param reason the reason why the user is being invited. 1041 * @throws NotConnectedException if the XMPP connection is not connected. 1042 * @throws InterruptedException if the calling thread was interrupted. 1043 * @deprecated use {@link #invite(MessageBuilder, EntityBareJid, String)} instead. 1044 */ 1045 @Deprecated 1046 // TODO: Remove in Smack 4.5. 1047 public void invite(Message message, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException { 1048 // TODO listen for 404 error code when inviter supplies a non-existent JID 1049 message.setTo(room); 1050 1051 // Create the MUCUser packet that will include the invitation 1052 MUCUser mucUser = new MUCUser(); 1053 MUCUser.Invite invite = new MUCUser.Invite(reason, user); 1054 mucUser.setInvite(invite); 1055 // Add the MUCUser packet that includes the invitation to the message 1056 message.addExtension(mucUser); 1057 1058 connection.sendStanza(message); 1059 } 1060 1061 /** 1062 * Invites another user to the room in which one is an occupant using a given Message. The invitation 1063 * will be sent to the room which in turn will forward the invitation to the invitee.<p> 1064 * 1065 * If the room is password-protected, the invitee will receive a password to use to join 1066 * the room. If the room is members-only, the invitee may be added to the member list. 1067 * 1068 * @param messageBuilder the message to use for sending the invitation. 1069 * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit) 1070 * @param reason the reason why the user is being invited. 1071 * @throws NotConnectedException if the XMPP connection is not connected. 1072 * @throws InterruptedException if the calling thread was interrupted. 1073 */ 1074 public void invite(MessageBuilder messageBuilder, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException { 1075 // TODO listen for 404 error code when inviter supplies a non-existent JID 1076 messageBuilder.to(room); 1077 1078 // Create the MUCUser packet that will include the invitation 1079 MUCUser mucUser = new MUCUser(); 1080 MUCUser.Invite invite = new MUCUser.Invite(reason, user); 1081 mucUser.setInvite(invite); 1082 // Add the MUCUser packet that includes the invitation to the message 1083 messageBuilder.addExtension(mucUser); 1084 1085 Message message = messageBuilder.build(); 1086 connection.sendStanza(message); 1087 } 1088 1089 /** 1090 * Invites another user to the room in which one is an occupant. In contrast 1091 * to the method "invite", the invitation is sent directly to the user rather 1092 * than via the chat room. This is useful when the user being invited is 1093 * offline, as otherwise the invitation would be dropped. 1094 * 1095 * @param address the user to send the invitation to 1096 * @throws NotConnectedException if the XMPP connection is not connected. 1097 * @throws InterruptedException if the calling thread was interrupted. 1098 */ 1099 public void inviteDirectly(EntityBareJid address) throws NotConnectedException, InterruptedException { 1100 inviteDirectly(address, null, null, false, null); 1101 } 1102 1103 /** 1104 * Invites another user to the room in which one is an occupant. In contrast 1105 * to the method "invite", the invitation is sent directly to the user rather 1106 * than via the chat room. This is useful when the user being invited is 1107 * offline, as otherwise the invitation would be dropped. 1108 * 1109 * @param address the user to send the invitation to 1110 * @param reason the purpose for the invitation 1111 * @param password specifies a password needed for entry 1112 * @param continueAsOneToOneChat specifies if the groupchat room continues a one-to-one chat having the designated thread 1113 * @param thread the thread to continue 1114 * @throws NotConnectedException if the XMPP connection is not connected. 1115 * @throws InterruptedException if the calling thread was interrupted. 1116 */ 1117 public void inviteDirectly(EntityBareJid address, String reason, String password, boolean continueAsOneToOneChat, String thread) 1118 throws NotConnectedException, InterruptedException { 1119 // Add the extension for direct invitation 1120 GroupChatInvitation invitationExt = new GroupChatInvitation(room, 1121 reason, 1122 password, 1123 continueAsOneToOneChat, 1124 thread); 1125 1126 Message message = connection.getStanzaFactory().buildMessageStanza() 1127 .to(address) 1128 .addExtension(invitationExt) 1129 .build(); 1130 1131 connection.sendStanza(message); 1132 } 1133 1134 /** 1135 * Adds a listener to invitation rejections notifications. The listener will be fired anytime 1136 * an invitation is declined. 1137 * 1138 * @param listener an invitation rejection listener. 1139 * @return true if the listener was not already added. 1140 */ 1141 public boolean addInvitationRejectionListener(InvitationRejectionListener listener) { 1142 return invitationRejectionListeners.add(listener); 1143 } 1144 1145 /** 1146 * Removes a listener from invitation rejections notifications. The listener will be fired 1147 * anytime an invitation is declined. 1148 * 1149 * @param listener an invitation rejection listener. 1150 * @return true if the listener was registered and is now removed. 1151 */ 1152 public boolean removeInvitationRejectionListener(InvitationRejectionListener listener) { 1153 return invitationRejectionListeners.remove(listener); 1154 } 1155 1156 /** 1157 * Fires invitation rejection listeners. 1158 * 1159 * @param message the message. 1160 * @param rejection the information about the rejection. 1161 */ 1162 private void fireInvitationRejectionListeners(Message message, MUCUser.Decline rejection) { 1163 EntityBareJid invitee = rejection.getFrom(); 1164 String reason = rejection.getReason(); 1165 InvitationRejectionListener[] listeners; 1166 synchronized (invitationRejectionListeners) { 1167 listeners = new InvitationRejectionListener[invitationRejectionListeners.size()]; 1168 invitationRejectionListeners.toArray(listeners); 1169 } 1170 for (InvitationRejectionListener listener : listeners) { 1171 listener.invitationDeclined(invitee, reason, message, rejection); 1172 } 1173 } 1174 1175 /** 1176 * Adds a listener to subject change notifications. The listener will be fired anytime 1177 * the room's subject changes. 1178 * 1179 * @param listener a subject updated listener. 1180 * @return true if the listener was not already added. 1181 */ 1182 public boolean addSubjectUpdatedListener(SubjectUpdatedListener listener) { 1183 return subjectUpdatedListeners.add(listener); 1184 } 1185 1186 /** 1187 * Removes a listener from subject change notifications. The listener will be fired 1188 * anytime the room's subject changes. 1189 * 1190 * @param listener a subject updated listener. 1191 * @return true if the listener was registered and is now removed. 1192 */ 1193 public boolean removeSubjectUpdatedListener(SubjectUpdatedListener listener) { 1194 return subjectUpdatedListeners.remove(listener); 1195 } 1196 1197 /** 1198 * Adds a new {@link StanzaListener} that will be invoked every time a new presence 1199 * is going to be sent by this MultiUserChat to the server. Stanza interceptors may 1200 * add new extensions to the presence that is going to be sent to the MUC service. 1201 * 1202 * @param presenceInterceptor the new stanza interceptor that will intercept presence packets. 1203 */ 1204 public void addPresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor) { 1205 boolean added = presenceInterceptors.add(presenceInterceptor); 1206 if (!added) return; 1207 int currentCount = presenceInterceptorCount.incrementAndGet(); 1208 if (currentCount == 1) { 1209 connection.addPresenceInterceptor(this.presenceInterceptor, ToMatchesFilter.create(room).asPredicate(Presence.class)); 1210 } 1211 } 1212 1213 /** 1214 * Removes a {@link StanzaListener} that was being invoked every time a new presence 1215 * was being sent by this MultiUserChat to the server. Stanza interceptors may 1216 * add new extensions to the presence that is going to be sent to the MUC service. 1217 * 1218 * @param presenceInterceptor the stanza interceptor to remove. 1219 */ 1220 public void removePresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor) { 1221 boolean removed = presenceInterceptors.remove(presenceInterceptor); 1222 if (!removed) return; 1223 int currentCount = presenceInterceptorCount.decrementAndGet(); 1224 if (currentCount == 0) { 1225 connection.removePresenceInterceptor(this.presenceInterceptor); 1226 } 1227 } 1228 1229 /** 1230 * Returns the last known room's subject or <code>null</code> if the user hasn't joined the room 1231 * or the room does not have a subject yet. In case the room has a subject, as soon as the 1232 * user joins the room a message with the current room's subject will be received.<p> 1233 * 1234 * To be notified every time the room's subject change you should add a listener 1235 * to this room. {@link #addSubjectUpdatedListener(SubjectUpdatedListener)}<p> 1236 * 1237 * To change the room's subject use {@link #changeSubject(String)}. 1238 * 1239 * @return the room's subject or <code>null</code> if the user hasn't joined the room or the 1240 * room does not have a subject yet. 1241 */ 1242 public String getSubject() { 1243 return subject; 1244 } 1245 1246 /** 1247 * Returns the reserved room nickname for the user in the room. A user may have a reserved 1248 * nickname, for example through explicit room registration or database integration. In such 1249 * cases it may be desirable for the user to discover the reserved nickname before attempting 1250 * to enter the room. 1251 * 1252 * @return the reserved room nickname or <code>null</code> if none. 1253 * @throws SmackException if there was no response from the server. 1254 * @throws InterruptedException if the calling thread was interrupted. 1255 */ 1256 public String getReservedNickname() throws SmackException, InterruptedException { 1257 try { 1258 DiscoverInfo result = 1259 ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo( 1260 room, 1261 "x-roomuser-item"); 1262 // Look for an Identity that holds the reserved nickname and return its name 1263 for (DiscoverInfo.Identity identity : result.getIdentities()) { 1264 return identity.getName(); 1265 } 1266 } 1267 catch (XMPPException e) { 1268 LOGGER.log(Level.SEVERE, "Error retrieving room nickname", e); 1269 } 1270 // If no Identity was found then the user does not have a reserved room nickname 1271 return null; 1272 } 1273 1274 /** 1275 * Returns the nickname that was used to join the room, or <code>null</code> if not 1276 * currently joined. 1277 * 1278 * @return the nickname currently being used. 1279 */ 1280 public Resourcepart getNickname() { 1281 final EntityFullJid myRoomJid = getMyRoomJid(); 1282 if (myRoomJid == null) { 1283 return null; 1284 } 1285 return myRoomJid.getResourcepart(); 1286 } 1287 1288 /** 1289 * Return the full JID of the user in the room, or <code>null</code> if the room is not joined. 1290 * 1291 * @return the full JID of the user in the room, or <code>null</code>. 1292 * @since 4.5.0 1293 */ 1294 public EntityFullJid getMyRoomJid() { 1295 return myRoomJid; 1296 } 1297 1298 private static final Object changeNicknameLock = new Object(); 1299 1300 /** 1301 * Changes the occupant's nickname to a new nickname within the room. Each room occupant 1302 * will receive two presence packets. One of type "unavailable" for the old nickname and one 1303 * indicating availability for the new nickname. The unavailable presence will contain the new 1304 * nickname and an appropriate status code (namely 303) as extended presence information. The 1305 * status code 303 indicates that the occupant is changing his/her nickname. 1306 * 1307 * @param nickname the new nickname within the room. 1308 * @throws XMPPErrorException if the new nickname is already in use by another occupant. 1309 * @throws NoResponseException if there was no response from the server. 1310 * @throws NotConnectedException if the XMPP connection is not connected. 1311 * @throws InterruptedException if the calling thread was interrupted. 1312 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 1313 */ 1314 public void changeNickname(Resourcepart nickname) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException { 1315 Objects.requireNonNull(nickname, "Nickname must not be null or blank."); 1316 // Check that we already have joined the room before attempting to change the 1317 // nickname. 1318 if (!isJoined()) { 1319 throw new MucNotJoinedException(this); 1320 } 1321 final EntityFullJid jid = JidCreate.entityFullFrom(room, nickname); 1322 // We change the nickname by sending a presence packet where the "to" 1323 // field is in the form "roomName@service/nickname" 1324 // We don't have to signal the MUC support again 1325 Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza() 1326 .to(jid) 1327 .ofType(Presence.Type.available) 1328 .build(); 1329 1330 synchronized (changeNicknameLock) { 1331 // Wait for a presence packet back from the server. 1332 StanzaFilter responseFilter = 1333 new AndFilter( 1334 FromMatchesFilter.createFull(jid), 1335 new StanzaTypeFilter(Presence.class)); 1336 StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, joinPresence); 1337 // Wait up to a certain number of seconds for a reply. If there is a negative reply, an 1338 // exception will be thrown 1339 response.nextResultOrThrow(); 1340 1341 // TODO: Shouldn't this handle nickname rewriting by the MUC service? 1342 setNickname(nickname); 1343 } 1344 } 1345 1346 /** 1347 * Changes the occupant's availability status within the room. The presence type 1348 * will remain available but with a new status that describes the presence update and 1349 * a new presence mode (e.g. Extended away). 1350 * 1351 * @param status a text message describing the presence update. 1352 * @param mode the mode type for the presence update. 1353 * @throws NotConnectedException if the XMPP connection is not connected. 1354 * @throws InterruptedException if the calling thread was interrupted. 1355 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 1356 */ 1357 public void changeAvailabilityStatus(String status, Presence.Mode mode) throws NotConnectedException, InterruptedException, MucNotJoinedException { 1358 final EntityFullJid myRoomJid = getMyRoomJid(); 1359 if (myRoomJid == null) { 1360 throw new MucNotJoinedException(this); 1361 } 1362 1363 // We change the availability status by sending a presence packet to the room with the 1364 // new presence status and mode 1365 Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza() 1366 .to(myRoomJid) 1367 .ofType(Presence.Type.available) 1368 .setStatus(status) 1369 .setMode(mode) 1370 .build(); 1371 1372 // Send join packet. 1373 connection.sendStanza(joinPresence); 1374 } 1375 1376 /** 1377 * Kicks a visitor or participant from the room. The kicked occupant will receive a presence 1378 * of type "unavailable" including a status code 307 and optionally along with the reason 1379 * (if provided) and the bare JID of the user who initiated the kick. After the occupant 1380 * was kicked from the room, the rest of the occupants will receive a presence of type 1381 * "unavailable". The presence will include a status code 307 which means that the occupant 1382 * was kicked from the room. 1383 * 1384 * @param nickname the nickname of the participant or visitor to kick from the room 1385 * (e.g. "john"). 1386 * @param reason the reason why the participant or visitor is being kicked from the room. 1387 * @throws XMPPErrorException if an error occurs kicking the occupant. In particular, a 1388 * 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin" 1389 * was intended to be kicked (i.e. Not Allowed error); or a 1390 * 403 error can occur if the occupant that intended to kick another occupant does 1391 * not have kicking privileges (i.e. Forbidden error); or a 1392 * 400 error can occur if the provided nickname is not present in the room. 1393 * @throws NoResponseException if there was no response from the server. 1394 * @throws NotConnectedException if the XMPP connection is not connected. 1395 * @throws InterruptedException if the calling thread was interrupted. 1396 */ 1397 public void kickParticipant(Resourcepart nickname, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1398 changeRole(nickname, MUCRole.none, reason); 1399 } 1400 1401 /** 1402 * Sends a voice request to the MUC. The room moderators usually need to approve this request. 1403 * 1404 * @throws NotConnectedException if the XMPP connection is not connected. 1405 * @throws InterruptedException if the calling thread was interrupted. 1406 * @see <a href="http://xmpp.org/extensions/xep-0045.html#requestvoice">XEP-45 § 7.13 Requesting 1407 * Voice</a> 1408 * @since 4.1 1409 */ 1410 public void requestVoice() throws NotConnectedException, InterruptedException { 1411 DataForm.Builder form = DataForm.builder() 1412 .setFormType(MUCInitialPresence.NAMESPACE + "#request"); 1413 1414 TextSingleFormField.Builder requestVoiceField = FormField.textSingleBuilder("muc#role"); 1415 requestVoiceField.setLabel("Requested role"); 1416 requestVoiceField.setValue("participant"); 1417 form.addField(requestVoiceField.build()); 1418 1419 Message message = connection.getStanzaFactory().buildMessageStanza() 1420 .to(room) 1421 .addExtension(form.build()) 1422 .build(); 1423 connection.sendStanza(message); 1424 } 1425 1426 /** 1427 * Grants voice to visitors in the room. In a moderated room, a moderator may want to manage 1428 * who does and does not have "voice" in the room. To have voice means that a room occupant 1429 * is able to send messages to the room occupants. 1430 * 1431 * @param nicknames the nicknames of the visitors to grant voice in the room (e.g. "john"). 1432 * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a 1433 * 403 error can occur if the occupant that intended to grant voice is not 1434 * a moderator in this room (i.e. Forbidden error); or a 1435 * 400 error can occur if the provided nickname is not present in the room. 1436 * @throws NoResponseException if there was no response from the server. 1437 * @throws NotConnectedException if the XMPP connection is not connected. 1438 * @throws InterruptedException if the calling thread was interrupted. 1439 */ 1440 public void grantVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1441 changeRole(nicknames, MUCRole.participant); 1442 } 1443 1444 /** 1445 * Grants voice to a visitor in the room. In a moderated room, a moderator may want to manage 1446 * who does and does not have "voice" in the room. To have voice means that a room occupant 1447 * is able to send messages to the room occupants. 1448 * 1449 * @param nickname the nickname of the visitor to grant voice in the room (e.g. "john"). 1450 * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a 1451 * 403 error can occur if the occupant that intended to grant voice is not 1452 * a moderator in this room (i.e. Forbidden error); or a 1453 * 400 error can occur if the provided nickname is not present in the room. 1454 * @throws NoResponseException if there was no response from the server. 1455 * @throws NotConnectedException if the XMPP connection is not connected. 1456 * @throws InterruptedException if the calling thread was interrupted. 1457 */ 1458 public void grantVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1459 changeRole(nickname, MUCRole.participant, null); 1460 } 1461 1462 /** 1463 * Revokes voice from participants in the room. In a moderated room, a moderator may want to 1464 * revoke an occupant's privileges to speak. To have voice means that a room occupant 1465 * is able to send messages to the room occupants. 1466 * 1467 * @param nicknames the nicknames of the participants to revoke voice (e.g. "john"). 1468 * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a 1469 * 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin" 1470 * was tried to revoke his voice (i.e. Not Allowed error); or a 1471 * 400 error can occur if the provided nickname is not present in the room. 1472 * @throws NoResponseException if there was no response from the server. 1473 * @throws NotConnectedException if the XMPP connection is not connected. 1474 * @throws InterruptedException if the calling thread was interrupted. 1475 */ 1476 public void revokeVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1477 changeRole(nicknames, MUCRole.visitor); 1478 } 1479 1480 /** 1481 * Revokes voice from a participant in the room. In a moderated room, a moderator may want to 1482 * revoke an occupant's privileges to speak. To have voice means that a room occupant 1483 * is able to send messages to the room occupants. 1484 * 1485 * @param nickname the nickname of the participant to revoke voice (e.g. "john"). 1486 * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a 1487 * 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin" 1488 * was tried to revoke his voice (i.e. Not Allowed error); or a 1489 * 400 error can occur if the provided nickname is not present in the room. 1490 * @throws NoResponseException if there was no response from the server. 1491 * @throws NotConnectedException if the XMPP connection is not connected. 1492 * @throws InterruptedException if the calling thread was interrupted. 1493 */ 1494 public void revokeVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1495 changeRole(nickname, MUCRole.visitor, null); 1496 } 1497 1498 /** 1499 * Bans users from the room. An admin or owner of the room can ban users from a room. This 1500 * means that the banned user will no longer be able to join the room unless the ban has been 1501 * removed. If the banned user was present in the room then he/she will be removed from the 1502 * room and notified that he/she was banned along with the reason (if provided) and the bare 1503 * XMPP user ID of the user who initiated the ban. 1504 * 1505 * @param jids the bare XMPP user IDs of the users to ban. 1506 * @throws XMPPErrorException if an error occurs banning a user. In particular, a 1507 * 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin" 1508 * was tried to be banned (i.e. Not Allowed error). 1509 * @throws NoResponseException if there was no response from the server. 1510 * @throws NotConnectedException if the XMPP connection is not connected. 1511 * @throws InterruptedException if the calling thread was interrupted. 1512 */ 1513 public void banUsers(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1514 changeAffiliationByAdmin(jids, MUCAffiliation.outcast); 1515 } 1516 1517 /** 1518 * Bans a user from the room. An admin or owner of the room can ban users from a room. This 1519 * means that the banned user will no longer be able to join the room unless the ban has been 1520 * removed. If the banned user was present in the room then he/she will be removed from the 1521 * room and notified that he/she was banned along with the reason (if provided) and the bare 1522 * XMPP user ID of the user who initiated the ban. 1523 * 1524 * @param jid the bare XMPP user ID of the user to ban (e.g. "user@host.org"). 1525 * @param reason the optional reason why the user was banned. 1526 * @throws XMPPErrorException if an error occurs banning a user. In particular, a 1527 * 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin" 1528 * was tried to be banned (i.e. Not Allowed error). 1529 * @throws NoResponseException if there was no response from the server. 1530 * @throws NotConnectedException if the XMPP connection is not connected. 1531 * @throws InterruptedException if the calling thread was interrupted. 1532 */ 1533 public void banUser(Jid jid, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1534 changeAffiliationByAdmin(jid, MUCAffiliation.outcast, reason); 1535 } 1536 1537 /** 1538 * Grants membership to other users. Only administrators are able to grant membership. A user 1539 * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room 1540 * that a user cannot enter without being on the member list). 1541 * 1542 * @param jids the XMPP user IDs of the users to grant membership. 1543 * @throws XMPPErrorException if an error occurs granting membership to a user. 1544 * @throws NoResponseException if there was no response from the server. 1545 * @throws NotConnectedException if the XMPP connection is not connected. 1546 * @throws InterruptedException if the calling thread was interrupted. 1547 */ 1548 public void grantMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1549 changeAffiliationByAdmin(jids, MUCAffiliation.member); 1550 } 1551 1552 /** 1553 * Grants membership to a user. Only administrators are able to grant membership. A user 1554 * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room 1555 * that a user cannot enter without being on the member list). 1556 * 1557 * @param jid the XMPP user ID of the user to grant membership (e.g. "user@host.org"). 1558 * @throws XMPPErrorException if an error occurs granting membership to a user. 1559 * @throws NoResponseException if there was no response from the server. 1560 * @throws NotConnectedException if the XMPP connection is not connected. 1561 * @throws InterruptedException if the calling thread was interrupted. 1562 */ 1563 public void grantMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1564 changeAffiliationByAdmin(jid, MUCAffiliation.member, null); 1565 } 1566 1567 /** 1568 * Revokes users' membership. Only administrators are able to revoke membership. A user 1569 * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room 1570 * that a user cannot enter without being on the member list). If the user is in the room and 1571 * the room is of type members-only then the user will be removed from the room. 1572 * 1573 * @param jids the bare XMPP user IDs of the users to revoke membership. 1574 * @throws XMPPErrorException if an error occurs revoking membership to a user. 1575 * @throws NoResponseException if there was no response from the server. 1576 * @throws NotConnectedException if the XMPP connection is not connected. 1577 * @throws InterruptedException if the calling thread was interrupted. 1578 */ 1579 public void revokeMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1580 changeAffiliationByAdmin(jids, MUCAffiliation.none); 1581 } 1582 1583 /** 1584 * Revokes a user's membership. Only administrators are able to revoke membership. A user 1585 * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room 1586 * that a user cannot enter without being on the member list). If the user is in the room and 1587 * the room is of type members-only then the user will be removed from the room. 1588 * 1589 * @param jid the bare XMPP user ID of the user to revoke membership (e.g. "user@host.org"). 1590 * @throws XMPPErrorException if an error occurs revoking membership to a user. 1591 * @throws NoResponseException if there was no response from the server. 1592 * @throws NotConnectedException if the XMPP connection is not connected. 1593 * @throws InterruptedException if the calling thread was interrupted. 1594 */ 1595 public void revokeMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1596 changeAffiliationByAdmin(jid, MUCAffiliation.none, null); 1597 } 1598 1599 /** 1600 * Grants moderator privileges to participants or visitors. Room administrators may grant 1601 * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite 1602 * other users, modify room's subject plus all the participant privileges. 1603 * 1604 * @param nicknames the nicknames of the occupants to grant moderator privileges. 1605 * @throws XMPPErrorException if an error occurs granting moderator privileges to a user. 1606 * @throws NoResponseException if there was no response from the server. 1607 * @throws NotConnectedException if the XMPP connection is not connected. 1608 * @throws InterruptedException if the calling thread was interrupted. 1609 */ 1610 public void grantModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1611 changeRole(nicknames, MUCRole.moderator); 1612 } 1613 1614 /** 1615 * Grants moderator privileges to a participant or visitor. Room administrators may grant 1616 * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite 1617 * other users, modify room's subject plus all the participant privileges. 1618 * 1619 * @param nickname the nickname of the occupant to grant moderator privileges. 1620 * @throws XMPPErrorException if an error occurs granting moderator privileges to a user. 1621 * @throws NoResponseException if there was no response from the server. 1622 * @throws NotConnectedException if the XMPP connection is not connected. 1623 * @throws InterruptedException if the calling thread was interrupted. 1624 */ 1625 public void grantModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1626 changeRole(nickname, MUCRole.moderator, null); 1627 } 1628 1629 /** 1630 * Revokes moderator privileges from other users. The occupant that loses moderator 1631 * privileges will become a participant. Room administrators may revoke moderator privileges 1632 * only to occupants whose affiliation is member or none. This means that an administrator is 1633 * not allowed to revoke moderator privileges from other room administrators or owners. 1634 * 1635 * @param nicknames the nicknames of the occupants to revoke moderator privileges. 1636 * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user. 1637 * @throws NoResponseException if there was no response from the server. 1638 * @throws NotConnectedException if the XMPP connection is not connected. 1639 * @throws InterruptedException if the calling thread was interrupted. 1640 */ 1641 public void revokeModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1642 changeRole(nicknames, MUCRole.participant); 1643 } 1644 1645 /** 1646 * Revokes moderator privileges from another user. The occupant that loses moderator 1647 * privileges will become a participant. Room administrators may revoke moderator privileges 1648 * only to occupants whose affiliation is member or none. This means that an administrator is 1649 * not allowed to revoke moderator privileges from other room administrators or owners. 1650 * 1651 * @param nickname the nickname of the occupant to revoke moderator privileges. 1652 * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user. 1653 * @throws NoResponseException if there was no response from the server. 1654 * @throws NotConnectedException if the XMPP connection is not connected. 1655 * @throws InterruptedException if the calling thread was interrupted. 1656 */ 1657 public void revokeModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1658 changeRole(nickname, MUCRole.participant, null); 1659 } 1660 1661 /** 1662 * Grants ownership privileges to other users. Room owners may grant ownership privileges. 1663 * Some room implementations will not allow to grant ownership privileges to other users. 1664 * An owner is allowed to change defining room features as well as perform all administrative 1665 * functions. 1666 * 1667 * @param jids the collection of bare XMPP user IDs of the users to grant ownership. 1668 * @throws XMPPErrorException if an error occurs granting ownership privileges to a user. 1669 * @throws NoResponseException if there was no response from the server. 1670 * @throws NotConnectedException if the XMPP connection is not connected. 1671 * @throws InterruptedException if the calling thread was interrupted. 1672 */ 1673 public void grantOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1674 changeAffiliationByAdmin(jids, MUCAffiliation.owner); 1675 } 1676 1677 /** 1678 * Grants ownership privileges to another user. Room owners may grant ownership privileges. 1679 * Some room implementations will not allow to grant ownership privileges to other users. 1680 * An owner is allowed to change defining room features as well as perform all administrative 1681 * functions. 1682 * 1683 * @param jid the bare XMPP user ID of the user to grant ownership (e.g. "user@host.org"). 1684 * @throws XMPPErrorException if an error occurs granting ownership privileges to a user. 1685 * @throws NoResponseException if there was no response from the server. 1686 * @throws NotConnectedException if the XMPP connection is not connected. 1687 * @throws InterruptedException if the calling thread was interrupted. 1688 */ 1689 public void grantOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1690 changeAffiliationByAdmin(jid, MUCAffiliation.owner, null); 1691 } 1692 1693 /** 1694 * Revokes ownership privileges from other users. The occupant that loses ownership 1695 * privileges will become an administrator. Room owners may revoke ownership privileges. 1696 * Some room implementations will not allow to grant ownership privileges to other users. 1697 * 1698 * @param jids the bare XMPP user IDs of the users to revoke ownership. 1699 * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user. 1700 * @throws NoResponseException if there was no response from the server. 1701 * @throws NotConnectedException if the XMPP connection is not connected. 1702 * @throws InterruptedException if the calling thread was interrupted. 1703 */ 1704 public void revokeOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1705 changeAffiliationByAdmin(jids, MUCAffiliation.admin); 1706 } 1707 1708 /** 1709 * Revokes ownership privileges from another user. The occupant that loses ownership 1710 * privileges will become an administrator. Room owners may revoke ownership privileges. 1711 * Some room implementations will not allow to grant ownership privileges to other users. 1712 * 1713 * @param jid the bare XMPP user ID of the user to revoke ownership (e.g. "user@host.org"). 1714 * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user. 1715 * @throws NoResponseException if there was no response from the server. 1716 * @throws NotConnectedException if the XMPP connection is not connected. 1717 * @throws InterruptedException if the calling thread was interrupted. 1718 */ 1719 public void revokeOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1720 changeAffiliationByAdmin(jid, MUCAffiliation.admin, null); 1721 } 1722 1723 /** 1724 * Grants administrator privileges to other users. Room owners may grant administrator 1725 * privileges to a member or unaffiliated user. An administrator is allowed to perform 1726 * administrative functions such as banning users and edit moderator list. 1727 * 1728 * @param jids the bare XMPP user IDs of the users to grant administrator privileges. 1729 * @throws XMPPErrorException if an error occurs granting administrator privileges to a user. 1730 * @throws NoResponseException if there was no response from the server. 1731 * @throws NotConnectedException if the XMPP connection is not connected. 1732 * @throws InterruptedException if the calling thread was interrupted. 1733 */ 1734 public void grantAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1735 changeAffiliationByAdmin(jids, MUCAffiliation.admin); 1736 } 1737 1738 /** 1739 * Grants administrator privileges to another user. Room owners may grant administrator 1740 * privileges to a member or unaffiliated user. An administrator is allowed to perform 1741 * administrative functions such as banning users and edit moderator list. 1742 * 1743 * @param jid the bare XMPP user ID of the user to grant administrator privileges 1744 * (e.g. "user@host.org"). 1745 * @throws XMPPErrorException if an error occurs granting administrator privileges to a user. 1746 * @throws NoResponseException if there was no response from the server. 1747 * @throws NotConnectedException if the XMPP connection is not connected. 1748 * @throws InterruptedException if the calling thread was interrupted. 1749 */ 1750 public void grantAdmin(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1751 changeAffiliationByAdmin(jid, MUCAffiliation.admin); 1752 } 1753 1754 /** 1755 * Revokes administrator privileges from users. The occupant that loses administrator 1756 * privileges will become a member. Room owners may revoke administrator privileges from 1757 * a member or unaffiliated user. 1758 * 1759 * @param jids the bare XMPP user IDs of the user to revoke administrator privileges. 1760 * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user. 1761 * @throws NoResponseException if there was no response from the server. 1762 * @throws NotConnectedException if the XMPP connection is not connected. 1763 * @throws InterruptedException if the calling thread was interrupted. 1764 */ 1765 public void revokeAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1766 changeAffiliationByAdmin(jids, MUCAffiliation.admin); 1767 } 1768 1769 /** 1770 * Revokes administrator privileges from a user. The occupant that loses administrator 1771 * privileges will become a member. Room owners may revoke administrator privileges from 1772 * a member or unaffiliated user. 1773 * 1774 * @param jid the bare XMPP user ID of the user to revoke administrator privileges 1775 * (e.g. "user@host.org"). 1776 * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user. 1777 * @throws NoResponseException if there was no response from the server. 1778 * @throws NotConnectedException if the XMPP connection is not connected. 1779 * @throws InterruptedException if the calling thread was interrupted. 1780 */ 1781 public void revokeAdmin(EntityJid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { 1782 changeAffiliationByAdmin(jid, MUCAffiliation.member); 1783 } 1784 1785 /** 1786 * Tries to change the affiliation with an 'muc#admin' namespace 1787 * 1788 * @param jid TODO javadoc me please 1789 * @param affiliation TODO javadoc me please 1790 * @throws XMPPErrorException if there was an XMPP error returned. 1791 * @throws NoResponseException if there was no response from the remote entity. 1792 * @throws NotConnectedException if the XMPP connection is not connected. 1793 * @throws InterruptedException if the calling thread was interrupted. 1794 */ 1795 private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation) 1796 throws NoResponseException, XMPPErrorException, 1797 NotConnectedException, InterruptedException { 1798 changeAffiliationByAdmin(jid, affiliation, null); 1799 } 1800 1801 /** 1802 * Tries to change the affiliation with an 'muc#admin' namespace 1803 * 1804 * @param jid TODO javadoc me please 1805 * @param affiliation TODO javadoc me please 1806 * @param reason the reason for the affiliation change (optional) 1807 * @throws XMPPErrorException if there was an XMPP error returned. 1808 * @throws NoResponseException if there was no response from the remote entity. 1809 * @throws NotConnectedException if the XMPP connection is not connected. 1810 * @throws InterruptedException if the calling thread was interrupted. 1811 */ 1812 private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1813 MUCAdmin iq = new MUCAdmin(); 1814 iq.setTo(room); 1815 iq.setType(IQ.Type.set); 1816 // Set the new affiliation. 1817 MUCItem item = new MUCItem(affiliation, jid, reason); 1818 iq.addItem(item); 1819 1820 connection.sendIqRequestAndWaitForResponse(iq); 1821 } 1822 1823 private void changeAffiliationByAdmin(Collection<? extends Jid> jids, MUCAffiliation affiliation) 1824 throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1825 MUCAdmin iq = new MUCAdmin(); 1826 iq.setTo(room); 1827 iq.setType(IQ.Type.set); 1828 for (Jid jid : jids) { 1829 // Set the new affiliation. 1830 MUCItem item = new MUCItem(affiliation, jid); 1831 iq.addItem(item); 1832 } 1833 1834 connection.sendIqRequestAndWaitForResponse(iq); 1835 } 1836 1837 private void changeRole(Resourcepart nickname, MUCRole role, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1838 MUCAdmin iq = new MUCAdmin(); 1839 iq.setTo(room); 1840 iq.setType(IQ.Type.set); 1841 // Set the new role. 1842 MUCItem item = new MUCItem(role, nickname, reason); 1843 iq.addItem(item); 1844 1845 connection.sendIqRequestAndWaitForResponse(iq); 1846 } 1847 1848 private void changeRole(Collection<Resourcepart> nicknames, MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1849 MUCAdmin iq = new MUCAdmin(); 1850 iq.setTo(room); 1851 iq.setType(IQ.Type.set); 1852 for (Resourcepart nickname : nicknames) { 1853 // Set the new role. 1854 MUCItem item = new MUCItem(role, nickname); 1855 iq.addItem(item); 1856 } 1857 1858 connection.sendIqRequestAndWaitForResponse(iq); 1859 } 1860 1861 /** 1862 * Returns the number of occupants in the group chat.<p> 1863 * 1864 * Note: this value will only be accurate after joining the group chat, and 1865 * may fluctuate over time. If you query this value directly after joining the 1866 * group chat it may not be accurate, as it takes a certain amount of time for 1867 * the server to send all presence packets to this client. 1868 * 1869 * @return the number of occupants in the group chat. 1870 */ 1871 public int getOccupantsCount() { 1872 return occupantsMap.size(); 1873 } 1874 1875 /** 1876 * Returns an List for the list of fully qualified occupants 1877 * in the group chat. For example, "conference@chat.jivesoftware.com/SomeUser". 1878 * Typically, a client would only display the nickname of the occupant. To 1879 * get the nickname from the fully qualified name, use the 1880 * {@link org.jxmpp.util.XmppStringUtils#parseResource(String)} method. 1881 * Note: this value will only be accurate after joining the group chat, and may 1882 * fluctuate over time. 1883 * 1884 * @return a List of the occupants in the group chat. 1885 */ 1886 public List<EntityFullJid> getOccupants() { 1887 return new ArrayList<>(occupantsMap.keySet()); 1888 } 1889 1890 /** 1891 * Returns the presence info for a particular user, or <code>null</code> if the user 1892 * is not in the room.<p> 1893 * 1894 * @param user the room occupant to search for his presence. The format of user must 1895 * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch). 1896 * @return the occupant's current presence, or <code>null</code> if the user is unavailable 1897 * or if no presence information is available. 1898 */ 1899 public Presence getOccupantPresence(EntityFullJid user) { 1900 return occupantsMap.get(user); 1901 } 1902 1903 /** 1904 * Returns the Occupant information for a particular occupant, or <code>null</code> if the 1905 * user is not in the room. The Occupant object may include information such as full 1906 * JID of the user as well as the role and affiliation of the user in the room.<p> 1907 * 1908 * @param user the room occupant to search for his presence. The format of user must 1909 * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch). 1910 * @return the Occupant or <code>null</code> if the user is unavailable (i.e. not in the room). 1911 */ 1912 public Occupant getOccupant(EntityFullJid user) { 1913 Presence presence = getOccupantPresence(user); 1914 if (presence != null) { 1915 return new Occupant(presence); 1916 } 1917 return null; 1918 } 1919 1920 /** 1921 * Adds a stanza listener that will be notified of any new Presence packets 1922 * sent to the group chat. Using a listener is a suitable way to know when the list 1923 * of occupants should be re-loaded due to any changes. 1924 * 1925 * @param listener a stanza listener that will be notified of any presence packets 1926 * sent to the group chat. 1927 * @return true if the listener was not already added. 1928 */ 1929 public boolean addParticipantListener(PresenceListener listener) { 1930 return presenceListeners.add(listener); 1931 } 1932 1933 /** 1934 * Removes a stanza listener that was being notified of any new Presence packets 1935 * sent to the group chat. 1936 * 1937 * @param listener a stanza listener that was being notified of any presence packets 1938 * sent to the group chat. 1939 * @return true if the listener was removed, otherwise the listener was not added previously. 1940 */ 1941 public boolean removeParticipantListener(PresenceListener listener) { 1942 return presenceListeners.remove(listener); 1943 } 1944 1945 /** 1946 * Returns a list of <code>Affiliate</code> with the room owners. 1947 * 1948 * @return a list of <code>Affiliate</code> with the room owners. 1949 * @throws XMPPErrorException if you don't have enough privileges to get this information. 1950 * @throws NoResponseException if there was no response from the server. 1951 * @throws NotConnectedException if the XMPP connection is not connected. 1952 * @throws InterruptedException if the calling thread was interrupted. 1953 */ 1954 public List<Affiliate> getOwners() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1955 return getAffiliatesByAdmin(MUCAffiliation.owner); 1956 } 1957 1958 /** 1959 * Returns a list of <code>Affiliate</code> with the room administrators. 1960 * 1961 * @return a list of <code>Affiliate</code> with the room administrators. 1962 * @throws XMPPErrorException if you don't have enough privileges to get this information. 1963 * @throws NoResponseException if there was no response from the server. 1964 * @throws NotConnectedException if the XMPP connection is not connected. 1965 * @throws InterruptedException if the calling thread was interrupted. 1966 */ 1967 public List<Affiliate> getAdmins() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1968 return getAffiliatesByAdmin(MUCAffiliation.admin); 1969 } 1970 1971 /** 1972 * Returns a list of <code>Affiliate</code> with the room members. 1973 * 1974 * @return a list of <code>Affiliate</code> with the room members. 1975 * @throws XMPPErrorException if you don't have enough privileges to get this information. 1976 * @throws NoResponseException if there was no response from the server. 1977 * @throws NotConnectedException if the XMPP connection is not connected. 1978 * @throws InterruptedException if the calling thread was interrupted. 1979 */ 1980 public List<Affiliate> getMembers() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1981 return getAffiliatesByAdmin(MUCAffiliation.member); 1982 } 1983 1984 /** 1985 * Returns a list of <code>Affiliate</code> with the room outcasts. 1986 * 1987 * @return a list of <code>Affiliate</code> with the room outcasts. 1988 * @throws XMPPErrorException if you don't have enough privileges to get this information. 1989 * @throws NoResponseException if there was no response from the server. 1990 * @throws NotConnectedException if the XMPP connection is not connected. 1991 * @throws InterruptedException if the calling thread was interrupted. 1992 */ 1993 public List<Affiliate> getOutcasts() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 1994 return getAffiliatesByAdmin(MUCAffiliation.outcast); 1995 } 1996 1997 /** 1998 * Returns a collection of <code>Affiliate</code> that have the specified room affiliation 1999 * sending a request in the admin namespace. 2000 * 2001 * @param affiliation the affiliation of the users in the room. 2002 * @return a collection of <code>Affiliate</code> that have the specified room affiliation. 2003 * @throws XMPPErrorException if you don't have enough privileges to get this information. 2004 * @throws NoResponseException if there was no response from the server. 2005 * @throws NotConnectedException if the XMPP connection is not connected. 2006 * @throws InterruptedException if the calling thread was interrupted. 2007 */ 2008 private List<Affiliate> getAffiliatesByAdmin(MUCAffiliation affiliation) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 2009 MUCAdmin iq = new MUCAdmin(); 2010 iq.setTo(room); 2011 iq.setType(IQ.Type.get); 2012 // Set the specified affiliation. This may request the list of owners/admins/members/outcasts. 2013 MUCItem item = new MUCItem(affiliation); 2014 iq.addItem(item); 2015 2016 MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq); 2017 2018 // Get the list of affiliates from the server's answer 2019 List<Affiliate> affiliates = new ArrayList<Affiliate>(); 2020 for (MUCItem mucadminItem : answer.getItems()) { 2021 affiliates.add(new Affiliate(mucadminItem)); 2022 } 2023 return affiliates; 2024 } 2025 2026 /** 2027 * Returns a list of <code>Occupant</code> with the room moderators. 2028 * 2029 * @return a list of <code>Occupant</code> with the room moderators. 2030 * @throws XMPPErrorException if you don't have enough privileges to get this information. 2031 * @throws NoResponseException if there was no response from the server. 2032 * @throws NotConnectedException if the XMPP connection is not connected. 2033 * @throws InterruptedException if the calling thread was interrupted. 2034 */ 2035 public List<Occupant> getModerators() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 2036 return getOccupants(MUCRole.moderator); 2037 } 2038 2039 /** 2040 * Returns a list of <code>Occupant</code> with the room participants. 2041 * 2042 * @return a list of <code>Occupant</code> with the room participants. 2043 * @throws XMPPErrorException if you don't have enough privileges to get this information. 2044 * @throws NoResponseException if there was no response from the server. 2045 * @throws NotConnectedException if the XMPP connection is not connected. 2046 * @throws InterruptedException if the calling thread was interrupted. 2047 */ 2048 public List<Occupant> getParticipants() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 2049 return getOccupants(MUCRole.participant); 2050 } 2051 2052 /** 2053 * Returns a list of <code>Occupant</code> that have the specified room role. 2054 * 2055 * @param role the role of the occupant in the room. 2056 * @return a list of <code>Occupant</code> that have the specified room role. 2057 * @throws XMPPErrorException if an error occurred while performing the request to the server or you 2058 * don't have enough privileges to get this information. 2059 * @throws NoResponseException if there was no response from the server. 2060 * @throws NotConnectedException if the XMPP connection is not connected. 2061 * @throws InterruptedException if the calling thread was interrupted. 2062 */ 2063 private List<Occupant> getOccupants(MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 2064 MUCAdmin iq = new MUCAdmin(); 2065 iq.setTo(room); 2066 iq.setType(IQ.Type.get); 2067 // Set the specified role. This may request the list of moderators/participants. 2068 MUCItem item = new MUCItem(role); 2069 iq.addItem(item); 2070 2071 MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq); 2072 // Get the list of participants from the server's answer 2073 List<Occupant> participants = new ArrayList<Occupant>(); 2074 for (MUCItem mucadminItem : answer.getItems()) { 2075 participants.add(new Occupant(mucadminItem)); 2076 } 2077 return participants; 2078 } 2079 2080 /** 2081 * Sends a message to the chat room. 2082 * 2083 * @param text the text of the message to send. 2084 * @throws NotConnectedException if the XMPP connection is not connected. 2085 * @throws InterruptedException if the calling thread was interrupted. 2086 */ 2087 public void sendMessage(String text) throws NotConnectedException, InterruptedException { 2088 Message message = buildMessage() 2089 .setBody(text) 2090 .build(); 2091 connection.sendStanza(message); 2092 } 2093 2094 /** 2095 * Returns a new Chat for sending private messages to a given room occupant. 2096 * The Chat's occupant address is the room's JID (i.e. roomName@service/nick). The server 2097 * service will change the 'from' address to the sender's room JID and delivering the message 2098 * to the intended recipient's full JID. 2099 * 2100 * @param occupant occupant unique room JID (e.g. 'darkcave@macbeth.shakespeare.lit/Paul'). 2101 * @param listener the listener is a message listener that will handle messages for the newly 2102 * created chat. 2103 * @return new Chat for sending private messages to a given room occupant. 2104 */ 2105 // TODO This should be made new not using chat.Chat. Private MUC chats are different from XMPP-IM 1:1 chats in to many ways. 2106 // API sketch: PrivateMucChat createPrivateChat(Resourcepart nick) 2107 @SuppressWarnings("deprecation") 2108 public org.jivesoftware.smack.chat.Chat createPrivateChat(EntityFullJid occupant, ChatMessageListener listener) { 2109 return org.jivesoftware.smack.chat.ChatManager.getInstanceFor(connection).createChat(occupant, listener); 2110 } 2111 2112 /** 2113 * Creates a new Message to send to the chat room. 2114 * 2115 * @return a new Message addressed to the chat room. 2116 * @deprecated use {@link #buildMessage()} instead. 2117 */ 2118 @Deprecated 2119 // TODO: Remove when stanza builder is ready. 2120 public Message createMessage() { 2121 return connection.getStanzaFactory().buildMessageStanza() 2122 .ofType(Message.Type.groupchat) 2123 .to(room) 2124 .build(); 2125 } 2126 2127 /** 2128 * Constructs a new message builder for messages send to this MUC room. 2129 * 2130 * @return a new message builder. 2131 */ 2132 public MessageBuilder buildMessage() { 2133 return connection.getStanzaFactory() 2134 .buildMessageStanza() 2135 .ofType(Message.Type.groupchat) 2136 .to(room) 2137 ; 2138 } 2139 2140 /** 2141 * Sends a Message to the chat room. 2142 * 2143 * @param message the message. 2144 * @throws NotConnectedException if the XMPP connection is not connected. 2145 * @throws InterruptedException if the calling thread was interrupted. 2146 * @deprecated use {@link #sendMessage(MessageBuilder)} instead. 2147 */ 2148 @Deprecated 2149 // TODO: Remove in Smack 4.5. 2150 public void sendMessage(Message message) throws NotConnectedException, InterruptedException { 2151 sendMessage(message.asBuilder()); 2152 } 2153 2154 /** 2155 * Sends a Message to the chat room. 2156 * 2157 * @param messageBuilder the message. 2158 * @return a read-only view of the send message. 2159 * @throws NotConnectedException if the XMPP connection is not connected. 2160 * @throws InterruptedException if the calling thread was interrupted. 2161 */ 2162 public MessageView sendMessage(MessageBuilder messageBuilder) throws NotConnectedException, InterruptedException { 2163 for (MucMessageInterceptor interceptor : messageInterceptors) { 2164 interceptor.intercept(messageBuilder, this); 2165 } 2166 2167 Message message = messageBuilder.to(room).ofType(Message.Type.groupchat).build(); 2168 connection.sendStanza(message); 2169 return message; 2170 } 2171 2172 /** 2173 * Polls for and returns the next message, or <code>null</code> if there isn't 2174 * a message immediately available. This method provides significantly different 2175 * functionality than the {@link #nextMessage()} method since it's non-blocking. 2176 * In other words, the method call will always return immediately, whereas the 2177 * nextMessage method will return only when a message is available (or after 2178 * a specific timeout). 2179 * 2180 * @return the next message if one is immediately available and 2181 * <code>null</code> otherwise. 2182 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 2183 */ 2184 public Message pollMessage() throws MucNotJoinedException { 2185 if (messageCollector == null) { 2186 throw new MucNotJoinedException(this); 2187 } 2188 return messageCollector.pollResult(); 2189 } 2190 2191 /** 2192 * Returns the next available message in the chat. The method call will block 2193 * (not return) until a message is available. 2194 * 2195 * @return the next message. 2196 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 2197 * @throws InterruptedException if the calling thread was interrupted. 2198 */ 2199 public Message nextMessage() throws MucNotJoinedException, InterruptedException { 2200 if (messageCollector == null) { 2201 throw new MucNotJoinedException(this); 2202 } 2203 return messageCollector.nextResultBlockForever(); 2204 } 2205 2206 /** 2207 * Returns the next available message in the chat. The method call will block 2208 * (not return) until a stanza is available or the <code>timeout</code> has elapsed. 2209 * If the timeout elapses without a result, <code>null</code> will be returned. 2210 * 2211 * @param timeout the maximum amount of time to wait for the next message. 2212 * @return the next message, or <code>null</code> if the timeout elapses without a 2213 * message becoming available. 2214 * @throws MucNotJoinedException if not joined to the Multi-User Chat. 2215 * @throws InterruptedException if the calling thread was interrupted. 2216 */ 2217 public Message nextMessage(long timeout) throws MucNotJoinedException, InterruptedException { 2218 if (messageCollector == null) { 2219 throw new MucNotJoinedException(this); 2220 } 2221 return messageCollector.nextResult(timeout); 2222 } 2223 2224 /** 2225 * Adds a stanza listener that will be notified of any new messages in the 2226 * group chat. Only "group chat" messages addressed to this group chat will 2227 * be delivered to the listener. If you wish to listen for other packets 2228 * that may be associated with this group chat, you should register a 2229 * PacketListener directly with the XMPPConnection with the appropriate 2230 * PacketListener. 2231 * 2232 * @param listener a stanza listener. 2233 * @return true if the listener was not already added. 2234 */ 2235 public boolean addMessageListener(MessageListener listener) { 2236 return messageListeners.add(listener); 2237 } 2238 2239 /** 2240 * Removes a stanza listener that was being notified of any new messages in the 2241 * multi user chat. Only "group chat" messages addressed to this multi user chat were 2242 * being delivered to the listener. 2243 * 2244 * @param listener a stanza listener. 2245 * @return true if the listener was removed, otherwise the listener was not added previously. 2246 */ 2247 public boolean removeMessageListener(MessageListener listener) { 2248 return messageListeners.remove(listener); 2249 } 2250 2251 public boolean addMessageInterceptor(MucMessageInterceptor interceptor) { 2252 return messageInterceptors.add(interceptor); 2253 } 2254 2255 public boolean removeMessageInterceptor(MucMessageInterceptor interceptor) { 2256 return messageInterceptors.remove(interceptor); 2257 } 2258 2259 /** 2260 * Changes the subject within the room. As a default, only users with a role of "moderator" 2261 * are allowed to change the subject in a room. Although some rooms may be configured to 2262 * allow a mere participant or even a visitor to change the subject. 2263 * 2264 * @param subject the new room's subject to set. 2265 * @throws XMPPErrorException if someone without appropriate privileges attempts to change the 2266 * room subject will throw an error with code 403 (i.e. Forbidden) 2267 * @throws NoResponseException if there was no response from the server. 2268 * @throws NotConnectedException if the XMPP connection is not connected. 2269 * @throws InterruptedException if the calling thread was interrupted. 2270 */ 2271 public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { 2272 Message message = buildMessage() 2273 .setSubject(subject) 2274 .build(); 2275 // Wait for an error or confirmation message back from the server. 2276 StanzaFilter successFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() { 2277 @Override 2278 public boolean accept(Stanza packet) { 2279 Message msg = (Message) packet; 2280 return subject.equals(msg.getSubject()); 2281 } 2282 }); 2283 StanzaFilter errorFilter = new AndFilter(fromRoomFilter, new StanzaIdFilter(message), MessageTypeFilter.ERROR); 2284 StanzaFilter responseFilter = new OrFilter(successFilter, errorFilter); 2285 StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, message); 2286 // Wait up to a certain number of seconds for a reply. 2287 response.nextResultOrThrow(); 2288 } 2289 2290 /** 2291 * Remove the connection callbacks (PacketListener, PacketInterceptor, StanzaCollector) used by this MUC from the 2292 * connection. 2293 */ 2294 private void removeConnectionCallbacks() { 2295 connection.removeStanzaListener(messageListener); 2296 connection.removeStanzaListener(presenceListener); 2297 connection.removeStanzaListener(subjectListener); 2298 connection.removeStanzaListener(declinesListener); 2299 connection.removePresenceInterceptor(presenceInterceptor); 2300 if (messageCollector != null) { 2301 messageCollector.cancel(); 2302 messageCollector = null; 2303 } 2304 } 2305 2306 /** 2307 * Remove all callbacks and resources necessary when the user has left the room for some reason. 2308 */ 2309 private synchronized void userHasLeft() { 2310 occupantsMap.clear(); 2311 myRoomJid = null; 2312 // Update the list of joined rooms 2313 multiUserChatManager.removeJoinedRoom(room); 2314 removeConnectionCallbacks(); 2315 } 2316 2317 /** 2318 * Adds a listener that will be notified of changes in your status in the room 2319 * such as the user being kicked, banned, or granted admin permissions. 2320 * 2321 * @param listener a user status listener. 2322 * @return true if the user status listener was not already added. 2323 */ 2324 public boolean addUserStatusListener(UserStatusListener listener) { 2325 return userStatusListeners.add(listener); 2326 } 2327 2328 /** 2329 * Removes a listener that was being notified of changes in your status in the room 2330 * such as the user being kicked, banned, or granted admin permissions. 2331 * 2332 * @param listener a user status listener. 2333 * @return true if the listener was registered and is now removed. 2334 */ 2335 public boolean removeUserStatusListener(UserStatusListener listener) { 2336 return userStatusListeners.remove(listener); 2337 } 2338 2339 /** 2340 * Adds a listener that will be notified of changes in occupants status in the room 2341 * such as the user being kicked, banned, or granted admin permissions. 2342 * 2343 * @param listener a participant status listener. 2344 * @return true if the listener was not already added. 2345 */ 2346 public boolean addParticipantStatusListener(ParticipantStatusListener listener) { 2347 return participantStatusListeners.add(listener); 2348 } 2349 2350 /** 2351 * Removes a listener that was being notified of changes in occupants status in the room 2352 * such as the user being kicked, banned, or granted admin permissions. 2353 * 2354 * @param listener a participant status listener. 2355 * @return true if the listener was registered and is now removed. 2356 */ 2357 public boolean removeParticipantStatusListener(ParticipantStatusListener listener) { 2358 return participantStatusListeners.remove(listener); 2359 } 2360 2361 /** 2362 * Fires notification events if the role of a room occupant has changed. If the occupant that 2363 * changed his role is your occupant then the <code>UserStatusListeners</code> added to this 2364 * <code>MultiUserChat</code> will be fired. On the other hand, if the occupant that changed 2365 * his role is not yours then the <code>ParticipantStatusListeners</code> added to this 2366 * <code>MultiUserChat</code> will be fired. The following table shows the events that will 2367 * be fired depending on the previous and new role of the occupant. 2368 * 2369 * <pre> 2370 * <table border="1"> 2371 * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr> 2372 * 2373 * <tr><td>None</td><td>Visitor</td><td>--</td></tr> 2374 * <tr><td>Visitor</td><td>Participant</td><td>voiceGranted</td></tr> 2375 * <tr><td>Participant</td><td>Moderator</td><td>moderatorGranted</td></tr> 2376 * 2377 * <tr><td>None</td><td>Participant</td><td>voiceGranted</td></tr> 2378 * <tr><td>None</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr> 2379 * <tr><td>Visitor</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr> 2380 * 2381 * <tr><td>Moderator</td><td>Participant</td><td>moderatorRevoked</td></tr> 2382 * <tr><td>Participant</td><td>Visitor</td><td>voiceRevoked</td></tr> 2383 * <tr><td>Visitor</td><td>None</td><td>kicked</td></tr> 2384 * 2385 * <tr><td>Moderator</td><td>Visitor</td><td>voiceRevoked + moderatorRevoked</td></tr> 2386 * <tr><td>Moderator</td><td>None</td><td>kicked</td></tr> 2387 * <tr><td>Participant</td><td>None</td><td>kicked</td></tr> 2388 * </table> 2389 * </pre> 2390 * 2391 * @param oldRole the previous role of the user in the room before receiving the new presence 2392 * @param newRole the new role of the user in the room after receiving the new presence 2393 * @param isUserModification whether the received presence is about your user in the room or not 2394 * @param from the occupant whose role in the room has changed 2395 * (e.g. room@conference.jabber.org/nick). 2396 */ 2397 private void checkRoleModifications( 2398 MUCRole oldRole, 2399 MUCRole newRole, 2400 boolean isUserModification, 2401 EntityFullJid from) { 2402 // Voice was granted to a visitor 2403 if ((MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole)) 2404 && MUCRole.participant.equals(newRole)) { 2405 if (isUserModification) { 2406 for (UserStatusListener listener : userStatusListeners) { 2407 listener.voiceGranted(); 2408 } 2409 } 2410 else { 2411 for (ParticipantStatusListener listener : participantStatusListeners) { 2412 listener.voiceGranted(from); 2413 } 2414 } 2415 } 2416 // The participant's voice was revoked from the room 2417 else if ( 2418 MUCRole.participant.equals(oldRole) 2419 && (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole))) { 2420 if (isUserModification) { 2421 for (UserStatusListener listener : userStatusListeners) { 2422 listener.voiceRevoked(); 2423 } 2424 } 2425 else { 2426 for (ParticipantStatusListener listener : participantStatusListeners) { 2427 listener.voiceRevoked(from); 2428 } 2429 } 2430 } 2431 // Moderator privileges were granted to a participant 2432 if (!MUCRole.moderator.equals(oldRole) && MUCRole.moderator.equals(newRole)) { 2433 if (MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole)) { 2434 if (isUserModification) { 2435 for (UserStatusListener listener : userStatusListeners) { 2436 listener.voiceGranted(); 2437 } 2438 } 2439 else { 2440 for (ParticipantStatusListener listener : participantStatusListeners) { 2441 listener.voiceGranted(from); 2442 } 2443 } 2444 } 2445 if (isUserModification) { 2446 for (UserStatusListener listener : userStatusListeners) { 2447 listener.moderatorGranted(); 2448 } 2449 } 2450 else { 2451 for (ParticipantStatusListener listener : participantStatusListeners) { 2452 listener.moderatorGranted(from); 2453 } 2454 } 2455 } 2456 // Moderator privileges were revoked from a participant 2457 else if (MUCRole.moderator.equals(oldRole) && !MUCRole.moderator.equals(newRole)) { 2458 if (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole)) { 2459 if (isUserModification) { 2460 for (UserStatusListener listener : userStatusListeners) { 2461 listener.voiceRevoked(); 2462 } 2463 } 2464 else { 2465 for (ParticipantStatusListener listener : participantStatusListeners) { 2466 listener.voiceRevoked(from); 2467 } 2468 } 2469 } 2470 if (isUserModification) { 2471 for (UserStatusListener listener : userStatusListeners) { 2472 listener.moderatorRevoked(); 2473 } 2474 } 2475 else { 2476 for (ParticipantStatusListener listener : participantStatusListeners) { 2477 listener.moderatorRevoked(from); 2478 } 2479 } 2480 } 2481 } 2482 2483 /** 2484 * Fires notification events if the affiliation of a room occupant has changed. If the 2485 * occupant that changed his affiliation is your occupant then the 2486 * <code>UserStatusListeners</code> added to this <code>MultiUserChat</code> will be fired. 2487 * On the other hand, if the occupant that changed his affiliation is not yours then the 2488 * <code>ParticipantStatusListeners</code> added to this <code>MultiUserChat</code> will be 2489 * fired. The following table shows the events that will be fired depending on the previous 2490 * and new affiliation of the occupant. 2491 * 2492 * <pre> 2493 * <table border="1"> 2494 * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr> 2495 * 2496 * <tr><td>None</td><td>Member</td><td>membershipGranted</td></tr> 2497 * <tr><td>Member</td><td>Admin</td><td>membershipRevoked + adminGranted</td></tr> 2498 * <tr><td>Admin</td><td>Owner</td><td>adminRevoked + ownershipGranted</td></tr> 2499 * 2500 * <tr><td>None</td><td>Admin</td><td>adminGranted</td></tr> 2501 * <tr><td>None</td><td>Owner</td><td>ownershipGranted</td></tr> 2502 * <tr><td>Member</td><td>Owner</td><td>membershipRevoked + ownershipGranted</td></tr> 2503 * 2504 * <tr><td>Owner</td><td>Admin</td><td>ownershipRevoked + adminGranted</td></tr> 2505 * <tr><td>Admin</td><td>Member</td><td>adminRevoked + membershipGranted</td></tr> 2506 * <tr><td>Member</td><td>None</td><td>membershipRevoked</td></tr> 2507 * 2508 * <tr><td>Owner</td><td>Member</td><td>ownershipRevoked + membershipGranted</td></tr> 2509 * <tr><td>Owner</td><td>None</td><td>ownershipRevoked</td></tr> 2510 * <tr><td>Admin</td><td>None</td><td>adminRevoked</td></tr> 2511 * <tr><td><i>Anyone</i></td><td>Outcast</td><td>banned</td></tr> 2512 * </table> 2513 * </pre> 2514 * 2515 * @param oldAffiliation the previous affiliation of the user in the room before receiving the 2516 * new presence 2517 * @param newAffiliation the new affiliation of the user in the room after receiving the new 2518 * presence 2519 * @param isUserModification whether the received presence is about your user in the room or not 2520 * @param from the occupant whose role in the room has changed 2521 * (e.g. room@conference.jabber.org/nick). 2522 */ 2523 private void checkAffiliationModifications( 2524 MUCAffiliation oldAffiliation, 2525 MUCAffiliation newAffiliation, 2526 boolean isUserModification, 2527 EntityFullJid from) { 2528 // First check for revoked affiliation and then for granted affiliations. The idea is to 2529 // first fire the "revoke" events and then fire the "grant" events. 2530 2531 // The user's ownership to the room was revoked 2532 if (MUCAffiliation.owner.equals(oldAffiliation) && !MUCAffiliation.owner.equals(newAffiliation)) { 2533 if (isUserModification) { 2534 for (UserStatusListener listener : userStatusListeners) { 2535 listener.ownershipRevoked(); 2536 } 2537 } 2538 else { 2539 for (ParticipantStatusListener listener : participantStatusListeners) { 2540 listener.ownershipRevoked(from); 2541 } 2542 } 2543 } 2544 // The user's administrative privileges to the room were revoked 2545 else if (MUCAffiliation.admin.equals(oldAffiliation) && !MUCAffiliation.admin.equals(newAffiliation)) { 2546 if (isUserModification) { 2547 for (UserStatusListener listener : userStatusListeners) { 2548 listener.adminRevoked(); 2549 } 2550 } 2551 else { 2552 for (ParticipantStatusListener listener : participantStatusListeners) { 2553 listener.adminRevoked(from); 2554 } 2555 } 2556 } 2557 // The user's membership to the room was revoked 2558 else if (MUCAffiliation.member.equals(oldAffiliation) && !MUCAffiliation.member.equals(newAffiliation)) { 2559 if (isUserModification) { 2560 for (UserStatusListener listener : userStatusListeners) { 2561 listener.membershipRevoked(); 2562 } 2563 } 2564 else { 2565 for (ParticipantStatusListener listener : participantStatusListeners) { 2566 listener.membershipRevoked(from); 2567 } 2568 } 2569 } 2570 2571 // The user was granted ownership to the room 2572 if (!MUCAffiliation.owner.equals(oldAffiliation) && MUCAffiliation.owner.equals(newAffiliation)) { 2573 if (isUserModification) { 2574 for (UserStatusListener listener : userStatusListeners) { 2575 listener.ownershipGranted(); 2576 } 2577 } 2578 else { 2579 for (ParticipantStatusListener listener : participantStatusListeners) { 2580 listener.ownershipGranted(from); 2581 } 2582 } 2583 } 2584 // The user was granted administrative privileges to the room 2585 else if (!MUCAffiliation.admin.equals(oldAffiliation) && MUCAffiliation.admin.equals(newAffiliation)) { 2586 if (isUserModification) { 2587 for (UserStatusListener listener : userStatusListeners) { 2588 listener.adminGranted(); 2589 } 2590 } 2591 else { 2592 for (ParticipantStatusListener listener : participantStatusListeners) { 2593 listener.adminGranted(from); 2594 } 2595 } 2596 } 2597 // The user was granted membership to the room 2598 else if (!MUCAffiliation.member.equals(oldAffiliation) && MUCAffiliation.member.equals(newAffiliation)) { 2599 if (isUserModification) { 2600 for (UserStatusListener listener : userStatusListeners) { 2601 listener.membershipGranted(); 2602 } 2603 } 2604 else { 2605 for (ParticipantStatusListener listener : participantStatusListeners) { 2606 listener.membershipGranted(from); 2607 } 2608 } 2609 } 2610 } 2611 2612 /** 2613 * Fires events according to the received presence code. 2614 * 2615 * @param statusCodes TODO javadoc me please 2616 * @param isUserModification TODO javadoc me please 2617 * @param mucUser TODO javadoc me please 2618 * @param from TODO javadoc me please 2619 */ 2620 private void checkPresenceCode( 2621 Set<Status> statusCodes, 2622 boolean isUserModification, 2623 MUCUser mucUser, 2624 EntityFullJid from) { 2625 // Check if an occupant was kicked from the room 2626 if (statusCodes.contains(Status.KICKED_307)) { 2627 // Check if this occupant was kicked 2628 if (isUserModification) { 2629 for (UserStatusListener listener : userStatusListeners) { 2630 listener.kicked(mucUser.getItem().getActor(), mucUser.getItem().getReason()); 2631 } 2632 } 2633 else { 2634 for (ParticipantStatusListener listener : participantStatusListeners) { 2635 listener.kicked(from, mucUser.getItem().getActor(), mucUser.getItem().getReason()); 2636 } 2637 } 2638 } 2639 // A user was banned from the room 2640 if (statusCodes.contains(Status.BANNED_301)) { 2641 // Check if this occupant was banned 2642 if (isUserModification) { 2643 for (UserStatusListener listener : userStatusListeners) { 2644 listener.banned(mucUser.getItem().getActor(), mucUser.getItem().getReason()); 2645 } 2646 } 2647 else { 2648 for (ParticipantStatusListener listener : participantStatusListeners) { 2649 listener.banned(from, mucUser.getItem().getActor(), mucUser.getItem().getReason()); 2650 } 2651 } 2652 } 2653 // A user's membership was revoked from the room 2654 if (statusCodes.contains(Status.REMOVED_AFFIL_CHANGE_321)) { 2655 // Check if this occupant's membership was revoked 2656 if (isUserModification) { 2657 for (UserStatusListener listener : userStatusListeners) { 2658 listener.membershipRevoked(); 2659 } 2660 } else { 2661 for (ParticipantStatusListener listener : participantStatusListeners) { 2662 listener.membershipRevoked(from); 2663 } 2664 } 2665 } 2666 // A occupant has changed his nickname in the room 2667 if (statusCodes.contains(Status.NEW_NICKNAME_303)) { 2668 for (ParticipantStatusListener listener : participantStatusListeners) { 2669 listener.nicknameChanged(from, mucUser.getItem().getNick()); 2670 } 2671 } 2672 } 2673 2674 /** 2675 * Get the XMPP connection associated with this chat instance. 2676 * 2677 * @return the associated XMPP connection. 2678 * @since 4.3.0 2679 */ 2680 public XMPPConnection getXmppConnection() { 2681 return connection; 2682 } 2683 2684 public boolean serviceSupportsStableIds() { 2685 return DiscoverInfo.nullSafeContainsFeature(mucServiceDiscoInfo, MultiUserChatConstants.STABLE_ID_FEATURE); 2686 } 2687 2688 @Override 2689 public String toString() { 2690 return "MUC: " + room + "(" + connection.getUser() + ")"; 2691 } 2692}