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