Bump to 1.3.1
[slixmpp.git] / sleekxmpp / plugins / xep_0319 / idle.py
blob90456f9fbf2769a0c65656bf43b165edc408409d
1 """
2 SleekXMPP: The Sleek XMPP Library
3 Copyright (C) 2013 Nathanael C. Fritz, Lance J.T. Stout
4 This file is part of SleekXMPP.
6 See the file LICENSE for copying permission.
7 """
9 from datetime import datetime, timedelta
11 from sleekxmpp.stanza import Presence
12 from sleekxmpp.plugins import BasePlugin
13 from sleekxmpp.xmlstream import register_stanza_plugin
14 from sleekxmpp.xmlstream.handler import Callback
15 from sleekxmpp.xmlstream.matcher import StanzaPath
16 from sleekxmpp.plugins.xep_0319 import stanza
19 class XEP_0319(BasePlugin):
20 name = 'xep_0319'
21 description = 'XEP-0319: Last User Interaction in Presence'
22 dependencies = set(['xep_0012'])
23 stanza = stanza
25 def plugin_init(self):
26 self._idle_stamps = {}
27 register_stanza_plugin(Presence, stanza.Idle)
28 self.api.register(self._set_idle,
29 'set_idle',
30 default=True)
31 self.api.register(self._get_idle,
32 'get_idle',
33 default=True)
34 self.xmpp.register_handler(
35 Callback('Idle Presence',
36 StanzaPath('presence/idle'),
37 self._idle_presence))
38 self.xmpp.add_filter('out', self._stamp_idle_presence)
40 def session_bind(self, jid):
41 self.xmpp['xep_0030'].add_feature('urn:xmpp:idle:1')
43 def plugin_end(self):
44 self.xmpp['xep_0030'].del_feature(feature='urn:xmpp:idle:1')
45 self.xmpp.del_filter('out', self._stamp_idle_presence)
46 self.xmpp.remove_handler('Idle Presence')
48 def idle(self, jid=None, since=None):
49 seconds = None
50 if since is None:
51 since = datetime.now()
52 else:
53 seconds = datetime.now() - since
54 self.api['set_idle'](jid, None, None, since)
55 self.xmpp['xep_0012'].set_last_activity(jid=jid, seconds=seconds)
57 def active(self, jid=None):
58 self.api['set_idle'](jid, None, None, None)
59 self.xmpp['xep_0012'].del_last_activity(jid)
61 def _set_idle(self, jid, node, ifrom, data):
62 self._idle_stamps[jid] = data
64 def _get_idle(self, jid, node, ifrom, data):
65 return self._idle_stamps.get(jid, None)
67 def _idle_presence(self, pres):
68 self.xmpp.event('presence_idle', pres)
70 def _stamp_idle_presence(self, stanza):
71 if isinstance(stanza, Presence):
72 since = self.api['get_idle'](stanza['from'] or self.xmpp.boundjid)
73 if since:
74 stanza['idle']['since'] = since
75 return stanza