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