Let Google Hangouts contacts appear offline
[prosody.git] / util / stanza.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
10 local t_insert      =  table.insert;
11 local t_concat      =  table.concat;
12 local t_remove      =  table.remove;
13 local t_concat      =  table.concat;
14 local s_format      = string.format;
15 local s_match       =  string.match;
16 local tostring      =      tostring;
17 local setmetatable  =  setmetatable;
18 local getmetatable  =  getmetatable;
19 local pairs         =         pairs;
20 local ipairs        =        ipairs;
21 local type          =          type;
22 local next          =          next;
23 local print         =         print;
24 local unpack        =        unpack;
25 local s_gsub        =   string.gsub;
26 local s_char        =   string.char;
27 local s_find        =   string.find;
28 local os            =            os;
29
30 local do_pretty_printing = not os.getenv("WINDIR");
31 local getstyle, getstring;
32 if do_pretty_printing then
33         local ok, termcolours = pcall(require, "util.termcolours");
34         if ok then
35                 getstyle, getstring = termcolours.getstyle, termcolours.getstring;
36         else
37                 do_pretty_printing = nil;
38         end
39 end
40
41 local xmlns_stanzas = "urn:ietf:params:xml:ns:xmpp-stanzas";
42
43 module "stanza"
44
45 stanza_mt = { __type = "stanza" };
46 stanza_mt.__index = stanza_mt;
47 local stanza_mt = stanza_mt;
48
49 function stanza(name, attr)
50         local stanza = { name = name, attr = attr or {}, tags = {} };
51         return setmetatable(stanza, stanza_mt);
52 end
53 local stanza = stanza;
54
55 function stanza_mt:query(xmlns)
56         return self:tag("query", { xmlns = xmlns });
57 end
58
59 function stanza_mt:body(text, attr)
60         return self:tag("body", attr):text(text);
61 end
62
63 function stanza_mt:tag(name, attrs)
64         local s = stanza(name, attrs);
65         local last_add = self.last_add;
66         if not last_add then last_add = {}; self.last_add = last_add; end
67         (last_add[#last_add] or self):add_direct_child(s);
68         t_insert(last_add, s);
69         return self;
70 end
71
72 function stanza_mt:text(text)
73         local last_add = self.last_add;
74         (last_add and last_add[#last_add] or self):add_direct_child(text);
75         return self;
76 end
77
78 function stanza_mt:up()
79         local last_add = self.last_add;
80         if last_add then t_remove(last_add); end
81         return self;
82 end
83
84 function stanza_mt:reset()
85         self.last_add = nil;
86         return self;
87 end
88
89 function stanza_mt:add_direct_child(child)
90         if type(child) == "table" then
91                 t_insert(self.tags, child);
92         end
93         t_insert(self, child);
94 end
95
96 function stanza_mt:add_child(child)
97         local last_add = self.last_add;
98         (last_add and last_add[#last_add] or self):add_direct_child(child);
99         return self;
100 end
101
102 function stanza_mt:get_child(name, xmlns)
103         for _, child in ipairs(self.tags) do
104                 if (not name or child.name == name)
105                         and ((not xmlns and self.attr.xmlns == child.attr.xmlns)
106                                 or child.attr.xmlns == xmlns) then
107                         
108                         return child;
109                 end
110         end
111 end
112
113 function stanza_mt:get_child_text(name, xmlns)
114         local tag = self:get_child(name, xmlns);
115         if tag then
116                 return tag:get_text();
117         end
118         return nil;
119 end
120
121 function stanza_mt:child_with_name(name)
122         for _, child in ipairs(self.tags) do
123                 if child.name == name then return child; end
124         end
125 end
126
127 function stanza_mt:child_with_ns(ns)
128         for _, child in ipairs(self.tags) do
129                 if child.attr.xmlns == ns then return child; end
130         end
131 end
132
133 function stanza_mt:children()
134         local i = 0;
135         return function (a)
136                         i = i + 1
137                         return a[i];
138                 end, self, i;
139 end
140
141 function stanza_mt:childtags(name, xmlns)
142         xmlns = xmlns or self.attr.xmlns;
143         local tags = self.tags;
144         local start_i, max_i = 1, #tags;
145         return function ()
146                 for i = start_i, max_i do
147                         local v = tags[i];
148                         if (not name or v.name == name)
149                         and (not xmlns or xmlns == v.attr.xmlns) then
150                                 start_i = i+1;
151                                 return v;
152                         end
153                 end
154         end;
155 end
156
157 function stanza_mt:maptags(callback)
158         local tags, curr_tag = self.tags, 1;
159         local n_children, n_tags = #self, #tags;
160         
161         local i = 1;
162         while curr_tag <= n_tags do
163                 if self[i] == tags[curr_tag] then
164                         local ret = callback(self[i]);
165                         if ret == nil then
166                                 t_remove(self, i);
167                                 t_remove(tags, curr_tag);
168                                 n_children = n_children - 1;
169                                 n_tags = n_tags - 1;
170                         else
171                                 self[i] = ret;
172                                 tags[i] = ret;
173                         end
174                         i = i + 1;
175                         curr_tag = curr_tag + 1;
176                 end
177         end
178         return self;
179 end
180
181 local xml_escape
182 do
183         local escape_table = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" };
184         function xml_escape(str) return (s_gsub(str, "['&<>\"]", escape_table)); end
185         _M.xml_escape = xml_escape;
186 end
187
188 local function _dostring(t, buf, self, xml_escape, parentns)
189         local nsid = 0;
190         local name = t.name
191         t_insert(buf, "<"..name);
192         for k, v in pairs(t.attr) do
193                 if s_find(k, "\1", 1, true) then
194                         local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$");
195                         nsid = nsid + 1;
196                         t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'");
197                 elseif not(k == "xmlns" and v == parentns) then
198                         t_insert(buf, " "..k.."='"..xml_escape(v).."'");
199                 end
200         end
201         local len = #t;
202         if len == 0 then
203                 t_insert(buf, "/>");
204         else
205                 t_insert(buf, ">");
206                 for n=1,len do
207                         local child = t[n];
208                         if child.name then
209                                 self(child, buf, self, xml_escape, t.attr.xmlns);
210                         else
211                                 t_insert(buf, xml_escape(child));
212                         end
213                 end
214                 t_insert(buf, "</"..name..">");
215         end
216 end
217 function stanza_mt.__tostring(t)
218         local buf = {};
219         _dostring(t, buf, _dostring, xml_escape, nil);
220         return t_concat(buf);
221 end
222
223 function stanza_mt.top_tag(t)
224         local attr_string = "";
225         if t.attr then
226                 for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, xml_escape(tostring(v))); end end
227         end
228         return s_format("<%s%s>", t.name, attr_string);
229 end
230
231 function stanza_mt.get_text(t)
232         if #t.tags == 0 then
233                 return t_concat(t);
234         end
235 end
236
237 function stanza_mt.get_error(stanza)
238         local type, condition, text;
239         
240         local error_tag = stanza:get_child("error");
241         if not error_tag then
242                 return nil, nil, nil;
243         end
244         type = error_tag.attr.type;
245         
246         for child in error_tag:childtags() do
247                 if child.attr.xmlns == xmlns_stanzas then
248                         if not text and child.name == "text" then
249                                 text = child:get_text();
250                         elseif not condition then
251                                 condition = child.name;
252                         end
253                         if condition and text then
254                                 break;
255                         end
256                 end
257         end
258         return type, condition or "undefined-condition", text;
259 end
260
261 function stanza_mt.__add(s1, s2)
262         return s1:add_direct_child(s2);
263 end
264
265
266 do
267         local id = 0;
268         function new_id()
269                 id = id + 1;
270                 return "lx"..id;
271         end
272 end
273
274 function preserialize(stanza)
275         local s = { name = stanza.name, attr = stanza.attr };
276         for _, child in ipairs(stanza) do
277                 if type(child) == "table" then
278                         t_insert(s, preserialize(child));
279                 else
280                         t_insert(s, child);
281                 end
282         end
283         return s;
284 end
285
286 function deserialize(stanza)
287         -- Set metatable
288         if stanza then
289                 local attr = stanza.attr;
290                 for i=1,#attr do attr[i] = nil; end
291                 local attrx = {};
292                 for att in pairs(attr) do
293                         if s_find(att, "|", 1, true) and not s_find(att, "\1", 1, true) then
294                                 local ns,na = s_match(att, "^([^|]+)|(.+)$");
295                                 attrx[ns.."\1"..na] = attr[att];
296                                 attr[att] = nil;
297                         end
298                 end
299                 for a,v in pairs(attrx) do
300                         attr[a] = v;
301                 end
302                 setmetatable(stanza, stanza_mt);
303                 for _, child in ipairs(stanza) do
304                         if type(child) == "table" then
305                                 deserialize(child);
306                         end
307                 end
308                 if not stanza.tags then
309                         -- Rebuild tags
310                         local tags = {};
311                         for _, child in ipairs(stanza) do
312                                 if type(child) == "table" then
313                                         t_insert(tags, child);
314                                 end
315                         end
316                         stanza.tags = tags;
317                 end
318         end
319         
320         return stanza;
321 end
322
323 local function _clone(stanza)
324         local attr, tags = {}, {};
325         for k,v in pairs(stanza.attr) do attr[k] = v; end
326         local new = { name = stanza.name, attr = attr, tags = tags };
327         for i=1,#stanza do
328                 local child = stanza[i];
329                 if child.name then
330                         child = _clone(child);
331                         t_insert(tags, child);
332                 end
333                 t_insert(new, child);
334         end
335         return setmetatable(new, stanza_mt);
336 end
337 clone = _clone;
338
339 function message(attr, body)
340         if not body then
341                 return stanza("message", attr);
342         else
343                 return stanza("message", attr):tag("body"):text(body):up();
344         end
345 end
346 function iq(attr)
347         if attr and not attr.id then attr.id = new_id(); end
348         return stanza("iq", attr or { id = new_id() });
349 end
350
351 function reply(orig)
352         return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or orig.attr.type) });
353 end
354
355 do
356         local xmpp_stanzas_attr = { xmlns = xmlns_stanzas };
357         function error_reply(orig, type, condition, message)
358                 local t = reply(orig);
359                 t.attr.type = "error";
360                 t:tag("error", {type = type}) --COMPAT: Some day xmlns:stanzas goes here
361                         :tag(condition, xmpp_stanzas_attr):up();
362                 if (message) then t:tag("text", xmpp_stanzas_attr):text(message):up(); end
363                 return t; -- stanza ready for adding app-specific errors
364         end
365 end
366
367 function presence(attr)
368         return stanza("presence", attr);
369 end
370
371 if do_pretty_printing then
372         local style_attrk = getstyle("yellow");
373         local style_attrv = getstyle("red");
374         local style_tagname = getstyle("red");
375         local style_punc = getstyle("magenta");
376         
377         local attr_format = " "..getstring(style_attrk, "%s")..getstring(style_punc, "=")..getstring(style_attrv, "'%s'");
378         local top_tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">");
379         --local tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">").."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
380         local tag_format = top_tag_format.."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
381         function stanza_mt.pretty_print(t)
382                 local children_text = "";
383                 for n, child in ipairs(t) do
384                         if type(child) == "string" then
385                                 children_text = children_text .. xml_escape(child);
386                         else
387                                 children_text = children_text .. child:pretty_print();
388                         end
389                 end
390
391                 local attr_string = "";
392                 if t.attr then
393                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
394                 end
395                 return s_format(tag_format, t.name, attr_string, children_text, t.name);
396         end
397         
398         function stanza_mt.pretty_top_tag(t)
399                 local attr_string = "";
400                 if t.attr then
401                         for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(attr_format, k, tostring(v)); end end
402                 end
403                 return s_format(top_tag_format, t.name, attr_string);
404         end
405 else
406         -- Sorry, fresh out of colours for you guys ;)
407         stanza_mt.pretty_print = stanza_mt.__tostring;
408         stanza_mt.pretty_top_tag = stanza_mt.top_tag;
409 end
410
411 return _M;