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