Minor fix
[prosody.git] / util / datamanager.lua
1 local format = string.format;
2 local setmetatable, type = setmetatable, type;
3 local pairs = pairs;
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 tostring = tostring;
9
10 module "datamanager"
11
12
13 ---- utils -----
14 local encode, decode;
15
16 local log = function (type, msg) return log(type, "datamanager", msg); end
17
18 do 
19         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
20
21         decode = function (s)
22                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
23         end
24
25         encode = function (s)
26                 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
27         end
28 end
29
30 local function basicSerialize (o)
31   if type(o) == "number" or type(o) == "boolean" then
32     return tostring(o)
33   else -- assume it is a string
34     return format("%q", tostring(o))
35   end
36 end
37
38
39 local function simplesave (f, o)
40       if type(o) == "number" then
41         f:write(o)
42       elseif type(o) == "string" then
43         f:write(format("%q", o))
44       elseif type(o) == "table" then
45         f:write("{\n")
46         for k,v in pairs(o) do
47           f:write(" [", basicSerialize(k), "] = ")
48           simplesave(f, v)
49           f:write(",\n")
50         end
51         f:write("}\n")
52       else
53         error("cannot serialize a " .. type(o))
54       end
55     end
56   
57 ------- API -------------
58
59 function getpath(username, host, datastore)
60         if username then
61                 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
62         elseif host then
63                 return format("data/%s/%s.dat", encode(host), datastore);
64         else
65                 return format("data/%s.dat", datastore);
66         end
67 end
68
69 function load(username, host, datastore)
70         local data, ret = loadfile(getpath(username, host, datastore));
71         if not data then log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
72         setfenv(data, {});
73         local success, ret = pcall(data);
74         if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end
75         return ret;
76 end
77
78 function store(username, host, datastore, data)
79         local f, msg = io_open(getpath(username, host, datastore), "w+");
80         if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..username.."@"..host); return nil; end
81         f:write("return ");
82         simplesave(f, data);
83         f:close();
84         return true;
85 end
86