LastActivityManager.java

  1. /**
  2.  *
  3.  * Copyright 2003-2006 Jive Software, 2014 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.jivesoftware.smackx.iqlast;

  18. import java.util.Map;
  19. import java.util.WeakHashMap;

  20. import org.jivesoftware.smack.SmackException.NoResponseException;
  21. import org.jivesoftware.smack.SmackException.NotConnectedException;
  22. import org.jivesoftware.smack.XMPPConnection;
  23. import org.jivesoftware.smack.ConnectionCreationListener;
  24. import org.jivesoftware.smack.StanzaListener;
  25. import org.jivesoftware.smack.Manager;
  26. import org.jivesoftware.smack.XMPPConnectionRegistry;
  27. import org.jivesoftware.smack.XMPPException.XMPPErrorException;
  28. import org.jivesoftware.smack.filter.StanzaTypeFilter;
  29. import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
  30. import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
  31. import org.jivesoftware.smack.packet.IQ;
  32. import org.jivesoftware.smack.packet.IQ.Type;
  33. import org.jivesoftware.smack.packet.Message;
  34. import org.jivesoftware.smack.packet.Stanza;
  35. import org.jivesoftware.smack.packet.Presence;
  36. import org.jivesoftware.smack.packet.XMPPError;
  37. import org.jivesoftware.smack.packet.XMPPError.Condition;
  38. import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
  39. import org.jivesoftware.smackx.iqlast.packet.LastActivity;
  40. import org.jxmpp.jid.Jid;

  41. /**
  42.  * A last activity manager for handling information about the last activity
  43.  * associated with a Jabber ID. A manager handles incoming LastActivity requests
  44.  * of existing Connections. It also allows to request last activity information
  45.  * of other users.
  46.  * <p>
  47.  *
  48.  * LastActivity (XEP-0012) based on the sending JID's type allows for retrieval
  49.  * of:
  50.  * <ol>
  51.  * <li>How long a particular user has been idle
  52.  * <li>How long a particular user has been logged-out and the message the
  53.  * specified when doing so.
  54.  * <li>How long a host has been up.
  55.  * </ol>
  56.  * <p/>
  57.  *
  58.  * For example to get the idle time of a user logged in a resource, simple send
  59.  * the LastActivity packet to them, as in the following code:
  60.  * <p>
  61.  *
  62.  * <pre>
  63.  * XMPPConnection con = new XMPPTCPConnection(&quot;jabber.org&quot;);
  64.  * con.login(&quot;john&quot;, &quot;doe&quot;);
  65.  * LastActivity activity = LastActivity.getLastActivity(con, &quot;xray@jabber.org/Smack&quot;);
  66.  * </pre>
  67.  *
  68.  * To get the lapsed time since the last user logout is the same as above but
  69.  * with out the resource:
  70.  *
  71.  * <pre>
  72.  * LastActivity activity = LastActivity.getLastActivity(con, &quot;xray@jabber.org&quot;);
  73.  * </pre>
  74.  *
  75.  * To get the uptime of a host, you simple send the LastActivity packet to it,
  76.  * as in the following code example:
  77.  * <p>
  78.  *
  79.  * <pre>
  80.  * LastActivity activity = LastActivity.getLastActivity(con, &quot;jabber.org&quot;);
  81.  * </pre>
  82.  *
  83.  * @author Gabriel Guardincerri
  84.  * @author Florian Schmaus
  85.  * @see <a href="http://xmpp.org/extensions/xep-0012.html">XEP-0012: Last
  86.  *      Activity</a>
  87.  */

  88. public class LastActivityManager extends Manager {
  89.     private static final Map<XMPPConnection, LastActivityManager> instances = new WeakHashMap<XMPPConnection, LastActivityManager>();
  90. //    private static final PacketFilter IQ_GET_LAST_FILTER = new AndFilter(IQTypeFilter.GET,
  91. //                    new StanzaTypeFilter(LastActivity.class));

  92.     private static boolean enabledPerDefault = true;

  93.     /**
  94.      * Enable or disable Last Activity for new XMPPConnections.
  95.      *
  96.      * @param enabledPerDefault
  97.      */
  98.     public static void setEnabledPerDefault(boolean enabledPerDefault) {
  99.         LastActivityManager.enabledPerDefault = enabledPerDefault;
  100.     }

  101.     // Enable the LastActivity support on every established connection
  102.     static {
  103.         XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
  104.             public void connectionCreated(XMPPConnection connection) {
  105.                 LastActivityManager.getInstanceFor(connection);
  106.             }
  107.         });
  108.     }

  109.     public static synchronized LastActivityManager getInstanceFor(XMPPConnection connection) {
  110.         LastActivityManager lastActivityManager = instances.get(connection);
  111.         if (lastActivityManager == null)
  112.             lastActivityManager = new LastActivityManager(connection);
  113.         return lastActivityManager;
  114.     }

  115.     private volatile long lastMessageSent;
  116.     private boolean enabled = false;

  117.     /**
  118.      * Creates a last activity manager to response last activity requests.
  119.      *
  120.      * @param connection
  121.      *            The XMPPConnection that the last activity requests will use.
  122.      */
  123.     private LastActivityManager(XMPPConnection connection) {
  124.         super(connection);

  125.         // Listen to all the sent messages to reset the idle time on each one
  126.         connection.addPacketSendingListener(new StanzaListener() {
  127.             public void processPacket(Stanza packet) {
  128.                 Presence presence = (Presence) packet;
  129.                 Presence.Mode mode = presence.getMode();
  130.                 if (mode == null) return;
  131.                 switch (mode) {
  132.                 case available:
  133.                 case chat:
  134.                     // We assume that only a switch to available and chat indicates user activity
  135.                     // since other mode changes could be also a result of some sort of automatism
  136.                     resetIdleTime();
  137.                 default:
  138.                     break;
  139.                 }
  140.             }
  141.         }, StanzaTypeFilter.PRESENCE);

  142.         connection.addPacketSendingListener(new StanzaListener() {
  143.             @Override
  144.             public void processPacket(Stanza packet) {
  145.                 Message message = (Message) packet;
  146.                 // if it's not an error message, reset the idle time
  147.                 if (message.getType() == Message.Type.error) return;
  148.                 resetIdleTime();
  149.             }
  150.         }, StanzaTypeFilter.MESSAGE);

  151.         // Register a listener for a last activity query
  152.         connection.registerIQRequestHandler(new AbstractIqRequestHandler(LastActivity.ELEMENT, LastActivity.NAMESPACE,
  153.                         Type.get, Mode.async) {
  154.             @Override
  155.             public IQ handleIQRequest(IQ iqRequest) {
  156.                 if (!enabled)
  157.                     return IQ.createErrorResponse(iqRequest, new XMPPError(Condition.not_acceptable));
  158.                 LastActivity message = new LastActivity();
  159.                 message.setType(IQ.Type.result);
  160.                 message.setTo(iqRequest.getFrom());
  161.                 message.setFrom(iqRequest.getTo());
  162.                 message.setStanzaId(iqRequest.getStanzaId());
  163.                 message.setLastActivity(getIdleTime());

  164.                 return message;
  165.             }
  166.         });

  167.         if (enabledPerDefault) {
  168.             enable();
  169.         }
  170.         resetIdleTime();
  171.         instances.put(connection, this);
  172.     }

  173.     public synchronized void enable() {
  174.         ServiceDiscoveryManager.getInstanceFor(connection()).addFeature(LastActivity.NAMESPACE);
  175.         enabled = true;
  176.     }

  177.     public synchronized void disable() {
  178.         ServiceDiscoveryManager.getInstanceFor(connection()).removeFeature(LastActivity.NAMESPACE);
  179.         enabled = false;
  180.     }

  181.     /**
  182.      * Resets the idle time to 0, this should be invoked when a new message is
  183.      * sent.
  184.      */
  185.     private void resetIdleTime() {
  186.         lastMessageSent = System.currentTimeMillis();
  187.     }

  188.     /**
  189.      * The idle time is the lapsed time between the last message sent and now.
  190.      *
  191.      * @return the lapsed time between the last message sent and now.
  192.      */
  193.     private long getIdleTime() {
  194.         long lms = lastMessageSent;
  195.         long now = System.currentTimeMillis();
  196.         return ((now - lms) / 1000);
  197.     }

  198.     /**
  199.      * Returns the last activity of a particular jid. If the jid is a full JID
  200.      * (i.e., a JID of the form of 'user@host/resource') then the last activity
  201.      * is the idle time of that connected resource. On the other hand, when the
  202.      * jid is a bare JID (e.g. 'user@host') then the last activity is the lapsed
  203.      * time since the last logout or 0 if the user is currently logged in.
  204.      * Moreover, when the jid is a server or component (e.g., a JID of the form
  205.      * 'host') the last activity is the uptime.
  206.      *
  207.      * @param jid
  208.      *            the JID of the user.
  209.      * @return the LastActivity packet of the jid.
  210.      * @throws XMPPErrorException
  211.      *             thrown if a server error has occured.
  212.      * @throws NoResponseException if there was no response from the server.
  213.      * @throws NotConnectedException
  214.      * @throws InterruptedException
  215.      */
  216.     public LastActivity getLastActivity(Jid jid) throws NoResponseException, XMPPErrorException,
  217.                     NotConnectedException, InterruptedException {
  218.         LastActivity activity = new LastActivity(jid);
  219.         return (LastActivity) connection().createPacketCollectorAndSend(activity).nextResultOrThrow();
  220.     }

  221.     /**
  222.      * Returns true if Last Activity (XEP-0012) is supported by a given JID
  223.      *
  224.      * @param jid a JID to be tested for Last Activity support
  225.      * @return true if Last Activity is supported, otherwise false
  226.      * @throws NotConnectedException
  227.      * @throws XMPPErrorException
  228.      * @throws NoResponseException
  229.      * @throws InterruptedException
  230.      */
  231.     public boolean isLastActivitySupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  232.         return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, LastActivity.NAMESPACE);
  233.     }
  234. }