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