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.ConnectionCreationListener;
  21. import org.jivesoftware.smack.Manager;
  22. import org.jivesoftware.smack.SmackException.NoResponseException;
  23. import org.jivesoftware.smack.SmackException.NotConnectedException;
  24. import org.jivesoftware.smack.StanzaListener;
  25. import org.jivesoftware.smack.XMPPConnection;
  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.Message;
  33. import org.jivesoftware.smack.packet.Presence;
  34. import org.jivesoftware.smack.packet.Stanza;
  35. import org.jivesoftware.smack.packet.StanzaError.Condition;

  36. import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
  37. import org.jivesoftware.smackx.iqlast.packet.LastActivity;

  38. import org.jxmpp.jid.Jid;

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

  82. public final class LastActivityManager extends Manager {
  83.     private static final Map<XMPPConnection, LastActivityManager> instances = new WeakHashMap<>();
  84. //    private static final PacketFilter IQ_GET_LAST_FILTER = new AndFilter(IQTypeFilter.GET,
  85. //                    new StanzaTypeFilter(LastActivity.class));

  86.     private static boolean enabledPerDefault = true;

  87.     /**
  88.      * Enable or disable Last Activity for new XMPPConnections.
  89.      *
  90.      * @param enabledPerDefault TODO javadoc me please
  91.      */
  92.     public static void setEnabledPerDefault(boolean enabledPerDefault) {
  93.         LastActivityManager.enabledPerDefault = enabledPerDefault;
  94.     }

  95.     // Enable the LastActivity support on every established connection
  96.     static {
  97.         XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
  98.             @Override
  99.             public void connectionCreated(XMPPConnection connection) {
  100.                 LastActivityManager.getInstanceFor(connection);
  101.             }
  102.         });
  103.     }

  104.     public static synchronized LastActivityManager getInstanceFor(XMPPConnection connection) {
  105.         LastActivityManager lastActivityManager = instances.get(connection);
  106.         if (lastActivityManager == null)
  107.             lastActivityManager = new LastActivityManager(connection);
  108.         return lastActivityManager;
  109.     }

  110.     private volatile long lastMessageSent;
  111.     private boolean enabled = false;

  112.     /**
  113.      * Creates a last activity manager to response last activity requests.
  114.      *
  115.      * @param connection TODO javadoc me please
  116.      *            The XMPPConnection that the last activity requests will use.
  117.      */
  118.     private LastActivityManager(XMPPConnection connection) {
  119.         super(connection);

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

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

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

  161.                 return message;
  162.             }
  163.         });

  164.         if (enabledPerDefault) {
  165.             enable();
  166.         }
  167.         resetIdleTime();
  168.         instances.put(connection, this);
  169.     }

  170.     public synchronized void enable() {
  171.         ServiceDiscoveryManager.getInstanceFor(connection()).addFeature(LastActivity.NAMESPACE);
  172.         enabled = true;
  173.     }

  174.     public synchronized void disable() {
  175.         ServiceDiscoveryManager.getInstanceFor(connection()).removeFeature(LastActivity.NAMESPACE);
  176.         enabled = false;
  177.     }

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

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

  195.     /**
  196.      * Returns the last activity of a particular jid. If the jid is a full JID
  197.      * (i.e., a JID of the form of 'user@host/resource') then the last activity
  198.      * is the idle time of that connected resource. On the other hand, when the
  199.      * jid is a bare JID (e.g. 'user@host') then the last activity is the lapsed
  200.      * time since the last logout or 0 if the user is currently logged in.
  201.      * Moreover, when the jid is a server or component (e.g., a JID of the form
  202.      * 'host') the last activity is the uptime.
  203.      *
  204.      * @param jid TODO javadoc me please
  205.      *            the JID of the user.
  206.      * @return the LastActivity stanza of the jid.
  207.      * @throws XMPPErrorException if there was an XMPP error returned.
  208.      *             thrown if a server error has occurred.
  209.      * @throws NoResponseException if there was no response from the server.
  210.      * @throws NotConnectedException if the XMPP connection is not connected.
  211.      * @throws InterruptedException if the calling thread was interrupted.
  212.      */
  213.     public LastActivity getLastActivity(Jid jid) throws NoResponseException, XMPPErrorException,
  214.                     NotConnectedException, InterruptedException {
  215.         LastActivity activity = new LastActivity(jid);
  216.         return (LastActivity) connection().sendIqRequestAndWaitForResponse(activity);
  217.     }

  218.     /**
  219.      * Returns true if Last Activity (XEP-0012) is supported by a given JID.
  220.      *
  221.      * @param jid a JID to be tested for Last Activity support
  222.      * @return true if Last Activity is supported, otherwise false
  223.      * @throws NotConnectedException if the XMPP connection is not connected.
  224.      * @throws XMPPErrorException if there was an XMPP error returned.
  225.      * @throws NoResponseException if there was no response from the remote entity.
  226.      * @throws InterruptedException if the calling thread was interrupted.
  227.      */
  228.     public boolean isLastActivitySupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  229.         return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, LastActivity.NAMESPACE);
  230.     }
  231. }