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