util.stanza: Don't add xmlns to tags when serializing if same as the parent tag's...
[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:child_with_name(name)
97         for _, child in ipairs(self.tags) do    
98                 if child.name == name then return child; end
99         end
100 end
101
102 function stanza_mt:child_with_ns(ns)
103         for _, child in ipairs(self.tags) do    
104                 if child.attr.xmlns == ns then return child; end
105         end
106 end
107
108 function stanza_mt:children()
109         local i = 0;
110         return function (a)
111                         i = i + 1
112                         local v = a[i]
113                         if v then return v; end
114                 end, self, i;
115                                             
116 end
117 function stanza_mt:childtags()
118         local i = 0;
119         return function (a)
120                         i = i + 1
121                         local v = self.tags[i]
122                         if v then return v; end
123                 end, self.tags[1], i;
124                                             
125 end
126
127 local xml_escape
128 do
129         local escape_table = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" };
130         function xml_escape(str) return (s_gsub(str, "['&<>\"]", escape_table)); end
131         _M.xml_escape = xml_escape;
132 end
133
134 local function _dostring(t, buf, self, xml_escape, parentns)
135         local nsid = 0;
136         local name = t.name
137         t_insert(buf, "<"..name);
138         for k, v in pairs(t.attr) do
139                 if s_find(k, "|", 1, true) then
140                         local ns, attrk = s_match(k, "^([^|]+)|(.+)$");
141                         nsid = nsid + 1;
142                         t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'");
143                elseif not(k == "xmlns" and v == parentns) then
144                         t_insert(buf, " "..k.."='"..xml_escape(v).."'");
145                 end
146         end
147         local len = #t;
148         if len == 0 then
149                 t_insert(buf, "/>");
150         else
151                 t_insert(buf, ">");
152                 for n=1,len do
153                         local child = t[n];
154                         if child.name then
155                                self(child, buf, self, xml_escape, t.attr.xmlns);
156                         else
157                                 t_insert(buf, xml_escape(child));
158                         end
159                 end
160                 t_insert(buf, "</"..name..">");
161         end
162 end
163 function stanza_mt.__tostring(t)
164         local buf = {};
165        _dostring(t, buf, _dostring, xml_escape, nil);
166         return t_concat(buf);
167 end
168
169 function stanza_mt.top_tag(t)
170         local attr_string = "";
171         if t.attr then
172                 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
173         end
174         return s_format("<%s%s>", t.name, attr_string);
175 end
176
177 function stanza_mt.get_text(t)
178         if #t.tags == 0 then
179                 return t_concat(t);
180         end
181 end
182
183 function stanza_mt.__add(s1, s2)
184         return s1:add_direct_child(s2);
185 end
186
187
188 do
189         local id = 0;
190         function new_id()
191                 id = id + 1;
192                 return "lx"..id;
193         end
194 end
195
196 function preserialize(stanza)
197         local s = { name = stanza.name, attr = stanza.attr };
198         for _, child in ipairs(stanza) do
199                 if type(child) == "table" then
200                         t_insert(s, preserialize(child));
201                 else
202                         t_insert(s, child);
203                 end
204         end
205         return s;
206 end
207
208 function deserialize(stanza)
209         -- Set metatable
210         if stanza then
211                 local attr = stanza.attr;
212                 for i=1,#attr do attr[i] = nil; end
213                 setmetatable(stanza, stanza_mt);
214                 for _, child in ipairs(stanza) do
215                         if type(child) == "table" then
216                                 deserialize(child);
217                         end
218                 end
219                 if not stanza.tags then
220                         -- Rebuild tags
221                         local tags = {};
222                         for _, child in ipairs(stanza) do
223                                 if type(child) == "table" then
224                                         t_insert(tags, child);
225                                 end
226                         end
227                         stanza.tags = tags;
228                         if not stanza.last_add then
229                                 stanza.last_add = {};
230                         end
231                 end
232         end
233         
234         return stanza;
235 end
236
237 function clone(stanza)
238         local lookup_table = {};
239         local function _copy(object)
240                 if type(object) ~= "table" then
241                         return object;
242                 elseif lookup_table[object] then
243                         return lookup_table[object];
244                 end
245                 local new_table = {};
246                 lookup_table[object] = new_table;
247                 for index, value in pairs(object) do
248                         new_table[_copy(index)] = _copy(value);
249                 end
250                 return setmetatable(new_table, getmetatable(object));
251         end
252         
253         return _copy(stanza)
254 end
255
256 function message(attr, body)
257         if not body then
258                 return stanza("message", attr);
259         else
260                 return stanza("message", attr):tag("body"):text(body);
261         end
262 end
263 function iq(attr)
264         if attr and not attr.id then attr.id = new_id(); end
265         return stanza("iq", attr or { id = new_id() });
266 end
267
268 function reply(orig)
269         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) });
270 end
271
272 function error_reply(orig, type, condition, message)
273         local t = reply(orig);
274         t.attr.type = "error";
275         t:tag("error", {type = type})
276                 :tag(condition, {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
277         if (message) then t:tag("text"):text(message):up(); end
278         return t; -- stanza ready for adding app-specific errors
279 end
280
281 function presence(attr)
282         return stanza("presence", attr);
283 end
284
285 if do_pretty_printing then
286         local style_attrk = getstyle("yellow");
287         local style_attrv = getstyle("red");
288         local style_tagname = getstyle("red");
289         local style_punc = getstyle("magenta");
290         
291         local attr_format = " "..getstring(style_attrk, "%s")..getstring(style_punc, "=")..getstring(style_attrv, "'%s'");
292         local top_tag_format = getstring(style_punc, "<")..getstring(style_tagname, "%s").."%s"..getstring(style_punc, ">");
293         --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, ">");
294         local tag_format = top_tag_format.."%s"..getstring(style_punc, "</")..getstring(style_tagname, "%s")..getstring(style_punc, ">");
295         function stanza_mt.pretty_print(t)
296                 local children_text = "";
297                 for n, child in ipairs(t) do
298                         if type(child) == "string" then 
299                                 children_text = children_text .. xml_escape(child);
300                         else
301                                 children_text = children_text .. child:pretty_print();
302                         end
303                 end
304
305                 local attr_string = "";
306                 if t.attr then
307                         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
308                 end
309                 return s_format(tag_format, t.name, attr_string, children_text, t.name);
310         end
311         
312         function stanza_mt.pretty_top_tag(t)
313                 local attr_string = "";
314                 if t.attr then
315                         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
316                 end
317                 return s_format(top_tag_format, t.name, attr_string);
318         end
319 else
320         -- Sorry, fresh out of colours for you guys ;)
321         stanza_mt.pretty_print = stanza_mt.__tostring;
322         stanza_mt.pretty_top_tag = stanza_mt.top_tag;
323 end
324
325 return _M;