util.cache: Add support for creating a proxy table to a cache, that looks and acts...
[prosody.git] / plugins / mod_private.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 st = require "util.stanza"
11
12 local private_storage = module:open_store();
13
14 module:add_feature("jabber:iq:private");
15
16 module:hook("iq/self/jabber:iq:private:query", function(event)
17         local origin, stanza = event.origin, event.stanza;
18         local query = stanza.tags[1];
19         if #query.tags ~= 1 then
20                 origin.send(st.error_reply(stanza, "modify", "bad-format"));
21                 return true;
22         end
23         local tag = query.tags[1];
24         local key = tag.name..":"..tag.attr.xmlns;
25         local data, err = private_storage:get(origin.username);
26         if err then
27                 origin.send(st.error_reply(stanza, "wait", "internal-server-error", err));
28                 return true;
29         end
30         if stanza.attr.type == "get" then
31                 if data and data[key] then
32                         origin.send(st.reply(stanza):query("jabber:iq:private"):add_child(st.deserialize(data[key])));
33                         return true;
34                 else
35                         origin.send(st.reply(stanza):add_child(query));
36                         return true;
37                 end
38         else -- type == set
39                 if not data then data = {}; end;
40                 if #tag == 0 then
41                         data[key] = nil;
42                 else
43                         data[key] = st.preserialize(tag);
44                 end
45                 -- TODO delete datastore if empty
46                 local ok, err = private_storage:set(origin.username, data);
47                 if not ok then
48                         origin.send(st.error_reply(stanza, "wait", "internal-server-error", err));
49                         return true;
50                 end
51                 origin.send(st.reply(stanza));
52                 return true;
53         end
54 end);