001/**
002 *
003 * Copyright © 2014-2021 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.muc;
018
019import java.lang.ref.WeakReference;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.HashSet;
024import java.util.List;
025import java.util.Map;
026import java.util.Set;
027import java.util.WeakHashMap;
028import java.util.concurrent.CopyOnWriteArrayList;
029import java.util.concurrent.CopyOnWriteArraySet;
030import java.util.logging.Level;
031import java.util.logging.Logger;
032
033import org.jivesoftware.smack.ConnectionCreationListener;
034import org.jivesoftware.smack.ConnectionListener;
035import org.jivesoftware.smack.Manager;
036import org.jivesoftware.smack.SmackException.NoResponseException;
037import org.jivesoftware.smack.SmackException.NotConnectedException;
038import org.jivesoftware.smack.StanzaListener;
039import org.jivesoftware.smack.XMPPConnection;
040import org.jivesoftware.smack.XMPPConnectionRegistry;
041import org.jivesoftware.smack.XMPPException.XMPPErrorException;
042import org.jivesoftware.smack.filter.AndFilter;
043import org.jivesoftware.smack.filter.ExtensionElementFilter;
044import org.jivesoftware.smack.filter.MessageTypeFilter;
045import org.jivesoftware.smack.filter.NotFilter;
046import org.jivesoftware.smack.filter.StanzaExtensionFilter;
047import org.jivesoftware.smack.filter.StanzaFilter;
048import org.jivesoftware.smack.filter.StanzaTypeFilter;
049import org.jivesoftware.smack.packet.Message;
050import org.jivesoftware.smack.packet.MessageBuilder;
051import org.jivesoftware.smack.packet.Stanza;
052import org.jivesoftware.smack.util.Async;
053import org.jivesoftware.smack.util.CleaningWeakReferenceMap;
054
055import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider;
056import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
057import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
058import org.jivesoftware.smackx.disco.packet.DiscoverItems;
059import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException;
060import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
061import org.jivesoftware.smackx.muc.packet.GroupChatInvitation;
062import org.jivesoftware.smackx.muc.packet.MUCInitialPresence;
063import org.jivesoftware.smackx.muc.packet.MUCUser;
064
065import org.jxmpp.jid.DomainBareJid;
066import org.jxmpp.jid.EntityBareJid;
067import org.jxmpp.jid.EntityFullJid;
068import org.jxmpp.jid.EntityJid;
069import org.jxmpp.jid.Jid;
070import org.jxmpp.jid.parts.Resourcepart;
071import org.jxmpp.util.cache.ExpirationCache;
072
073/**
074 * A manager for Multi-User Chat rooms.
075 * <p>
076 * Use {@link #getMultiUserChat(EntityBareJid)} to retrieve an object representing a Multi-User Chat room.
077 * </p>
078 * <p>
079 * <b>Automatic rejoin:</b> The manager supports automatic rejoin of MultiUserChat rooms once the connection got
080 * re-established. This mechanism is disabled by default. To enable it, use {@link #setAutoJoinOnReconnect(boolean)}.
081 * You can set a {@link AutoJoinFailedCallback} via {@link #setAutoJoinFailedCallback(AutoJoinFailedCallback)} to get
082 * notified if this mechanism failed for some reason. Note that as soon as rejoining for a single room failed, no
083 * further attempts will be made for the other rooms.
084 * </p>
085 *
086 * Note:
087 * For inviting other users to a group chat or listening for such invitations, take a look at the
088 * {@link DirectMucInvitationManager} which provides an implementation of XEP-0249: Direct MUC Invitations.
089 *
090 * @see <a href="http://xmpp.org/extensions/xep-0045.html">XEP-0045: Multi-User Chat</a>
091 */
092public final class MultiUserChatManager extends Manager {
093    private static final String DISCO_NODE = MUCInitialPresence.NAMESPACE + "#rooms";
094
095    private static final Logger LOGGER = Logger.getLogger(MultiUserChatManager.class.getName());
096
097    static {
098        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
099            @Override
100            public void connectionCreated(final XMPPConnection connection) {
101                // Set on every established connection that this client supports the Multi-User
102                // Chat protocol. This information will be used when another client tries to
103                // discover whether this client supports MUC or not.
104                ServiceDiscoveryManager.getInstanceFor(connection).addFeature(MUCInitialPresence.NAMESPACE);
105
106                // Set the NodeInformationProvider that will provide information about the
107                // joined rooms whenever a disco request is received
108                final WeakReference<XMPPConnection> weakRefConnection = new WeakReference<XMPPConnection>(connection);
109                ServiceDiscoveryManager.getInstanceFor(connection).setNodeInformationProvider(DISCO_NODE,
110                                new AbstractNodeInformationProvider() {
111                                    @Override
112                                    public List<DiscoverItems.Item> getNodeItems() {
113                                        XMPPConnection connection = weakRefConnection.get();
114                                        if (connection == null)
115                                            return Collections.emptyList();
116                                        Set<EntityBareJid> joinedRooms = MultiUserChatManager.getInstanceFor(connection).getJoinedRooms();
117                                        List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>();
118                                        for (EntityBareJid room : joinedRooms) {
119                                            answer.add(new DiscoverItems.Item(room));
120                                        }
121                                        return answer;
122                                    }
123                                });
124            }
125        });
126    }
127
128    private static final Map<XMPPConnection, MultiUserChatManager> INSTANCES = new WeakHashMap<XMPPConnection, MultiUserChatManager>();
129
130    /**
131     * Get a instance of a multi user chat manager for the given connection.
132     *
133     * @param connection TODO javadoc me please
134     * @return a multi user chat manager.
135     */
136    public static synchronized MultiUserChatManager getInstanceFor(XMPPConnection connection) {
137        MultiUserChatManager multiUserChatManager = INSTANCES.get(connection);
138        if (multiUserChatManager == null) {
139            multiUserChatManager = new MultiUserChatManager(connection);
140            INSTANCES.put(connection, multiUserChatManager);
141        }
142        return multiUserChatManager;
143    }
144
145    private static final StanzaFilter INVITATION_FILTER = new AndFilter(StanzaTypeFilter.MESSAGE, new StanzaExtensionFilter(new MUCUser()),
146                    new NotFilter(MessageTypeFilter.ERROR));
147
148    private static final StanzaFilter DIRECT_INVITATION_FILTER =
149        new AndFilter(StanzaTypeFilter.MESSAGE,
150                      new ExtensionElementFilter<GroupChatInvitation>(GroupChatInvitation.class),
151                      new NotFilter(MessageTypeFilter.ERROR));
152
153    private static final ExpirationCache<DomainBareJid, DiscoverInfo> KNOWN_MUC_SERVICES = new ExpirationCache<>(
154        100, 1000 * 60 * 60 * 24);
155
156    private static final Set<MucMessageInterceptor> DEFAULT_MESSAGE_INTERCEPTORS = new HashSet<>();
157
158    private final Set<InvitationListener> invitationsListeners = new CopyOnWriteArraySet<InvitationListener>();
159
160    /**
161     * The XMPP addresses of currently joined rooms.
162     */
163    private final Set<EntityBareJid> joinedRooms = new CopyOnWriteArraySet<>();
164
165    /**
166     * A Map of MUC JIDs to {@link MultiUserChat} instances. We use weak references for the values in order to allow
167     * those instances to get garbage collected. Note that MultiUserChat instances can not get garbage collected while
168     * the user is joined, because then the MUC will have PacketListeners added to the XMPPConnection.
169     */
170    private final Map<EntityBareJid, WeakReference<MultiUserChat>> multiUserChats = new CleaningWeakReferenceMap<>();
171
172    private boolean autoJoinOnReconnect;
173
174    private AutoJoinFailedCallback autoJoinFailedCallback;
175
176    private AutoJoinSuccessCallback autoJoinSuccessCallback;
177
178    private final ServiceDiscoveryManager serviceDiscoveryManager;
179
180    private MultiUserChatManager(XMPPConnection connection) {
181        super(connection);
182        serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);
183        // Listens for all messages that include a MUCUser extension and fire the invitation
184        // listeners if the message includes an invitation.
185        StanzaListener invitationPacketListener = new StanzaListener() {
186            @Override
187            public void processStanza(Stanza packet) {
188                final Message message = (Message) packet;
189                // Get the MUCUser extension
190                final MUCUser mucUser = MUCUser.from(message);
191                // Check if the MUCUser extension includes an invitation
192                if (mucUser.getInvite() != null) {
193                    EntityBareJid mucJid = message.getFrom().asEntityBareJidIfPossible();
194                    if (mucJid == null) {
195                        LOGGER.warning("Invite to non bare JID: '" + message.toXML() + "'");
196                        return;
197                    }
198                    // Fire event for invitation listeners
199                    final MultiUserChat muc = getMultiUserChat(mucJid);
200                    final XMPPConnection connection = connection();
201                    final MUCUser.Invite invite = mucUser.getInvite();
202                    final EntityJid from = invite.getFrom();
203                    final String reason = invite.getReason();
204                    final String password = mucUser.getPassword();
205                    for (final InvitationListener listener : invitationsListeners) {
206                        listener.invitationReceived(connection, muc, from, reason, password, message, invite);
207                    }
208                }
209            }
210        };
211        connection.addAsyncStanzaListener(invitationPacketListener, INVITATION_FILTER);
212
213        // Listens for all messages that include an XEP-0249 GroupChatInvitation extension and fire the invitation
214        // listeners
215        StanzaListener directInvitationStanzaListener = new StanzaListener() {
216            @Override
217            public void processStanza(Stanza stanza) {
218                final Message message = (Message) stanza;
219                GroupChatInvitation invite =
220                    stanza.getExtension(GroupChatInvitation.class);
221
222                // Fire event for invitation listeners
223                final MultiUserChat muc = getMultiUserChat(invite.getRoomAddress());
224                final XMPPConnection connection = connection();
225                final EntityJid from = message.getFrom().asEntityJidIfPossible();
226                if (from == null) {
227                    LOGGER.warning("Group Chat Invitation from non entity JID in '" + message + "'");
228                    return;
229                }
230                final String reason = invite.getReason();
231                final String password = invite.getPassword();
232                final MUCUser.Invite mucInvite = new MUCUser.Invite(reason, from, connection.getUser().asEntityBareJid());
233                for (final InvitationListener listener : invitationsListeners) {
234                    listener.invitationReceived(connection, muc, from, reason, password, message, mucInvite);
235                }
236            }
237        };
238        connection.addAsyncStanzaListener(directInvitationStanzaListener, DIRECT_INVITATION_FILTER);
239
240        connection.addConnectionListener(new ConnectionListener() {
241            @Override
242            public void authenticated(XMPPConnection connection, boolean resumed) {
243                if (resumed) return;
244                if (!autoJoinOnReconnect) return;
245
246                final Set<EntityBareJid> mucs = getJoinedRooms();
247                if (mucs.isEmpty()) return;
248
249                Async.go(new Runnable() {
250                    @Override
251                    public void run() {
252                        final AutoJoinFailedCallback failedCallback = autoJoinFailedCallback;
253                        final AutoJoinSuccessCallback successCallback = autoJoinSuccessCallback;
254                        for (EntityBareJid mucJid : mucs) {
255                            MultiUserChat muc = getMultiUserChat(mucJid);
256
257                            if (!muc.isJoined()) return;
258
259                            Resourcepart nickname = muc.getNickname();
260                            if (nickname == null) return;
261
262                            try {
263                                muc.leave();
264                            } catch (NotConnectedException | InterruptedException | MucNotJoinedException
265                                            | NoResponseException | XMPPErrorException e) {
266                                if (failedCallback != null) {
267                                    failedCallback.autoJoinFailed(muc, e);
268                                } else {
269                                    LOGGER.log(Level.WARNING, "Could not leave room", e);
270                                }
271                                return;
272                            }
273                            try {
274                                muc.join(nickname);
275                                if (successCallback != null) {
276                                    successCallback.autoJoinSuccess(muc, nickname);
277                                }
278                            } catch (NotAMucServiceException | NoResponseException | XMPPErrorException
279                                    | NotConnectedException | InterruptedException e) {
280                                if (failedCallback != null) {
281                                    failedCallback.autoJoinFailed(muc, e);
282                                } else {
283                                    LOGGER.log(Level.WARNING, "Could not leave room", e);
284                                }
285                                return;
286                            }
287                        }
288                    }
289
290                });
291            }
292        });
293    }
294
295    /**
296     * Creates a multi user chat. Note: no information is sent to or received from the server until you attempt to
297     * {@link MultiUserChat#join(org.jxmpp.jid.parts.Resourcepart) join} the chat room. On some server implementations, the room will not be
298     * created until the first person joins it.
299     * <p>
300     * Most XMPP servers use a sub-domain for the chat service (eg chat.example.com for the XMPP server example.com).
301     * You must ensure that the room address you're trying to connect to includes the proper chat sub-domain.
302     * </p>
303     *
304     * @param jid the name of the room in the form "roomName@service", where "service" is the hostname at which the
305     *        multi-user chat service is running. Make sure to provide a valid JID.
306     * @return MultiUserChat instance of the room with the given jid.
307     */
308    public synchronized MultiUserChat getMultiUserChat(EntityBareJid jid) {
309        WeakReference<MultiUserChat> weakRefMultiUserChat = multiUserChats.get(jid);
310        if (weakRefMultiUserChat == null) {
311            return createNewMucAndAddToMap(jid);
312        }
313        MultiUserChat multiUserChat = weakRefMultiUserChat.get();
314        if (multiUserChat == null) {
315            return createNewMucAndAddToMap(jid);
316        }
317        return multiUserChat;
318    }
319
320    public static boolean addDefaultMessageInterceptor(MucMessageInterceptor messageInterceptor) {
321        synchronized (DEFAULT_MESSAGE_INTERCEPTORS) {
322            return DEFAULT_MESSAGE_INTERCEPTORS.add(messageInterceptor);
323        }
324    }
325
326    public static boolean removeDefaultMessageInterceptor(MucMessageInterceptor messageInterceptor) {
327        synchronized (DEFAULT_MESSAGE_INTERCEPTORS) {
328            return DEFAULT_MESSAGE_INTERCEPTORS.remove(messageInterceptor);
329        }
330    }
331
332    private MultiUserChat createNewMucAndAddToMap(EntityBareJid jid) {
333        MultiUserChat multiUserChat = new MultiUserChat(connection(), jid, this);
334        multiUserChats.put(jid, new WeakReference<MultiUserChat>(multiUserChat));
335        return multiUserChat;
336    }
337
338    /**
339     * Returns true if the specified user supports the Multi-User Chat protocol.
340     *
341     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
342     * @return a boolean indicating whether the specified user supports the MUC protocol.
343     * @throws XMPPErrorException if there was an XMPP error returned.
344     * @throws NoResponseException if there was no response from the remote entity.
345     * @throws NotConnectedException if the XMPP connection is not connected.
346     * @throws InterruptedException if the calling thread was interrupted.
347     */
348    public boolean isServiceEnabled(Jid user) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
349        return serviceDiscoveryManager.supportsFeature(user, MUCInitialPresence.NAMESPACE);
350    }
351
352    /**
353     * Returns a Set of the rooms where the user has joined. The Iterator will contain Strings where each String
354     * represents a room (e.g. room@muc.jabber.org).
355     *
356     * Note: In order to get a list of bookmarked (but not necessarily joined) conferences, use
357     * {@link org.jivesoftware.smackx.bookmarks.BookmarkManager#getBookmarkedConferences()}.
358     *
359     * @return a List of the rooms where the user has joined using a given connection.
360     */
361    public Set<EntityBareJid> getJoinedRooms() {
362        return Collections.unmodifiableSet(joinedRooms);
363    }
364
365    /**
366     * Returns a List of the rooms where the requested user has joined. The Iterator will contain Strings where each
367     * String represents a room (e.g. room@muc.jabber.org).
368     *
369     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
370     * @return a List of the rooms where the requested user has joined.
371     * @throws XMPPErrorException if there was an XMPP error returned.
372     * @throws NoResponseException if there was no response from the remote entity.
373     * @throws NotConnectedException if the XMPP connection is not connected.
374     * @throws InterruptedException if the calling thread was interrupted.
375     */
376    public List<EntityBareJid> getJoinedRooms(EntityFullJid user) throws NoResponseException, XMPPErrorException,
377                    NotConnectedException, InterruptedException {
378        // Send the disco packet to the user
379        DiscoverItems result = serviceDiscoveryManager.discoverItems(user, DISCO_NODE);
380        List<DiscoverItems.Item> items = result.getItems();
381        List<EntityBareJid> answer = new ArrayList<>(items.size());
382        // Collect the entityID for each returned item
383        for (DiscoverItems.Item item : items) {
384            EntityBareJid muc = item.getEntityID().asEntityBareJidIfPossible();
385            if (muc == null) {
386                LOGGER.warning("Not a bare JID: " + item.getEntityID());
387                continue;
388            }
389            answer.add(muc);
390        }
391        return answer;
392    }
393
394    /**
395     * Returns the discovered information of a given room without actually having to join the room. The server will
396     * provide information only for rooms that are public.
397     *
398     * @param room the name of the room in the form "roomName@service" of which we want to discover its information.
399     * @return the discovered information of a given room without actually having to join the room.
400     * @throws XMPPErrorException if there was an XMPP error returned.
401     * @throws NoResponseException if there was no response from the remote entity.
402     * @throws NotConnectedException if the XMPP connection is not connected.
403     * @throws InterruptedException if the calling thread was interrupted.
404     */
405    public RoomInfo getRoomInfo(EntityBareJid room) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
406        DiscoverInfo info = serviceDiscoveryManager.discoverInfo(room);
407        return new RoomInfo(info);
408    }
409
410    /**
411     * Returns a collection with the XMPP addresses of the Multi-User Chat services.
412     *
413     * @return a collection with the XMPP addresses of the Multi-User Chat services.
414     * @throws XMPPErrorException if there was an XMPP error returned.
415     * @throws NoResponseException if there was no response from the remote entity.
416     * @throws NotConnectedException if the XMPP connection is not connected.
417     * @throws InterruptedException if the calling thread was interrupted.
418     */
419    public List<DomainBareJid> getMucServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
420        return serviceDiscoveryManager.findServices(MUCInitialPresence.NAMESPACE, false, false);
421    }
422
423    /**
424     * Returns a collection with the XMPP addresses of the Multi-User Chat services.
425     *
426     * @return a collection with the XMPP addresses of the Multi-User Chat services.
427     * @throws XMPPErrorException if there was an XMPP error returned.
428     * @throws NoResponseException if there was no response from the remote entity.
429     * @throws NotConnectedException if the XMPP connection is not connected.
430     * @throws InterruptedException if the calling thread was interrupted.
431     * @deprecated use {@link #getMucServiceDomains()} instead.
432     */
433    // TODO: Remove in Smack 4.5
434    @Deprecated
435    public List<DomainBareJid> getXMPPServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
436        return getMucServiceDomains();
437    }
438
439    /**
440     * Check if the provided domain bare JID provides a MUC service.
441     *
442     * @param domainBareJid the domain bare JID to check.
443     * @return <code>true</code> if the provided JID provides a MUC service, <code>false</code> otherwise.
444     * @throws NoResponseException if there was no response from the remote entity.
445     * @throws XMPPErrorException if there was an XMPP error returned.
446     * @throws NotConnectedException if the XMPP connection is not connected.
447     * @throws InterruptedException if the calling thread was interrupted.
448     * @see <a href="http://xmpp.org/extensions/xep-0045.html#disco-service-features">XEP-45 § 6.2 Discovering the Features Supported by a MUC Service</a>
449     * @since 4.2
450     */
451    public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException,
452                    XMPPErrorException, NotConnectedException, InterruptedException {
453        return getMucServiceDiscoInfo(domainBareJid) != null;
454    }
455
456    DiscoverInfo getMucServiceDiscoInfo(DomainBareJid mucServiceAddress)
457                    throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
458        DiscoverInfo discoInfo = KNOWN_MUC_SERVICES.get(mucServiceAddress);
459        if (discoInfo != null) {
460            return discoInfo;
461        }
462
463        discoInfo = serviceDiscoveryManager.discoverInfo(mucServiceAddress);
464        if (!discoInfo.containsFeature(MUCInitialPresence.NAMESPACE)) {
465            return null;
466        }
467
468        KNOWN_MUC_SERVICES.put(mucServiceAddress, discoInfo);
469        return discoInfo;
470    }
471
472    /**
473     * Returns a Map of HostedRooms where each HostedRoom has the XMPP address of the room and the room's name.
474     * Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or
475     * join the room.
476     *
477     * @param serviceName the service that is hosting the rooms to discover.
478     * @return a map from the room's address to its HostedRoom information.
479     * @throws XMPPErrorException if there was an XMPP error returned.
480     * @throws NoResponseException if there was no response from the remote entity.
481     * @throws NotConnectedException if the XMPP connection is not connected.
482     * @throws InterruptedException if the calling thread was interrupted.
483     * @throws NotAMucServiceException if the entity is not a MUC serivce.
484     * @since 4.3.1
485     */
486    public Map<EntityBareJid, HostedRoom> getRoomsHostedBy(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException,
487                    NotConnectedException, InterruptedException, NotAMucServiceException {
488        if (!providesMucService(serviceName)) {
489            throw new NotAMucServiceException(serviceName);
490        }
491        DiscoverItems discoverItems = serviceDiscoveryManager.discoverItems(serviceName);
492        List<DiscoverItems.Item> items = discoverItems.getItems();
493
494        Map<EntityBareJid, HostedRoom> answer = new HashMap<>(items.size());
495        for (DiscoverItems.Item item : items) {
496            HostedRoom hostedRoom = new HostedRoom(item);
497            HostedRoom previousRoom = answer.put(hostedRoom.getJid(), hostedRoom);
498            assert previousRoom == null;
499        }
500
501        return answer;
502    }
503
504    /**
505     * Informs the sender of an invitation that the invitee declines the invitation. The rejection will be sent to the
506     * room which in turn will forward the rejection to the inviter.
507     *
508     * @param room the room that sent the original invitation.
509     * @param inviter the inviter of the declined invitation.
510     * @param reason the reason why the invitee is declining the invitation.
511     * @throws NotConnectedException if the XMPP connection is not connected.
512     * @throws InterruptedException if the calling thread was interrupted.
513     */
514    public void decline(EntityBareJid room, EntityBareJid inviter, String reason) throws NotConnectedException, InterruptedException {
515        XMPPConnection connection = connection();
516
517        MessageBuilder messageBuilder = connection.getStanzaFactory().buildMessageStanza().to(room);
518
519        // Create the MUCUser packet that will include the rejection
520        MUCUser mucUser = new MUCUser();
521        MUCUser.Decline decline = new MUCUser.Decline(reason, inviter);
522        mucUser.setDecline(decline);
523        // Add the MUCUser packet that includes the rejection
524        messageBuilder.addExtension(mucUser);
525
526        connection.sendStanza(messageBuilder.build());
527    }
528
529    /**
530     * Adds a listener to invitation notifications. The listener will be fired anytime an invitation is received.
531     *
532     * @param listener an invitation listener.
533     */
534    public void addInvitationListener(InvitationListener listener) {
535        invitationsListeners.add(listener);
536    }
537
538    /**
539     * Removes a listener to invitation notifications. The listener will be fired anytime an invitation is received.
540     *
541     * @param listener an invitation listener.
542     */
543    public void removeInvitationListener(InvitationListener listener) {
544        invitationsListeners.remove(listener);
545    }
546
547    /**
548     * If automatic join on reconnect is enabled, then the manager will try to auto join MUC rooms after the connection
549     * got re-established.
550     *
551     * @param autoJoin <code>true</code> to enable, <code>false</code> to disable.
552     */
553    public void setAutoJoinOnReconnect(boolean autoJoin) {
554        autoJoinOnReconnect = autoJoin;
555    }
556
557    /**
558     * Set a callback invoked by this manager when automatic join on reconnect failed. If failedCallback is not
559     * <code>null</code>, then automatic rejoin get also enabled.
560     *
561     * @param failedCallback the callback.
562     */
563    public void setAutoJoinFailedCallback(AutoJoinFailedCallback failedCallback) {
564        autoJoinFailedCallback = failedCallback;
565        if (failedCallback != null) {
566            setAutoJoinOnReconnect(true);
567        }
568    }
569
570    /**
571     * Set a callback invoked by this manager when automatic join on reconnect success.
572     * If successCallback is not <code>null</code>, automatic rejoin will also
573     * be enabled.
574     *
575     * @param successCallback the callback
576     */
577    public void setAutoJoinSuccessCallback(AutoJoinSuccessCallback successCallback) {
578        autoJoinSuccessCallback = successCallback;
579        if (successCallback != null) {
580            setAutoJoinOnReconnect(true);
581        }
582    }
583
584
585    void addJoinedRoom(EntityBareJid room) {
586        joinedRooms.add(room);
587    }
588
589    void removeJoinedRoom(EntityBareJid room) {
590        joinedRooms.remove(room);
591    }
592
593    static CopyOnWriteArrayList<MucMessageInterceptor> getMessageInterceptors() {
594        synchronized (DEFAULT_MESSAGE_INTERCEPTORS) {
595            return new CopyOnWriteArrayList<>(DEFAULT_MESSAGE_INTERCEPTORS);
596        }
597    }
598}