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     * @return MultiUserChat instance of the room with the given jid.
244     */
245    public synchronized MultiUserChat getMultiUserChat(EntityBareJid jid) {
246        WeakReference<MultiUserChat> weakRefMultiUserChat = multiUserChats.get(jid);
247        if (weakRefMultiUserChat == null) {
248            return createNewMucAndAddToMap(jid);
249        }
250        MultiUserChat multiUserChat = weakRefMultiUserChat.get();
251        if (multiUserChat == null) {
252            return createNewMucAndAddToMap(jid);
253        }
254        return multiUserChat;
255    }
256
257    private MultiUserChat createNewMucAndAddToMap(EntityBareJid jid) {
258        MultiUserChat multiUserChat = new MultiUserChat(connection(), jid, this);
259        multiUserChats.put(jid, new WeakReference<MultiUserChat>(multiUserChat));
260        return multiUserChat;
261    }
262
263    /**
264     * Returns true if the specified user supports the Multi-User Chat protocol.
265     *
266     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
267     * @return a boolean indicating whether the specified user supports the MUC protocol.
268     * @throws XMPPErrorException
269     * @throws NoResponseException
270     * @throws NotConnectedException
271     * @throws InterruptedException 
272     */
273    public boolean isServiceEnabled(Jid user) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
274        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(user, MUCInitialPresence.NAMESPACE);
275    }
276
277    /**
278     * Returns a Set of the rooms where the user has joined. The Iterator will contain Strings where each String
279     * represents a room (e.g. room@muc.jabber.org).
280     *
281     * @return a List of the rooms where the user has joined using a given connection.
282     */
283    public Set<EntityBareJid> getJoinedRooms() {
284        return Collections.unmodifiableSet(joinedRooms);
285    }
286
287    /**
288     * Returns a List of the rooms where the requested user has joined. The Iterator will contain Strings where each
289     * String represents a room (e.g. room@muc.jabber.org).
290     *
291     * @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
292     * @return a List of the rooms where the requested user has joined.
293     * @throws XMPPErrorException
294     * @throws NoResponseException
295     * @throws NotConnectedException
296     * @throws InterruptedException 
297     */
298    public List<EntityBareJid> getJoinedRooms(EntityJid user) throws NoResponseException, XMPPErrorException,
299                    NotConnectedException, InterruptedException {
300        // Send the disco packet to the user
301        DiscoverItems result = ServiceDiscoveryManager.getInstanceFor(connection()).discoverItems(user, DISCO_NODE);
302        List<DiscoverItems.Item> items = result.getItems();
303        List<EntityBareJid> answer = new ArrayList<>(items.size());
304        // Collect the entityID for each returned item
305        for (DiscoverItems.Item item : items) {
306            EntityBareJid muc = item.getEntityID().asEntityBareJidIfPossible();
307            if (muc == null) {
308                LOGGER.warning("Not a bare JID: " + item.getEntityID());
309                continue;
310            }
311            answer.add(muc);
312        }
313        return answer;
314    }
315
316    /**
317     * Returns the discovered information of a given room without actually having to join the room. The server will
318     * provide information only for rooms that are public.
319     *
320     * @param room the name of the room in the form "roomName@service" of which we want to discover its information.
321     * @return the discovered information of a given room without actually having to join the room.
322     * @throws XMPPErrorException
323     * @throws NoResponseException
324     * @throws NotConnectedException
325     * @throws InterruptedException 
326     */
327    public RoomInfo getRoomInfo(EntityBareJid room) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
328        DiscoverInfo info = ServiceDiscoveryManager.getInstanceFor(connection()).discoverInfo(room);
329        return new RoomInfo(info);
330    }
331
332    /**
333     * Returns a collection with the XMPP addresses of the Multi-User Chat services.
334     *
335     * @return a collection with the XMPP addresses of the Multi-User Chat services.
336     * @throws XMPPErrorException
337     * @throws NoResponseException
338     * @throws NotConnectedException
339     * @throws InterruptedException 
340     */
341    public List<DomainBareJid> getXMPPServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
342        ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection());
343        return sdm.findServices(MUCInitialPresence.NAMESPACE, false, false);
344    }
345
346    /**
347     * Check if the provided domain bare JID provides a MUC service.
348     * 
349     * @param domainBareJid the domain bare JID to check.
350     * @return <code>true</code> if the provided JID provides a MUC service, <code>false</code> otherwise.
351     * @throws NoResponseException
352     * @throws XMPPErrorException
353     * @throws NotConnectedException
354     * @throws InterruptedException
355     * @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>
356     * @since 4.2
357     */
358    public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException,
359                    XMPPErrorException, NotConnectedException, InterruptedException {
360        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(domainBareJid,
361                        MUCInitialPresence.NAMESPACE);
362    }
363
364    /**
365     * Returns a List of HostedRooms where each HostedRoom has the XMPP address of the room and the room's name.
366     * Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or
367     * join the room.
368     *
369     * @param serviceName the service that is hosting the rooms to discover.
370     * @return a collection of HostedRooms.
371     * @throws XMPPErrorException
372     * @throws NoResponseException
373     * @throws NotConnectedException
374     * @throws InterruptedException 
375     * @throws NotAMucServiceException 
376     */
377    public List<HostedRoom> getHostedRooms(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException,
378                    NotConnectedException, InterruptedException, NotAMucServiceException {
379        if (!providesMucService(serviceName)) {
380            throw new NotAMucServiceException(serviceName);
381        }
382        ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection());
383        DiscoverItems discoverItems = discoManager.discoverItems(serviceName);
384        List<DiscoverItems.Item> items = discoverItems.getItems();
385        List<HostedRoom> answer = new ArrayList<HostedRoom>(items.size());
386        for (DiscoverItems.Item item : items) {
387            answer.add(new HostedRoom(item));
388        }
389        return answer;
390    }
391
392    /**
393     * Informs the sender of an invitation that the invitee declines the invitation. The rejection will be sent to the
394     * room which in turn will forward the rejection to the inviter.
395     *
396     * @param room the room that sent the original invitation.
397     * @param inviter the inviter of the declined invitation.
398     * @param reason the reason why the invitee is declining the invitation.
399     * @throws NotConnectedException
400     * @throws InterruptedException 
401     */
402    public void decline(EntityBareJid room, EntityBareJid inviter, String reason) throws NotConnectedException, InterruptedException {
403        Message message = new Message(room);
404
405        // Create the MUCUser packet that will include the rejection
406        MUCUser mucUser = new MUCUser();
407        MUCUser.Decline decline = new MUCUser.Decline(reason, inviter);
408        mucUser.setDecline(decline);
409        // Add the MUCUser packet that includes the rejection
410        message.addExtension(mucUser);
411
412        connection().sendStanza(message);
413    }
414
415    /**
416     * Adds a listener to invitation notifications. The listener will be fired anytime an invitation is received.
417     *
418     * @param listener an invitation listener.
419     */
420    public void addInvitationListener(InvitationListener listener) {
421        invitationsListeners.add(listener);
422    }
423
424    /**
425     * Removes a listener to invitation notifications. The listener will be fired anytime an invitation is received.
426     *
427     * @param listener an invitation listener.
428     */
429    public void removeInvitationListener(InvitationListener listener) {
430        invitationsListeners.remove(listener);
431    }
432
433    /**
434     * If automatic join on reconnect is enabled, then the manager will try to auto join MUC rooms after the connection
435     * got re-established.
436     *
437     * @param autoJoin <code>true</code> to enable, <code>false</code> to disable.
438     */
439    public void setAutoJoinOnReconnect(boolean autoJoin) {
440        autoJoinOnReconnect = autoJoin;
441    }
442
443    /**
444     * Set a callback invoked by this manager when automatic join on reconnect failed. If failedCallback is not
445     * <code>null</code>,then automatic rejoin get also enabled.
446     *
447     * @param failedCallback the callback.
448     */
449    public void setAutoJoinFailedCallback(AutoJoinFailedCallback failedCallback) {
450        autoJoinFailedCallback = failedCallback;
451        if (failedCallback != null) {
452            setAutoJoinOnReconnect(true);
453        }
454    }
455
456    void addJoinedRoom(EntityBareJid room) {
457        joinedRooms.add(room);
458    }
459
460    void removeJoinedRoom(EntityBareJid room) {
461        joinedRooms.remove(room);
462    }
463}