comparison mod_mam/rsm.lib.lua @ 701:cc5805f83583

mod_mam: Implement support for Result Set Management in queries.
author Kim Alvefur <zash@zash.se>
date Fri, 08 Jun 2012 03:13:31 +0200
parents
children d94ee0848b27
comparison
equal deleted inserted replaced
700:0c130c45b7c1 701:cc5805f83583
1 local stanza = require"util.stanza".stanza;
2 local tostring, tonumber = tostring, tonumber;
3 local type = type;
4 local pairs = pairs;
5
6 local xmlns_rsm = 'http://jabber.org/protocol/rsm';
7
8 local element_parsers;
9
10 do
11 local function xs_int(st)
12 return tonumber(st:get_text());
13 end
14 local function xs_string(st)
15 return st:get_text();
16 end
17
18 element_parsers = {
19 after = xs_string;
20 before = function(st)
21 return st:get_text() or true;
22 end;
23 max = xs_int;
24 index = xs_int;
25
26 first = function(st)
27 return { index = tonumber(st.attr.index); st:get_text() };
28 end;
29 last = xs_string;
30 count = xs_int;
31 }
32 end
33
34 local element_generators = setmetatable({
35 first = function(st, data)
36 if type(data) == "table" then
37 st:tag("first", { index = data.index }):text(data[1]):up();
38 else
39 st:tag("first"):text(tostring(data)):up();
40 end
41 end;
42 }, {
43 __index = function(_, name)
44 return function(st, data)
45 st:tag(name):text(tostring(data)):up();
46 end
47 end;
48 });
49
50
51 local function parse(stanza)
52 local rs = {};
53 for tag in stanza:childtags() do
54 local name = tag.name;
55 local parser = name and element_parsers[name];
56 if parser then
57 rs[name] = parser(tag);
58 end
59 end
60 return rs;
61 end
62
63 local function generate(t)
64 local st = stanza("rsm", { xmlns = xmlns_rsm });
65 for k,v in pairs(t) do
66 if element_parsers[k] then
67 element_generators[k](st, v);
68 end
69 end
70 return st;
71 end
72
73 local function get(st)
74 local set = st:get_child("set", xmlns_rsm);
75 if set and #set.tags > 0 then
76 return parse(set);
77 else
78 module:log("debug", "RSM parse failed, %s", tostring(st));
79 end
80 end
81
82 return { parse = parse, generate = generate, get = get };