Insert copyright/license headers
[prosody.git] / util / datamanager.lua
1 -- Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21 local format = string.format;
22 local setmetatable, type = setmetatable, type;
23 local pairs, ipairs = pairs, ipairs;
24 local char = string.char;
25 local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
26 local log = require "util.logger".init("datamanager");
27 local io_open = io.open;
28 local os_remove = os.remove;
29 local tostring, tonumber = tostring, tonumber;
30 local error = error;
31 local next = next;
32 local t_insert = table.insert;
33
34 local indent = function(f, i)
35         for n = 1, i do
36                 f:write("\t");
37         end
38 end
39
40 local data_path = "data";
41
42 module "datamanager"
43
44
45 ---- utils -----
46 local encode, decode;
47
48 do 
49         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
50
51         decode = function (s)
52                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
53         end
54
55         encode = function (s)
56                 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
57         end
58 end
59
60 local function basicSerialize (o)
61         if type(o) == "number" or type(o) == "boolean" then
62                 return tostring(o);
63         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
64                 return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
65         end
66 end
67
68
69 local function simplesave (f, o, ind)
70         if type(o) == "number" then
71                 f:write(o)
72         elseif type(o) == "string" then
73                 f:write((format("%q", o):gsub("\\\n", "\\n")))
74         elseif type(o) == "table" then
75                 f:write("{\n")
76                 for k,v in pairs(o) do
77                         indent(f, ind);
78                         f:write("[", basicSerialize(k), "] = ")
79                         simplesave(f, v, ind+1)
80                         f:write(",\n")
81                 end
82                 indent(f, ind-1);
83                 f:write("}")
84         elseif type(o) == "boolean" then
85                 f:write(o and "true" or "false");
86         else
87                 error("cannot serialize a " .. type(o))
88         end
89 end
90
91 ------- API -------------
92
93 function set_data_path(path)
94         data_path = path;
95 end
96
97 function getpath(username, host, datastore, ext)
98         ext = ext or "dat";
99         if username then
100                 return format("%s/%s/%s/%s.%s", data_path, encode(host), datastore, encode(username), ext);
101         elseif host then
102                 return format("%s/%s/%s.%s", data_path, encode(host), datastore, ext);
103         else
104                 return format("%s/%s.%s", data_path, datastore, ext);
105         end
106 end
107
108 function load(username, host, datastore)
109         local data, ret = loadfile(getpath(username, host, datastore));
110         if not data then
111                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
112                 return nil;
113         end
114         setfenv(data, {});
115         local success, ret = pcall(data);
116         if not success then
117                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
118                 return nil;
119         end
120         return ret;
121 end
122
123 function store(username, host, datastore, data)
124         if not data then
125                 data = {};
126         end
127         -- save the datastore
128         local f, msg = io_open(getpath(username, host, datastore), "w+");
129         if not f then
130                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
131                 return;
132         end
133         f:write("return ");
134         simplesave(f, data, 1);
135         f:close();
136         if not next(data) then -- try to delete empty datastore
137                 os_remove(getpath(username, host, datastore));
138         end
139         -- we write data even when we are deleting because lua doesn't have a
140         -- platform independent way of checking for non-exisitng files
141         return true;
142 end
143
144 function list_append(username, host, datastore, data)
145         if not data then return; end
146         -- save the datastore
147         local f, msg = io_open(getpath(username, host, datastore, "list"), "a+");
148         if not f then
149                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
150                 return;
151         end
152         f:write("item(");
153         simplesave(f, data, 1);
154         f:write(");\n");
155         f:close();
156         return true;
157 end
158
159 function list_store(username, host, datastore, data)
160         if not data then
161                 data = {};
162         end
163         -- save the datastore
164         local f, msg = io_open(getpath(username, host, datastore, "list"), "w+");
165         if not f then
166                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
167                 return;
168         end
169         for _, d in ipairs(data) do
170                 f:write("item(");
171                 simplesave(f, d, 1);
172                 f:write(");\n");
173         end
174         f:close();
175         if not next(data) then -- try to delete empty datastore
176                 os_remove(getpath(username, host, datastore, "list"));
177         end
178         -- we write data even when we are deleting because lua doesn't have a
179         -- platform independent way of checking for non-exisitng files
180         return true;
181 end
182
183 function list_load(username, host, datastore)
184         local data, ret = loadfile(getpath(username, host, datastore, "list"));
185         if not data then
186                 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
187                 return nil;
188         end
189         local items = {};
190         setfenv(data, {item = function(i) t_insert(items, i); end});
191         local success, ret = pcall(data);
192         if not success then
193                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
194                 return nil;
195         end
196         return items;
197 end
198
199 return _M;