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