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