Merge with backout
[prosody.git] / util / datamanager.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 format = string.format;
11 local setmetatable, type = setmetatable, type;
12 local pairs, ipairs = pairs, ipairs;
13 local char = string.char;
14 local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
15 local log = require "util.logger".init("datamanager");
16 local io_open = io.open;
17 local os_remove = os.remove;
18 local tostring, tonumber = tostring, tonumber;
19 local error = error;
20 local next = next;
21 local t_insert = table.insert;
22 local append = require "util.serialization".append;
23 local path_separator = "/"; if os.getenv("WINDIR") then path_separator = "\\" end
24 local raw_mkdir;
25
26 if prosody.platform == "posix" then
27         raw_mkdir = require "util.pposix".mkdir; -- Doesn't trample on umask
28 else
29         raw_mkdir = require "lfs".mkdir;
30 end
31
32 module "datamanager"
33
34 ---- utils -----
35 local encode, decode;
36 do
37         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
38
39         decode = function (s)
40                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
41         end
42
43         encode = function (s)
44                 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
45         end
46 end
47
48 local _mkdir = {};
49 local function mkdir(path)
50         path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
51         if not _mkdir[path] then
52                 raw_mkdir(path);
53                 _mkdir[path] = true;
54         end
55         return path;
56 end
57
58 local data_path = "data";
59 local callbacks = {};
60
61 ------- API -------------
62
63 function set_data_path(path)
64         log("debug", "Setting data path to: %s", path);
65         data_path = path;
66 end
67
68 local function callback(username, host, datastore, data)
69         for _, f in ipairs(callbacks) do
70                 username, host, datastore, data = f(username, host, datastore, data);
71                 if username == false then break; end
72         end
73         
74         return username, host, datastore, data;
75 end
76 function add_callback(func)
77         if not callbacks[func] then -- Would you really want to set the same callback more than once?
78                 callbacks[func] = true;
79                 callbacks[#callbacks+1] = func;
80                 return true;
81         end
82 end
83 function remove_callback(func)
84         if callbacks[func] then
85                 for i, f in ipairs(callbacks) do
86                         if f == func then
87                                 callbacks[i] = nil;
88                                 callbacks[f] = nil;
89                                 return true;
90                         end
91                 end
92         end
93 end
94
95 function getpath(username, host, datastore, ext, create)
96         ext = ext or "dat";
97         host = (host and encode(host)) or "_global";
98         username = username and encode(username);
99         if username then
100                 if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
101                 return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
102         elseif host then
103                 if create then mkdir(mkdir(data_path).."/"..host); end
104                 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
105         else
106                 if create then mkdir(data_path); end
107                 return format("%s/%s.%s", data_path, datastore, ext);
108         end
109 end
110
111 function load(username, host, datastore)
112         local data, ret = loadfile(getpath(username, host, datastore));
113         if not data then
114                 log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
115                 return nil;
116         end
117         setfenv(data, {});
118         local success, ret = pcall(data);
119         if not success then
120                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
121                 return nil;
122         end
123         return ret;
124 end
125
126 function store(username, host, datastore, data)
127         if not data then
128                 data = {};
129         end
130
131         username, host, datastore, data = callback(username, host, datastore, data);
132         if username == false then
133                 return true; -- Don't save this data at all
134         end
135
136         -- save the datastore
137         local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
138         if not f then
139                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
140                 return;
141         end
142         f:write("return ");
143         append(f, data);
144         f:close();
145         if next(data) == nil then -- try to delete empty datastore
146                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
147                 os_remove(getpath(username, host, datastore));
148         end
149         -- we write data even when we are deleting because lua doesn't have a
150         -- platform independent way of checking for non-exisitng files
151         return true;
152 end
153
154 function list_append(username, host, datastore, data)
155         if not data then return; end
156         if callback(username, host, datastore) == false then return true; end
157         -- save the datastore
158         local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+");
159         if not f then
160                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
161                 return;
162         end
163         f:write("item(");
164         append(f, data);
165         f:write(");\n");
166         f:close();
167         return true;
168 end
169
170 function list_store(username, host, datastore, data)
171         if not data then
172                 data = {};
173         end
174         if callback(username, host, datastore) == false then return true; end
175         -- save the datastore
176         local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
177         if not f then
178                 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
179                 return;
180         end
181         for _, d in ipairs(data) do
182                 f:write("item(");
183                 append(f, d);
184                 f:write(");\n");
185         end
186         f:close();
187         if next(data) == nil then -- try to delete empty datastore
188                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
189                 os_remove(getpath(username, host, datastore, "list"));
190         end
191         -- we write data even when we are deleting because lua doesn't have a
192         -- platform independent way of checking for non-exisitng files
193         return true;
194 end
195
196 function list_load(username, host, datastore)
197         local data, ret = loadfile(getpath(username, host, datastore, "list"));
198         if not data then
199                 log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
200                 return nil;
201         end
202         local items = {};
203         setfenv(data, {item = function(i) t_insert(items, i); end});
204         local success, ret = pcall(data);
205         if not success then
206                 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
207                 return nil;
208         end
209         return items;
210 end
211
212 return _M;