Merge 0.9->trunk
[prosody.git] / plugins / mod_presence.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 log = module._log;
10
11 local require = require;
12 local pairs, ipairs = pairs, ipairs;
13 local t_concat, t_insert = table.concat, table.insert;
14 local s_find = string.find;
15 local tonumber = tonumber;
16
17 local core_post_stanza = prosody.core_post_stanza;
18 local st = require "util.stanza";
19 local jid_split = require "util.jid".split;
20 local jid_bare = require "util.jid".bare;
21 local datetime = require "util.datetime";
22 local hosts = hosts;
23 local NULL = {};
24
25 local rostermanager = require "core.rostermanager";
26 local sessionmanager = require "core.sessionmanager";
27
28 local function select_top_resources(user)
29         local priority = 0;
30         local recipients = {};
31         for _, session in pairs(user.sessions) do -- find resource with greatest priority
32                 if session.presence then
33                         -- TODO check active privacy list for session
34                         local p = session.priority;
35                         if p > priority then
36                                 priority = p;
37                                 recipients = {session};
38                         elseif p == priority then
39                                 t_insert(recipients, session);
40                         end
41                 end
42         end
43         return recipients;
44 end
45 local function recalc_resource_map(user)
46         if user then
47                 user.top_resources = select_top_resources(user);
48                 if #user.top_resources == 0 then user.top_resources = nil; end
49         end
50 end
51
52 local ignore_presence_priority = module:get_option("ignore_presence_priority");
53
54 function handle_normal_presence(origin, stanza)
55         if ignore_presence_priority then
56                 local priority = stanza:child_with_name("priority");
57                 if priority and priority[1] ~= "0" then
58                         for i=#priority.tags,1,-1 do priority.tags[i] = nil; end
59                         for i=#priority,1,-1 do priority[i] = nil; end
60                         priority[1] = "0";
61                 end
62         end
63         local priority = stanza:child_with_name("priority");
64         if priority and #priority > 0 then
65                 priority = t_concat(priority);
66                 if s_find(priority, "^[+-]?[0-9]+$") then
67                         priority = tonumber(priority);
68                         if priority < -128 then priority = -128 end
69                         if priority > 127 then priority = 127 end
70                 else priority = 0; end
71         else priority = 0; end
72         if full_sessions[origin.full_jid] then -- if user is still connected
73                 origin.send(stanza); -- reflect their presence back to them
74         end
75         local roster = origin.roster;
76         local node, host = origin.username, origin.host;
77         local user = bare_sessions[node.."@"..host];
78         for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources
79                 if res ~= origin and res.presence then -- to resource
80                         stanza.attr.to = res.full_jid;
81                         core_post_stanza(origin, stanza, true);
82                 end
83         end
84         for jid, item in pairs(roster) do -- broadcast to all interested contacts
85                 if item.subscription == "both" or item.subscription == "from" then
86                         stanza.attr.to = jid;
87                         core_post_stanza(origin, stanza, true);
88                 end
89         end
90         if stanza.attr.type == nil and not origin.presence then -- initial presence
91                 origin.presence = stanza; -- FIXME repeated later
92                 local probe = st.presence({from = origin.full_jid, type = "probe"});
93                 for jid, item in pairs(roster) do -- probe all contacts we are subscribed to
94                         if item.subscription == "both" or item.subscription == "to" then
95                                 probe.attr.to = jid;
96                                 core_post_stanza(origin, probe, true);
97                         end
98                 end
99                 for _, res in pairs(user and user.sessions or NULL) do -- broadcast from all available resources
100                         if res ~= origin and res.presence then
101                                 res.presence.attr.to = origin.full_jid;
102                                 core_post_stanza(res, res.presence, true);
103                                 res.presence.attr.to = nil;
104                         end
105                 end
106                 if roster.pending then -- resend incoming subscription requests
107                         for jid in pairs(roster.pending) do
108                                 origin.send(st.presence({type="subscribe", from=jid})); -- TODO add to attribute? Use original?
109                         end
110                 end
111                 local request = st.presence({type="subscribe", from=origin.username.."@"..origin.host});
112                 for jid, item in pairs(roster) do -- resend outgoing subscription requests
113                         if item.ask then
114                                 request.attr.to = jid;
115                                 core_post_stanza(origin, request, true);
116                         end
117                 end
118
119                 if priority >= 0 then
120                         local event = { origin = origin }
121                         module:fire_event('message/offline/broadcast', event);
122                 end
123         end
124         if stanza.attr.type == "unavailable" then
125                 origin.presence = nil;
126                 if origin.priority then
127                         origin.priority = nil;
128                         recalc_resource_map(user);
129                 end
130                 if origin.directed then
131                         for jid in pairs(origin.directed) do
132                                 stanza.attr.to = jid;
133                                 core_post_stanza(origin, stanza, true);
134                         end
135                         origin.directed = nil;
136                 end
137         else
138                 origin.presence = stanza;
139                 stanza:tag("delay", { xmlns = "urn:xmpp:delay", from = host, stamp = datetime.datetime() }):up();
140                 if origin.priority ~= priority then
141                         origin.priority = priority;
142                         recalc_resource_map(user);
143                 end
144         end
145         stanza.attr.to = nil; -- reset it
146 end
147
148 function send_presence_of_available_resources(user, host, jid, recipient_session, stanza)
149         local h = hosts[host];
150         local count = 0;
151         if h and h.type == "local" then
152                 local u = h.sessions[user];
153                 if u then
154                         for k, session in pairs(u.sessions) do
155                                 local pres = session.presence;
156                                 if pres then
157                                         if stanza then pres = stanza; pres.attr.from = session.full_jid; end
158                                         pres.attr.to = jid;
159                                         core_post_stanza(session, pres, true);
160                                         pres.attr.to = nil;
161                                         count = count + 1;
162                                 end
163                         end
164                 end
165         end
166         log("debug", "broadcasted presence of %d resources from %s@%s to %s", count, user, host, jid);
167         return count;
168 end
169
170 function handle_outbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare)
171         local node, host = jid_split(from_bare);
172         if to_bare == from_bare then return; end -- No self contacts
173         local st_from, st_to = stanza.attr.from, stanza.attr.to;
174         stanza.attr.from, stanza.attr.to = from_bare, to_bare;
175         log("debug", "outbound presence %s from %s for %s", stanza.attr.type, from_bare, to_bare);
176         if stanza.attr.type == "probe" then
177                 stanza.attr.from, stanza.attr.to = st_from, st_to;
178                 return;
179         elseif stanza.attr.type == "subscribe" then
180                 -- 1. route stanza
181                 -- 2. roster push (subscription = none, ask = subscribe)
182                 if rostermanager.set_contact_pending_out(node, host, to_bare) then
183                         rostermanager.roster_push(node, host, to_bare);
184                 end -- else file error
185                 core_post_stanza(origin, stanza);
186         elseif stanza.attr.type == "unsubscribe" then
187                 -- 1. route stanza
188                 -- 2. roster push (subscription = none or from)
189                 if rostermanager.unsubscribe(node, host, to_bare) then
190                         rostermanager.roster_push(node, host, to_bare); -- FIXME do roster push when roster has in fact not changed?
191                 end -- else file error
192                 core_post_stanza(origin, stanza);
193         elseif stanza.attr.type == "subscribed" then
194                 -- 1. route stanza
195                 -- 2. roster_push ()
196                 -- 3. send_presence_of_available_resources
197                 if rostermanager.subscribed(node, host, to_bare) then
198                         rostermanager.roster_push(node, host, to_bare);
199                 end
200                 core_post_stanza(origin, stanza);
201                 send_presence_of_available_resources(node, host, to_bare, origin);
202         elseif stanza.attr.type == "unsubscribed" then
203                 -- 1. send unavailable
204                 -- 2. route stanza
205                 -- 3. roster push (subscription = from or both)
206                 local success, pending_in, subscribed = rostermanager.unsubscribed(node, host, to_bare);
207                 if success then
208                         if subscribed then
209                                 rostermanager.roster_push(node, host, to_bare);
210                         end
211                         core_post_stanza(origin, stanza);
212                         if subscribed then
213                                 send_presence_of_available_resources(node, host, to_bare, origin, st.presence({ type = "unavailable" }));
214                         end
215                 end
216         else
217                 origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid presence type"));
218         end
219         stanza.attr.from, stanza.attr.to = st_from, st_to;
220         return true;
221 end
222
223 function handle_inbound_presence_subscriptions_and_probes(origin, stanza, from_bare, to_bare)
224         local node, host = jid_split(to_bare);
225         local st_from, st_to = stanza.attr.from, stanza.attr.to;
226         stanza.attr.from, stanza.attr.to = from_bare, to_bare;
227         log("debug", "inbound presence %s from %s for %s", stanza.attr.type, from_bare, to_bare);
228         
229         if stanza.attr.type == "probe" then
230                 local result, err = rostermanager.is_contact_subscribed(node, host, from_bare);
231                 if result then
232                         if 0 == send_presence_of_available_resources(node, host, st_from, origin) then
233                                 core_post_stanza(hosts[host], st.presence({from=to_bare, to=st_from, type="unavailable"}), true); -- TODO send last activity
234                         end
235                 elseif not err then
236                         core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unsubscribed"}), true);
237                 end
238         elseif stanza.attr.type == "subscribe" then
239                 if rostermanager.is_contact_subscribed(node, host, from_bare) then
240                         core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="subscribed"}), true); -- already subscribed
241                         -- Sending presence is not clearly stated in the RFC, but it seems appropriate
242                         if 0 == send_presence_of_available_resources(node, host, from_bare, origin) then
243                                 core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- TODO send last activity
244                         end
245                 else
246                         core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt
247                         if not rostermanager.is_contact_pending_in(node, host, from_bare) then
248                                 if rostermanager.set_contact_pending_in(node, host, from_bare) then
249                                         sessionmanager.send_to_available_resources(node, host, stanza);
250                                 end -- TODO else return error, unable to save
251                         end
252                 end
253         elseif stanza.attr.type == "unsubscribe" then
254                 if rostermanager.process_inbound_unsubscribe(node, host, from_bare) then
255                         sessionmanager.send_to_interested_resources(node, host, stanza);
256                         rostermanager.roster_push(node, host, from_bare);
257                 end
258         elseif stanza.attr.type == "subscribed" then
259                 if rostermanager.process_inbound_subscription_approval(node, host, from_bare) then
260                         sessionmanager.send_to_interested_resources(node, host, stanza);
261                         rostermanager.roster_push(node, host, from_bare);
262                 end
263         elseif stanza.attr.type == "unsubscribed" then
264                 if rostermanager.process_inbound_subscription_cancellation(node, host, from_bare) then
265                         sessionmanager.send_to_interested_resources(node, host, stanza);
266                         rostermanager.roster_push(node, host, from_bare);
267                 end
268         else
269                 origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid presence type"));
270         end
271         stanza.attr.from, stanza.attr.to = st_from, st_to;
272         return true;
273 end
274
275 local outbound_presence_handler = function(data)
276         -- outbound presence recieved
277         local origin, stanza = data.origin, data.stanza;
278
279         local to = stanza.attr.to;
280         if to then
281                 local t = stanza.attr.type;
282                 if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes
283                         return handle_outbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to));
284                 end
285
286                 local to_bare = jid_bare(to);
287                 local roster = origin.roster;
288                 if roster and not(roster[to_bare] and (roster[to_bare].subscription == "both" or roster[to_bare].subscription == "from")) then -- directed presence
289                         origin.directed = origin.directed or {};
290                         if t then -- removing from directed presence list on sending an error or unavailable
291                                 origin.directed[to] = nil; -- FIXME does it make more sense to add to_bare rather than to?
292                         else
293                                 origin.directed[to] = true; -- FIXME does it make more sense to add to_bare rather than to?
294                         end
295                 end
296         end -- TODO maybe handle normal presence here, instead of letting it pass to incoming handlers?
297 end
298
299 module:hook("pre-presence/full", outbound_presence_handler);
300 module:hook("pre-presence/bare", outbound_presence_handler);
301 module:hook("pre-presence/host", outbound_presence_handler);
302
303 module:hook("presence/bare", function(data)
304         -- inbound presence to bare JID recieved
305         local origin, stanza = data.origin, data.stanza;
306
307         local to = stanza.attr.to;
308         local t = stanza.attr.type;
309         if to then
310                 if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes sent to bare JID
311                         return handle_inbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to));
312                 end
313         
314                 local user = bare_sessions[to];
315                 if user then
316                         for _, session in pairs(user.sessions) do
317                                 if session.presence then -- only send to available resources
318                                         session.send(stanza);
319                                 end
320                         end
321                 end -- no resources not online, discard
322         elseif not t or t == "unavailable" then
323                 handle_normal_presence(origin, stanza);
324         else
325                 origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid presence type"));
326         end
327         return true;
328 end);
329 module:hook("presence/full", function(data)
330         -- inbound presence to full JID recieved
331         local origin, stanza = data.origin, data.stanza;
332
333         local t = stanza.attr.type;
334         if t ~= nil and t ~= "unavailable" and t ~= "error" then -- check for subscriptions and probes sent to full JID
335                 return handle_inbound_presence_subscriptions_and_probes(origin, stanza, jid_bare(stanza.attr.from), jid_bare(stanza.attr.to));
336         end
337
338         local session = full_sessions[stanza.attr.to];
339         if session then
340                 -- TODO fire post processing event
341                 session.send(stanza);
342         end -- resource not online, discard
343         return true;
344 end);
345 module:hook("presence/host", function(data)
346         -- inbound presence to the host
347         local origin, stanza = data.origin, data.stanza;
348         
349         local from_bare = jid_bare(stanza.attr.from);
350         local t = stanza.attr.type;
351         if t == "probe" then
352                 core_post_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id }));
353         elseif t == "subscribe" then
354                 core_post_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id, type = "subscribed" }));
355                 core_post_stanza(hosts[module.host], st.presence({ from = module.host, to = from_bare, id = stanza.attr.id }));
356         end
357         return true;
358 end);
359
360 module:hook("resource-unbind", function(event)
361         local session, err = event.session, event.error;
362         -- Send unavailable presence
363         if session.presence then
364                 local pres = st.presence{ type = "unavailable" };
365                 if err then
366                         pres:tag("status"):text("Disconnected: "..err):up();
367                 end
368                 session:dispatch_stanza(pres);
369         elseif session.directed then
370                 local pres = st.presence{ type = "unavailable", from = session.full_jid };
371                 if err then
372                         pres:tag("status"):text("Disconnected: "..err):up();
373                 end
374                 for jid in pairs(session.directed) do
375                         pres.attr.to = jid;
376                         core_post_stanza(session, pres, true);
377                 end
378                 session.directed = nil;
379         end
380 end);