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