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