Forced merge.
[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 = require "util.logger".init("datamanager");
7 local io_open = io.open;
8 local os_remove = os.remove;
9 local tostring, tonumber = tostring, tonumber;
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 local data_path = "data";
21
22 module "datamanager"
23
24
25 ---- utils -----
26 local encode, decode;
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 set_data_path(path)
74         data_path = path;
75 end
76
77 function getpath(username, host, datastore, ext)
78         ext = ext or "dat";
79         if username then
80                 return format("%s/%s/%s/%s.%s", data_path, encode(host), datastore, encode(username), ext);
81         elseif host then
82                 return format("%s/%s/%s.%s", data_path, encode(host), datastore, ext);
83         else
84                 return format("%s/%s.%s", data_path, datastore, ext);
85         end
86 end
87
88 function load(username, host, datastore)
89         local data, ret = loadfile(getpath(username, host, datastore));
90         if not data then
91                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
92                 return nil;
93         end
94         setfenv(data, {});
95         local success, ret = pcall(data);
96         if not success then
97                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
98                 return nil;
99         end
100         return ret;
101 end
102
103 function store(username, host, datastore, data)
104         if not data then
105                 data = {};
106         end
107         -- save the datastore
108         local f, msg = io_open(getpath(username, host, datastore), "w+");
109         if not f then
110                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
111                 return;
112         end
113         f:write("return ");
114         simplesave(f, data, 1);
115         f:close();
116         if not next(data) then -- try to delete empty datastore
117                 os_remove(getpath(username, host, datastore));
118         end
119         -- we write data even when we are deleting because lua doesn't have a
120         -- platform independent way of checking for non-exisitng files
121         return true;
122 end
123
124 function list_append(username, host, datastore, data)
125         if not data then return; end
126         -- save the datastore
127         local f, msg = io_open(getpath(username, host, datastore, "list"), "a+");
128         if not f then
129                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
130                 return;
131         end
132         f:write("item(");
133         simplesave(f, data, 1);
134         f:write(");\n");
135         f:close();
136         return true;
137 end
138
139 function list_store(username, host, datastore, data)
140         if not data then
141                 data = {};
142         end
143         -- save the datastore
144         local f, msg = io_open(getpath(username, host, datastore, "list"), "w+");
145         if not f then
146                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
147                 return;
148         end
149         for _, d in ipairs(data) do
150                 f:write("item(");
151                 simplesave(f, d, 1);
152                 f:write(");\n");
153         end
154         f:close();
155         if not next(data) then -- try to delete empty datastore
156                 os_remove(getpath(username, host, datastore, "list"));
157         end
158         -- we write data even when we are deleting because lua doesn't have a
159         -- platform independent way of checking for non-exisitng files
160         return true;
161 end
162
163 function list_load(username, host, datastore)
164         local data, ret = loadfile(getpath(username, host, datastore, "list"));
165         if not data then
166                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
167                 return nil;
168         end
169         local items = {};
170         setfenv(data, {item = function(i) t_insert(items, i); end});
171         local success, ret = pcall(data);
172         if not success then
173                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
174                 return nil;
175         end
176         return items;
177 end
178
179 return _M;