001/**
002 *
003 * Copyright © 2014-2017 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.CopyOnWriteArraySet;
029import java.util.logging.Level;
030import java.util.logging.Logger;
031
032import org.jivesoftware.smack.AbstractConnectionListener;
033import org.jivesoftware.smack.ConnectionCreationListener;
034import org.jivesoftware.smack.Manager;
035import org.jivesoftware.smack.SmackException.NoResponseException;
036import org.jivesoftware.smack.SmackException.NotConnectedException;
037import org.jivesoftware.smack.StanzaListener;
038import org.jivesoftware.smack.XMPPConnection;
039import org.jivesoftware.smack.XMPPConnectionRegistry;
040import org.jivesoftware.smack.XMPPException.XMPPErrorException;
041import org.jivesoftware.smack.filter.AndFilter;
042import org.jivesoftware.smack.filter.MessageTypeFilter;
043import org.jivesoftware.smack.filter.NotFilter;
044import org.jivesoftware.smack.filter.StanzaExtensionFilter;
045import org.jivesoftware.smack.filter.StanzaFilter;
046import org.jivesoftware.smack.filter.StanzaTypeFilter;
047import org.jivesoftware.smack.packet.Message;
048import org.jivesoftware.smack.packet.Stanza;
049import org.jivesoftware.smack.util.Async;
050
051import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider;
052import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
053import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
054import org.jivesoftware.smackx.disco.packet.DiscoverItems;
055import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
056import org.jivesoftware.smackx.muc.packet.MUCInitialPresence;
057import org.jivesoftware.smackx.muc.packet.MUCUser;
058
059import org.jxmpp.jid.DomainBareJid;
060import org.jxmpp.jid.EntityBareJid;
061import org.jxmpp.jid.EntityJid;
062import org.jxmpp.jid.Jid;
063import org.jxmpp.jid.parts.Resourcepart;
064
065/**
066 * A manager for Multi-User Chat rooms.
067 * <p>
068 * Use {@link #getMultiUserChat(EntityBareJid)} to retrieve an object representing a Multi-User Chat room.
069 * </p>
070 * <p>
071 * <b>Automatic rejoin:</b> The manager supports automatic rejoin of MultiUserChat rooms once the connection got
072 * re-established. This mechanism is disabled by default. To enable it, use {@link #setAutoJoinOnReconnect(boolean)}.
073 * You can set a {@link AutoJoinFailedCallback} via {@link #setAutoJoinFailedCallback(AutoJoinFailedCallback)} to get
074 * notified if this mechanism failed for some reason. Note that as soon as rejoining for a single room failed, no
075 * further attempts will be made for the other rooms.
076 * </p>
077 * 
078 * @see <a href="http://xmpp.org/extensions/xep-0045.html">XEP-0045: Multi-User Chat</a>
079 */
080public final class MultiUserChatManager extends Manager {
081    private final static String DISCO_NODE = MUCInitialPresence.NAMESPACE + "#rooms";
082
083    private static final Logger LOGGER = Logger.getLogger(MultiUserChatManager.class.getName());
084
085    static {
086        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
087            @Override
088            public void connectionCreated(final XMPPConnection connection) {
089                // Set on every established connection that this client supports the Multi-User
090                // Chat protocol. This information will be used when another client tries to
091                // discover whether this client supports MUC or not.
092                ServiceDiscoveryManager.getInstanceFor(connection).addFeature(MUCInitialPresence.NAMESPACE);
093
094                // Set the NodeInformationProvider that will provide information about the
095                // joined rooms whenever a disco request is received
096                final WeakReference<XMPPConnection> weakRefConnection = new WeakReference<XMPPConnection>(connection);
097                ServiceDiscoveryManager.getInstanceFor(connection).setNodeInformationProvider(DISCO_NODE,
098                                new AbstractNodeInformationProvider() {
099                                    @Override
100                                    public List<DiscoverItems.Item> getNodeItems() {
101                                        XMPPConnection connection = weakRefConnection.get();
102                                        if (connection == null)
103                                            return Collections.emptyList();
104                                        Set<EntityBareJid> joinedRooms = MultiUserChatManager.getInstanceFor(connection).getJoinedRooms();
105                                        List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>();
106                                        for (EntityBareJid room : joinedRooms) {
107                                            answer.add(new DiscoverItems.Item(room));
108                                        }
109                                        return answer;
110                                    }
111                                });
112            }
113        });
114    }
115
116    private static final Map<XMPPConnection, MultiUserChatManager> INSTANCES = new WeakHashMap<XMPPConnection, MultiUserChatManager>();
117
118    /**
119     * Get a instance of a multi user chat manager for the given connection.
120     * 
121     * @param connection
122     * @return a multi user chat manager.
123     */
124    public static synchronized MultiUserChatManager getInstanceFor(XMPPConnection connection) {
125        MultiUserChatManager multiUserChatManager = INSTANCES.get(connection);
126        if (multiUserChatManager == null) {
127            multiUserChatManager = new MultiUserChatManager(connection);
128            INSTANCES.put(connection, multiUserChatManager);
129        }
130        return multiUserChatManager;
131    }
132
133    private static final StanzaFilter INVITATION_FILTER = new AndFilter(StanzaTypeFilter.MESSAGE, new StanzaExtensionFilter(new MUCUser()),
134                    new NotFilter(MessageTypeFilter.ERROR));
135
136    private final Set<InvitationListener> invitationsListeners = new CopyOnWriteArraySet<InvitationListener>();
137    private final Set<EntityBareJid> joinedRooms = new HashSet<>();
138
139    /**
140     * A Map of MUC JIDs to {@link MultiUserChat} instances. We use weak references for the values in order to allow
141     * those instances to get garbage collected. Note that MultiUserChat instances can not get garbage collected while
142     * the user is joined, because then the MUC will have PacketListeners added to the XMPPConnection.
143     */
144    private final Map<EntityBareJid, WeakReference<MultiUserChat>> multiUserChats = new HashMap<>();
145
146    private boolean autoJoinOnReconnect;
147
148    private AutoJoinFailedCallback autoJoinFailedCallback;
149
150    private MultiUserChatManager(XMPPConnection connection) {
151        super(connection);
152        // Listens for all messages that include a MUCUser extension and fire the invitation
153        // listeners if the message includes an invitation.
154        StanzaListener invitationPacketListener = new StanzaListener() {
155            @Override
156            public void processStanza(Stanza packet) {
157                final Message message = (Message) packet;
158                // Get the MUCUser extension
159                final MUCUser mucUser = MUCUser.from(message);
160                // Check if the MUCUser extension includes an invitation
161                if (mucUser.getInvite() != null) {
162                    EntityBareJid mucJid = message.getFrom().asEntityBareJidIfPossible();
163                    if (mucJid == null) {
164                        LOGGER.warning("Invite to non bare JID: '" + message.toXML() + "'");
165                        return;
166                    }
167                    // Fire event for invitation listeners
168                    final MultiUserChat muc = getMultiUserChat(mucJid);
169                    final XMPPConnection connection = connection();
170                    final MUCUser.Invite invite = mucUser.getInvite();
171                    final EntityJid from = invite.getFrom();
172                    final String reason = invite.getReason();
173                    final String password = mucUser.getPassword();
174                    for (final InvitationListener listener : invitationsListeners) {
175                        listener.invitationReceived(connection, muc, from, reason, password, message, invite);
176                    }
177                }
178            }
179        };
180        connection.addAsyncStanzaListener(invitationPacketListener, INVITATION_FILTER);
181
182        connection.addConnectionListener(new AbstractConnectionListener() {
183            @Override
184            public void authenticated(XMPPConnection connection, boolean resumed) {
185                if (resumed) return;
186                if (!autoJoinOnReconnect) return;
187
188                final Set<EntityBareJid> mucs = getJoinedRooms();
189                if (mucs.isEmpty()) return;
190
191                Async.go(new Runnable() {
192                    @Override
193                    public void run() {
194                        final AutoJoinFailedCallback failedCallback = autoJoinFailedCallback;
195                        for (EntityBareJid mucJid : mucs) {
196                            MultiUserChat muc = getMultiUserChat(mucJid);
197
198                            if (!muc.isJoined()) return;
199
200                            Resourcepart nickname = muc.getNickname();
201                            if (nickname == null) return;
202
203                            try {
204                                muc.leave();
205                            } catch (NotConnectedException | InterruptedException e) {
206                                if (failedCallback != null) {
207                                    failedCallback.autoJoinFailed(muc, e);
208                                } else {
209                                    LOGGER.log(Level.WARNING, "Could not leave room", e);
210                                }
211                                return;
212                            }
213                            try {
214                                muc.join(nickname);
215                            } catch (NotAMucServiceException | NoResponseException | XMPPErrorException
216                                    | NotConnectedException | InterruptedException e) {
217                                if (failedCallback != null) {
218                                    failedCallback.autoJoinFailed(muc, e);
219                                } else {
220                                    LOGGER.log(Level.WARNING, "Could not leave room", e);
221                                }
222                                return;
223                            }
224                        }
225                    }
226
227                });
228            }
229        });
230    }
231
232    /**
233     * Creates a multi user chat. Note: no information is sent to or received from the server until you attempt to
234     * {@link MultiUserChat#join(org.jxmpp.jid.parts.Resourcepart) join} the chat room. On some server implementations, the room will not be
235     * created until the first person joins it.
236     * <p>
237     * Most XMPP servers use a sub-domain for the chat service (eg chat.example.com for the XMPP server example.com).
238     * You must ensure that the room address you're trying to connect to includes the proper chat sub-domain.
239     * </p>
240     *
241     * @param jid the name of the room in the form "roomName@service", where "service" is the hostname at which the
242     *        multi-user chat service is running. Make sure to provide a valid JID.
243     */
244    public synchronized MultiUserChat getMultiUserChat(EntityBareJid jid) {
245        WeakReference<MultiUserChat> weakRefMultiUserChat = multiUserChats.get(jid);
246        if (weakRefMultiUserChat == null) {
247            return createNewMucAndAddToMap(jid);
248        }
249        MultiUserChat multiUserChat = weakRefMultiUserChat.get();
250        if (multiUserChat == null) {
251            return createNewMucAndAddToMap(jid);
252        }
253        return multiUserChat;
254    }
255
256    private MultiUserChat createNewMucAndAddToMap(EntityBareJid jid) {
257        MultiUserChat multiUserChat = new MultiUserChat(connection(), jid, this);
258        multiUserChats.put(jid, new WeakReference<MultiUserChat>(multiUserChat));
259        return multiUserChat;
260    }
261
262    /**
263     * Returns true if the specified user supports the Multi-User Chat protocol.
264     *
265     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
266     * @return a boolean indicating whether the specified user supports the MUC protocol.
267     * @throws XMPPErrorException
268     * @throws NoResponseException
269     * @throws NotConnectedException
270     * @throws InterruptedException 
271     */
272    public boolean isServiceEnabled(Jid user) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
273        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(user, MUCInitialPresence.NAMESPACE);
274    }
275
276    /**
277     * Returns a Set of the rooms where the user has joined. The Iterator will contain Strings where each String
278     * represents a room (e.g. room@muc.jabber.org).
279     *
280     * @return a List of the rooms where the user has joined using a given connection.
281     */
282    public Set<EntityBareJid> getJoinedRooms() {
283        return Collections.unmodifiableSet(joinedRooms);
284    }
285
286    /**
287     * Returns a List of the rooms where the requested user has joined. The Iterator will contain Strings where each
288     * String represents a room (e.g. room@muc.jabber.org).
289     *
290     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
291     * @return a List of the rooms where the requested user has joined.
292     * @throws XMPPErrorException
293     * @throws NoResponseException
294     * @throws NotConnectedException
295     * @throws InterruptedException 
296     */
297    public List<EntityBareJid> getJoinedRooms(EntityJid user) throws NoResponseException, XMPPErrorException,
298                    NotConnectedException, InterruptedException {
299        // Send the disco packet to the user
300        DiscoverItems result = ServiceDiscoveryManager.getInstanceFor(connection()).discoverItems(user, DISCO_NODE);
301        List<DiscoverItems.Item> items = result.getItems();
302        List<EntityBareJid> answer = new ArrayList<>(items.size());
303        // Collect the entityID for each returned item
304        for (DiscoverItems.Item item : items) {
305            EntityBareJid muc = item.getEntityID().asEntityBareJidIfPossible();
306            if (muc == null) {
307                LOGGER.warning("Not a bare JID: " + item.getEntityID());
308                continue;
309            }
310            answer.add(muc);
311        }
312        return answer;
313    }
314
315    /**
316     * Returns the discovered information of a given room without actually having to join the room. The server will
317     * provide information only for rooms that are public.
318     *
319     * @param room the name of the room in the form "roomName@service" of which we want to discover its information.
320     * @return the discovered information of a given room without actually having to join the room.
321     * @throws XMPPErrorException
322     * @throws NoResponseException
323     * @throws NotConnectedException
324     * @throws InterruptedException 
325     */
326    public RoomInfo getRoomInfo(EntityBareJid room) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
327        DiscoverInfo info = ServiceDiscoveryManager.getInstanceFor(connection()).discoverInfo(room);
328        return new RoomInfo(info);
329    }
330
331    /**
332     * Returns a collection with the XMPP addresses of the Multi-User Chat services.
333     *
334     * @return a collection with the XMPP addresses of the Multi-User Chat services.
335     * @throws XMPPErrorException
336     * @throws NoResponseException
337     * @throws NotConnectedException
338     * @throws InterruptedException 
339     */
340    public List<DomainBareJid> getXMPPServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
341        ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection());
342        return sdm.findServices(MUCInitialPresence.NAMESPACE, false, false);
343    }
344
345    /**
346     * Check if the provided domain bare JID provides a MUC service.
347     * 
348     * @param domainBareJid the domain bare JID to check.
349     * @return <code>true</code> if the provided JID provides a MUC service, <code>false</code> otherwise.
350     * @throws NoResponseException
351     * @throws XMPPErrorException
352     * @throws NotConnectedException
353     * @throws InterruptedException
354     * @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>
355     * @since 4.2
356     */
357    public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException,
358                    XMPPErrorException, NotConnectedException, InterruptedException {
359        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(domainBareJid,
360                        MUCInitialPresence.NAMESPACE);
361    }
362
363    /**
364     * Returns a List of HostedRooms where each HostedRoom has the XMPP address of the room and the room's name.
365     * Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or
366     * join the room.
367     *
368     * @param serviceName the service that is hosting the rooms to discover.
369     * @return a collection of HostedRooms.
370     * @throws XMPPErrorException
371     * @throws NoResponseException
372     * @throws NotConnectedException
373     * @throws InterruptedException 
374     * @throws NotAMucServiceException 
375     */
376    public List<HostedRoom> getHostedRooms(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException,
377                    NotConnectedException, InterruptedException, NotAMucServiceException {
378        if (!providesMucService(serviceName)) {
379            throw new NotAMucServiceException(serviceName);
380        }
381        ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection());
382        DiscoverItems discoverItems = discoManager.discoverItems(serviceName);
383        List<DiscoverItems.Item> items = discoverItems.getItems();
384        List<HostedRoom> answer = new ArrayList<HostedRoom>(items.size());
385        for (DiscoverItems.Item item : items) {
386            answer.add(new HostedRoom(item));
387        }
388        return answer;
389    }
390
391    /**
392     * Informs the sender of an invitation that the invitee declines the invitation. The rejection will be sent to the
393     * room which in turn will forward the rejection to the inviter.
394     *
395     * @param room the room that sent the original invitation.
396     * @param inviter the inviter of the declined invitation.
397     * @param reason the reason why the invitee is declining the invitation.
398     * @throws NotConnectedException
399     * @throws InterruptedException 
400     */
401    public void decline(EntityBareJid room, EntityBareJid inviter, String reason) throws NotConnectedException, InterruptedException {
402        Message message = new Message(room);
403
404        // Create the MUCUser packet that will include the rejection
405        MUCUser mucUser = new MUCUser();
406        MUCUser.Decline decline = new MUCUser.Decline(reason, inviter);
407        mucUser.setDecline(decline);
408        // Add the MUCUser packet that includes the rejection
409        message.addExtension(mucUser);
410
411        connection().sendStanza(message);
412    }
413
414    /**
415     * Adds a listener to invitation notifications. The listener will be fired anytime an invitation is received.
416     *
417     * @param listener an invitation listener.
418     */
419    public void addInvitationListener(InvitationListener listener) {
420        invitationsListeners.add(listener);
421    }
422
423    /**
424     * Removes a listener to invitation notifications. The listener will be fired anytime an invitation is received.
425     *
426     * @param listener an invitation listener.
427     */
428    public void removeInvitationListener(InvitationListener listener) {
429        invitationsListeners.remove(listener);
430    }
431
432    /**
433     * If automatic join on reconnect is enabled, then the manager will try to auto join MUC rooms after the connection
434     * got re-established.
435     *
436     * @param autoJoin <code>true</code> to enable, <code>false</code> to disable.
437     */
438    public void setAutoJoinOnReconnect(boolean autoJoin) {
439        autoJoinOnReconnect = autoJoin;
440    }
441
442    /**
443     * Set a callback invoked by this manager when automatic join on reconnect failed. If failedCallback is not
444     * <code>null</code>,then automatic rejoin get also enabled.
445     *
446     * @param failedCallback the callback.
447     */
448    public void setAutoJoinFailedCallback(AutoJoinFailedCallback failedCallback) {
449        autoJoinFailedCallback = failedCallback;
450        if (failedCallback != null) {
451            setAutoJoinOnReconnect(true);
452        }
453    }
454
455    void addJoinedRoom(EntityBareJid room) {
456        joinedRooms.add(room);
457    }
458
459    void removeJoinedRoom(EntityBareJid room) {
460        joinedRooms.remove(room);
461    }
462}