1 -- Prosody IM |
|
2 -- Copyright (C) 2008-2009 Matthew Wild |
|
3 -- Copyright (C) 2008-2009 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 |
|
10 |
|
11 local t_insert = table.insert; |
|
12 local jid_split = require "util.jid".split; |
|
13 local ipairs = ipairs; |
|
14 local st = require "util.stanza"; |
|
15 |
|
16 module "discohelper"; |
|
17 |
|
18 local function addDiscoItemsHandler(self, jid, func) |
|
19 if self.item_handlers[jid] then |
|
20 t_insert(self.item_handlers[jid], func); |
|
21 else |
|
22 self.item_handlers[jid] = {func}; |
|
23 end |
|
24 end |
|
25 |
|
26 local function addDiscoInfoHandler(self, jid, func) |
|
27 if self.info_handlers[jid] then |
|
28 t_insert(self.info_handlers[jid], func); |
|
29 else |
|
30 self.info_handlers[jid] = {func}; |
|
31 end |
|
32 end |
|
33 |
|
34 local function handle(self, stanza) |
|
35 if stanza.name == "iq" and stanza.tags[1].name == "query" then |
|
36 local query = stanza.tags[1]; |
|
37 local to = stanza.attr.to; |
|
38 local from = stanza.attr.from |
|
39 local node = query.attr.node or ""; |
|
40 local to_node, to_host = jid_split(to); |
|
41 |
|
42 local reply = st.reply(stanza):query(query.attr.xmlns); |
|
43 local handlers; |
|
44 if query.attr.xmlns == "http://jabber.org/protocol/disco#info" then -- select handler set |
|
45 handlers = self.info_handlers; |
|
46 elseif query.attr.xmlns == "http://jabber.org/protocol/disco#items" then |
|
47 handlers = self.item_handlers; |
|
48 end |
|
49 local handler; |
|
50 local found; -- to keep track of any handlers found |
|
51 if to_node then -- handlers which get called always |
|
52 handler = handlers["*node"]; |
|
53 else |
|
54 handler = handlers["*host"]; |
|
55 end |
|
56 if handler then -- call always called handler |
|
57 for _, h in ipairs(handler) do |
|
58 if h(reply, to, from, node) then found = true; end |
|
59 end |
|
60 end |
|
61 handler = handlers[to]; -- get the handler |
|
62 if not handler then -- if not found then use default handler |
|
63 if to_node then |
|
64 handler = handlers["*defaultnode"]; |
|
65 else |
|
66 handler = handlers["*defaulthost"]; |
|
67 end |
|
68 end |
|
69 if handler then |
|
70 for _, h in ipairs(handler) do |
|
71 if h(reply, to, from, node) then found = true; end |
|
72 end |
|
73 end |
|
74 if found then return reply; end -- return the reply if there was one |
|
75 return st.error_reply(stanza, "cancel", "service-unavailable"); |
|
76 end |
|
77 end |
|
78 |
|
79 function new() |
|
80 return { |
|
81 item_handlers = {}; |
|
82 info_handlers = {}; |
|
83 addDiscoItemsHandler = addDiscoItemsHandler; |
|
84 addDiscoInfoHandler = addDiscoInfoHandler; |
|
85 handle = handle; |
|
86 }; |
|
87 end |
|
88 |
|
89 return _M; |
|