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