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