Merge 0.10->trunk
[prosody.git] / plugins / mod_lastactivity.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local st = require "util.stanza";
10 local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed;
11 local jid_bare = require "util.jid".bare;
12 local jid_split = require "util.jid".split;
13
14 module:add_feature("jabber:iq:last");
15
16 local map = {};
17
18 module:hook("pre-presence/bare", function(event)
19         local stanza = event.stanza;
20         if not(stanza.attr.to) and stanza.attr.type == "unavailable" then
21                 local t = os.time();
22                 local s = stanza:get_child_text("status");
23                 map[event.origin.username] = {s = s, t = t};
24         end
25 end, 10);
26
27 module:hook("iq/bare/jabber:iq:last:query", function(event)
28         local origin, stanza = event.origin, event.stanza;
29         if stanza.attr.type == "get" then
30                 local username = jid_split(stanza.attr.to) or origin.username;
31                 if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then
32                         local seconds, text = "0", "";
33                         if map[username] then
34                                 seconds = tostring(os.difftime(os.time(), map[username].t));
35                                 text = map[username].s;
36                         end
37                         origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:last', seconds=seconds}):text(text));
38                 else
39                         origin.send(st.error_reply(stanza, 'auth', 'forbidden'));
40                 end
41                 return true;
42         end
43 end);
44
45 module.save = function()
46         return {map = map};
47 end
48 module.restore = function(data)
49         map = data.map or {};
50 end
51