Added support for storing (and removing), loading and appending to lists of data...
[prosody.git] / util / datamanager.lua
1 local format = string.format;
2 local setmetatable, type = setmetatable, type;
3 local pairs, ipairs = pairs, ipairs;
4 local char = string.char;
5 local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
6 local log = log;
7 local io_open = io.open;
8 local os_remove = os.remove;
9 local tostring = tostring;
10 local error = error;
11 local next = next;
12 local t_insert = table.insert;
13
14 local indent = function(f, i)
15         for n = 1, i do
16                 f:write("\t");
17         end
18 end
19
20 module "datamanager"
21
22
23 ---- utils -----
24 local encode, decode;
25
26 local log = function (type, msg) return log(type, "datamanager", msg); end
27
28 do 
29         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
30
31         decode = function (s)
32                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
33         end
34
35         encode = function (s)
36                 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
37         end
38 end
39
40 local function basicSerialize (o)
41         if type(o) == "number" or type(o) == "boolean" then
42                 return tostring(o);
43         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
44                 return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
45         end
46 end
47
48
49 local function simplesave (f, o, ind)
50         if type(o) == "number" then
51                 f:write(o)
52         elseif type(o) == "string" then
53                 f:write((format("%q", o):gsub("\\\n", "\\n")))
54         elseif type(o) == "table" then
55                 f:write("{\n")
56                 for k,v in pairs(o) do
57                         indent(f, ind);
58                         f:write("[", basicSerialize(k), "] = ")
59                         simplesave(f, v, ind+1)
60                         f:write(",\n")
61                 end
62                 indent(f, ind-1);
63                 f:write("}")
64         elseif type(o) == "boolean" then
65                 f:write(o and "true" or "false");
66         else
67                 error("cannot serialize a " .. type(o))
68         end
69 end
70
71 ------- API -------------
72
73 function getpath(username, host, datastore, ext)
74         ext = ext or "dat";
75         if username then
76                 return format("data/%s/%s/%s.%s", encode(host), datastore, encode(username), ext);
77         elseif host then
78                 return format("data/%s/%s.%s", encode(host), datastore, ext);
79         else
80                 return format("data/%s.%s", datastore, ext);
81         end
82 end
83
84 function load(username, host, datastore)
85         local data, ret = loadfile(getpath(username, host, datastore));
86         if not data then
87                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
88                 return nil;
89         end
90         setfenv(data, {});
91         local success, ret = pcall(data);
92         if not success then
93                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
94                 return nil;
95         end
96         return ret;
97 end
98
99 function store(username, host, datastore, data)
100         if not data then
101                 data = {};
102         end
103         -- save the datastore
104         local f, msg = io_open(getpath(username, host, datastore), "w+");
105         if not f then
106                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
107                 return;
108         end
109         f:write("return ");
110         simplesave(f, data, 1);
111         f:close();
112         if not next(data) then -- try to delete empty datastore
113                 os_remove(getpath(username, host, datastore));
114         end
115         -- we write data even when we are deleting because lua doesn't have a
116         -- platform independent way of checking for non-exisitng files
117         return true;
118 end
119
120 function list_append(username, host, datastore, data)
121         if not data then return; end
122         -- save the datastore
123         local f, msg = io_open(getpath(username, host, datastore, "list"), "a+");
124         if not f then
125                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
126                 return;
127         end
128         f:write("item(");
129         simplesave(f, data, 1);
130         f:write(");\n");
131         f:close();
132         return true;
133 end
134
135 function list_store(username, host, datastore, data)
136         if not data then
137                 data = {};
138         end
139         -- save the datastore
140         local f, msg = io_open(getpath(username, host, datastore, "list"), "w+");
141         if not f then
142                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
143                 return;
144         end
145         for _, d in ipairs(data) do
146                 f:write("item(");
147                 simplesave(f, d, 1);
148                 f:write(");\n");
149         end
150         f:close();
151         if not next(data) then -- try to delete empty datastore
152                 os_remove(getpath(username, host, datastore, "list"));
153         end
154         -- we write data even when we are deleting because lua doesn't have a
155         -- platform independent way of checking for non-exisitng files
156         return true;
157 end
158
159 function list_load(username, host, datastore)
160         local data, ret = loadfile(getpath(username, host, datastore, "list"));
161         if not data then
162                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
163                 return nil;
164         end
165         local items = {};
166         setfenv(data, {item = function(i) t_insert(items, i); end});
167         local success, ret = pcall(data);
168         if not success then
169                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
170                 return nil;
171         end
172         return items;
173 end
174
175 return _M;