001/**
002 *
003 * Copyright 2003-2006 Jive Software, 2014 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 */
017
018package org.jivesoftware.smackx.iqlast;
019
020import java.util.Map;
021import java.util.WeakHashMap;
022
023import org.jivesoftware.smack.ConnectionCreationListener;
024import org.jivesoftware.smack.Manager;
025import org.jivesoftware.smack.SmackException.NoResponseException;
026import org.jivesoftware.smack.SmackException.NotConnectedException;
027import org.jivesoftware.smack.StanzaListener;
028import org.jivesoftware.smack.XMPPConnection;
029import org.jivesoftware.smack.XMPPConnectionRegistry;
030import org.jivesoftware.smack.XMPPException.XMPPErrorException;
031import org.jivesoftware.smack.filter.StanzaTypeFilter;
032import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
033import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
034import org.jivesoftware.smack.packet.IQ;
035import org.jivesoftware.smack.packet.IQ.Type;
036import org.jivesoftware.smack.packet.Message;
037import org.jivesoftware.smack.packet.Presence;
038import org.jivesoftware.smack.packet.Stanza;
039import org.jivesoftware.smack.packet.StanzaError.Condition;
040
041import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
042import org.jivesoftware.smackx.iqlast.packet.LastActivity;
043
044import org.jxmpp.jid.Jid;
045
046/**
047 * A last activity manager for handling information about the last activity
048 * associated with a Jabber ID. A manager handles incoming LastActivity requests
049 * of existing Connections. It also allows to request last activity information
050 * of other users.
051 *
052 * LastActivity (XEP-0012) based on the sending JID's type allows for retrieval
053 * of:
054 * <ol>
055 * <li>How long a particular user has been idle
056 * <li>How long a particular user has been logged-out and the message the
057 * specified when doing so.
058 * <li>How long a host has been up.
059 * </ol>
060 *
061 * For example to get the idle time of a user logged in a resource, simple send
062 * the LastActivity stanza to them, as in the following code:
063 *
064 * <pre>
065 * XMPPConnection con = new XMPPTCPConnection(&quot;jabber.org&quot;);
066 * con.login(&quot;john&quot;, &quot;doe&quot;);
067 * LastActivity activity = LastActivity.getLastActivity(con, &quot;xray@jabber.org/Smack&quot;);
068 * </pre>
069 *
070 * To get the lapsed time since the last user logout is the same as above but
071 * with out the resource:
072 *
073 * <pre>
074 * LastActivity activity = LastActivity.getLastActivity(con, &quot;xray@jabber.org&quot;);
075 * </pre>
076 *
077 * To get the uptime of a host, you simple send the LastActivity stanza to it,
078 * as in the following code example:
079 *
080 * <pre>
081 * LastActivity activity = LastActivity.getLastActivity(con, &quot;jabber.org&quot;);
082 * </pre>
083 *
084 * @author Gabriel Guardincerri
085 * @author Florian Schmaus
086 * @see <a href="http://xmpp.org/extensions/xep-0012.html">XEP-0012: Last
087 *      Activity</a>
088 */
089
090public final class LastActivityManager extends Manager {
091    private static final Map<XMPPConnection, LastActivityManager> instances = new WeakHashMap<>();
092//    private static final PacketFilter IQ_GET_LAST_FILTER = new AndFilter(IQTypeFilter.GET,
093//                    new StanzaTypeFilter(LastActivity.class));
094
095    private static boolean enabledPerDefault = true;
096
097    /**
098     * Enable or disable Last Activity for new XMPPConnections.
099     *
100     * @param enabledPerDefault TODO javadoc me please
101     */
102    public static void setEnabledPerDefault(boolean enabledPerDefault) {
103        LastActivityManager.enabledPerDefault = enabledPerDefault;
104    }
105
106    // Enable the LastActivity support on every established connection
107    static {
108        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
109            @Override
110            public void connectionCreated(XMPPConnection connection) {
111                LastActivityManager.getInstanceFor(connection);
112            }
113        });
114    }
115
116    public static synchronized LastActivityManager getInstanceFor(XMPPConnection connection) {
117        LastActivityManager lastActivityManager = instances.get(connection);
118        if (lastActivityManager == null)
119            lastActivityManager = new LastActivityManager(connection);
120        return lastActivityManager;
121    }
122
123    private volatile long lastMessageSent;
124    private boolean enabled = false;
125
126    /**
127     * Creates a last activity manager to response last activity requests.
128     *
129     * @param connection TODO javadoc me please
130     *            The XMPPConnection that the last activity requests will use.
131     */
132    private LastActivityManager(XMPPConnection connection) {
133        super(connection);
134
135        // Listen to all the sent messages to reset the idle time on each one
136        connection.addStanzaSendingListener(new StanzaListener() {
137            @Override
138            public void processStanza(Stanza packet) {
139                Presence presence = (Presence) packet;
140                Presence.Mode mode = presence.getMode();
141                if (mode == null) return;
142                switch (mode) {
143                case available:
144                case chat:
145                    // We assume that only a switch to available and chat indicates user activity
146                    // since other mode changes could be also a result of some sort of automatism
147                    resetIdleTime();
148                    break;
149                default:
150                    break;
151                }
152            }
153        }, StanzaTypeFilter.PRESENCE);
154
155        connection.addStanzaSendingListener(new StanzaListener() {
156            @Override
157            public void processStanza(Stanza packet) {
158                Message message = (Message) packet;
159                // if it's not an error message, reset the idle time
160                if (message.getType() == Message.Type.error) return;
161                resetIdleTime();
162            }
163        }, StanzaTypeFilter.MESSAGE);
164
165        // Register a listener for a last activity query
166        connection.registerIQRequestHandler(new AbstractIqRequestHandler(LastActivity.ELEMENT, LastActivity.NAMESPACE,
167                        Type.get, Mode.async) {
168            @Override
169            public IQ handleIQRequest(IQ iqRequest) {
170                if (!enabled)
171                    return IQ.createErrorResponse(iqRequest, Condition.not_acceptable);
172                LastActivity message = new LastActivity();
173                message.setType(IQ.Type.result);
174                message.setTo(iqRequest.getFrom());
175                message.setFrom(iqRequest.getTo());
176                message.setStanzaId(iqRequest.getStanzaId());
177                message.setLastActivity(getIdleTime());
178
179                return message;
180            }
181        });
182
183        if (enabledPerDefault) {
184            enable();
185        }
186        resetIdleTime();
187        instances.put(connection, this);
188    }
189
190    public synchronized void enable() {
191        ServiceDiscoveryManager.getInstanceFor(connection()).addFeature(LastActivity.NAMESPACE);
192        enabled = true;
193    }
194
195    public synchronized void disable() {
196        ServiceDiscoveryManager.getInstanceFor(connection()).removeFeature(LastActivity.NAMESPACE);
197        enabled = false;
198    }
199
200    /**
201     * Resets the idle time to 0, this should be invoked when a new message is
202     * sent.
203     */
204    private void resetIdleTime() {
205        lastMessageSent = System.currentTimeMillis();
206    }
207
208    /**
209     * The idle time is the lapsed time between the last message sent and now.
210     *
211     * @return the lapsed time between the last message sent and now.
212     */
213    private long getIdleTime() {
214        long lms = lastMessageSent;
215        long now = System.currentTimeMillis();
216        return (now - lms) / 1000;
217    }
218
219    /**
220     * Returns the last activity of a particular jid. If the jid is a full JID
221     * (i.e., a JID of the form of 'user@host/resource') then the last activity
222     * is the idle time of that connected resource. On the other hand, when the
223     * jid is a bare JID (e.g. 'user@host') then the last activity is the lapsed
224     * time since the last logout or 0 if the user is currently logged in.
225     * Moreover, when the jid is a server or component (e.g., a JID of the form
226     * 'host') the last activity is the uptime.
227     *
228     * @param jid TODO javadoc me please
229     *            the JID of the user.
230     * @return the LastActivity stanza of the jid.
231     * @throws XMPPErrorException if there was an XMPP error returned.
232     *             thrown if a server error has occurred.
233     * @throws NoResponseException if there was no response from the server.
234     * @throws NotConnectedException if the XMPP connection is not connected.
235     * @throws InterruptedException if the calling thread was interrupted.
236     */
237    public LastActivity getLastActivity(Jid jid) throws NoResponseException, XMPPErrorException,
238                    NotConnectedException, InterruptedException {
239        LastActivity activity = new LastActivity(jid);
240        return (LastActivity) connection().createStanzaCollectorAndSend(activity).nextResultOrThrow();
241    }
242
243    /**
244     * Returns true if Last Activity (XEP-0012) is supported by a given JID.
245     *
246     * @param jid a JID to be tested for Last Activity support
247     * @return true if Last Activity is supported, otherwise false
248     * @throws NotConnectedException if the XMPP connection is not connected.
249     * @throws XMPPErrorException if there was an XMPP error returned.
250     * @throws NoResponseException if there was no response from the remote entity.
251     * @throws InterruptedException if the calling thread was interrupted.
252     */
253    public boolean isLastActivitySupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
254        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, LastActivity.NAMESPACE);
255    }
256}