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