util.stanza: Add stanza:matched_children(name, xmlns) [name suggestions welcome]
[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                         local v = a[i]
126                         if v then return v; end
127                 end, self, i;
128 end
129
130 function stanza_mt:matched_children(name, xmlns)
131         xmlns = xmlns or self.attr.xmlns;
132         local tags = self.tags;
133         local start_i, max_i = 1, #tags;
134         return function ()
135                         for i=start_i,max_i do
136                                 v = tags[i];
137                                 if (not name or v.name == name)
138                                 and (not xmlns or xmlns == v.attr.xmlns) then
139                                         start_i = i+1;
140                                         return v;
141                                 end
142                         end
143                 end, tags, i;
144 end
145
146 function stanza_mt:childtags()
147         local i = 0;
148         return function (a)
149                         i = i + 1
150                         local v = self.tags[i]
151                         if v then return v; end
152                 end, self.tags[1], i;
153 end
154
155 local xml_escape
156 do
157         local escape_table = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" };
158         function xml_escape(str) return (s_gsub(str, "['&<>\"]", escape_table)); end
159         _M.xml_escape = xml_escape;
160 end
161
162 local function _dostring(t, buf, self, xml_escape, parentns)
163         local nsid = 0;
164         local name = t.name
165         t_insert(buf, "<"..name);
166         for k, v in pairs(t.attr) do
167                 if s_find(k, "\1", 1, true) then
168                         local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$");
169                         nsid = nsid + 1;
170                         t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'");
171                 elseif not(k == "xmlns" and v == parentns) then
172                         t_insert(buf, " "..k.."='"..xml_escape(v).."'");
173                 end
174         end
175         local len = #t;
176         if len == 0 then
177                 t_insert(buf, "/>");
178         else
179                 t_insert(buf, ">");
180                 for n=1,len do
181                         local child = t[n];
182                         if child.name then
183                                 self(child, buf, self, xml_escape, t.attr.xmlns);
184                         else
185                                 t_insert(buf, xml_escape(child));
186                         end
187                 end
188                 t_insert(buf, "</"..name..">");
189         end
190 end
191 function stanza_mt.__tostring(t)
192         local buf = {};
193         _dostring(t, buf, _dostring, xml_escape, nil);
194         return t_concat(buf);
195 end
196
197 function stanza_mt.top_tag(t)
198         local attr_string = "";
199         if t.attr then
200                 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
201         end
202         return s_format("<%s%s>", t.name, attr_string);
203 end
204
205 function stanza_mt.get_text(t)
206         if #t.tags == 0 then
207                 return t_concat(t);
208         end
209 end
210
211 function stanza_mt.get_error(stanza)
212         local type, condition, text;
213         
214         local error_tag = stanza:get_child("error");
215         if not error_tag then
216                 return nil, nil, nil;
217         end
218         type = error_tag.attr.type;
219         
220         for child in error_tag:children() do
221                 if child.attr.xmlns == xmlns_stanzas then
222                         if not text and child.name == "text" then
223                                 text = child:get_text();
224                         elseif not condition then
225                                 condition = child.name;
226                         end
227                         if condition and text then
228                                 break;
229                         end
230                 end
231         end
232         return type, condition or "undefined-condition", text or "";
233 end
234
235 function stanza_mt.__add(s1, s2)
236         return s1:add_direct_child(s2);
237 end
238
239
240 do
241         local id = 0;
242         function new_id()
243                 id = id + 1;
244                 return "lx"..id;
245         end
246 end
247
248 function preserialize(stanza)
249         local s = { name = stanza.name, attr = stanza.attr };
250         for _, child in ipairs(stanza) do
251                 if type(child) == "table" then
252                         t_insert(s, preserialize(child));
253                 else
254                         t_insert(s, child);
255                 end
256         end
257         return s;
258 end
259
260 function deserialize(stanza)
261         -- Set metatable
262         if stanza then
263                 local attr = stanza.attr;
264                 for i=1,#attr do attr[i] = nil; end
265                 local attrx = {};
266                 for att in pairs(attr) do
267                         if s_find(att, "|", 1, true) and not s_find(att, "\1", 1, true) then
268                                 local ns,na = s_match(att, "^([^|]+)|(.+)$");
269                                 attrx[ns.."\1"..na] = attr[att];
270                                 attr[att] = nil;
271                         end
272                 end
273                 for a,v in pairs(attrx) do
274                         attr[a] = v;
275                 end
276                 setmetatable(stanza, stanza_mt);
277                 for _, child in ipairs(stanza) do
278                         if type(child) == "table" then
279                                 deserialize(child);
280                         end
281                 end
282                 if not stanza.tags then
283                         -- Rebuild tags
284                         local tags = {};
285                         for _, child in ipairs(stanza) do
286                                 if type(child) == "table" then
287                                         t_insert(tags, child);
288                                 end
289                         end
290                         stanza.tags = tags;
291                         if not stanza.last_add then
292                                 stanza.last_add = {};
293                         end
294                 end
295         end
296         
297         return stanza;
298 end
299
300 function clone(stanza)
301         local lookup_table = {};
302         local function _copy(object)
303                 if type(object) ~= "table" then
304                         return object;
305                 elseif lookup_table[object] then
306                         return lookup_table[object];
307                 end
308                 local new_table = {};
309                 lookup_table[object] = new_table;
310                 for index, value in pairs(object) do
311                         new_table[_copy(index)] = _copy(value);
312                 end
313                 return setmetatable(new_table, getmetatable(object));
314         end
315         
316         return _copy(stanza)
317 end
318
319 function message(attr, body)
320         if not body then
321                 return stanza("message", attr);
322         else
323                 return stanza("message", attr):tag("body"):text(body);
324         end
325 end
326 function iq(attr)
327         if attr and not attr.id then attr.id = new_id(); end
328         return stanza("iq", attr or { id = new_id() });
329 end
330
331 function reply(orig)
332         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) });
333 end
334
335 do
336         local xmpp_stanzas_attr = { xmlns = xmlns_stanzas };
337         function error_reply(orig, type, condition, message)
338                 local t = reply(orig);
339                 t.attr.type = "error";
340                 t:tag("error", {type = type}) --COMPAT: Some day xmlns:stanzas goes here
341                         :tag(condition, xmpp_stanzas_attr):up();
342                 if (message) then t:tag("text", xmpp_stanzas_attr):text(message):up(); end
343                 return t; -- stanza ready for adding app-specific errors
344         end
345 end
346
347 function presence(attr)
348         return stanza("presence", attr);
349 end
350
351 if do_pretty_printing then
352         local style_attrk = getstyle("yellow");
353         local style_attrv = getstyle("red");
354         local style_tagname = getstyle("red");
355         local style_punc = getstyle("magenta");
356         
357         local attr_format = " "..getstring(style_attrk, "%s")..getstring(style_punc, "=")..getstring(style_attrv, "'%s'");
358         local top_tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">");
359         --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, ">");
360         local tag_format = top_tag_format.."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
361         function stanza_mt.pretty_print(t)
362                 local children_text = "";
363                 for n, child in ipairs(t) do
364                         if type(child) == "string" then
365                                 children_text = children_text .. xml_escape(child);
366                         else
367                                 children_text = children_text .. child:pretty_print();
368                         end
369                 end
370
371                 local attr_string = "";
372                 if t.attr then
373                         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
374                 end
375                 return s_format(tag_format, t.name, attr_string, children_text, t.name);
376         end
377         
378         function stanza_mt.pretty_top_tag(t)
379                 local attr_string = "";
380                 if t.attr then
381                         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
382                 end
383                 return s_format(top_tag_format, t.name, attr_string);
384         end
385 else
386         -- Sorry, fresh out of colours for you guys ;)
387         stanza_mt.pretty_print = stanza_mt.__tostring;
388         stanza_mt.pretty_top_tag = stanza_mt.top_tag;
389 end
390
391 return _M;