Merge 0.10->trunk
[prosody.git] / core / moduleapi.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2012 Matthew Wild
3 -- Copyright (C) 2008-2012 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 local config = require "core.configmanager";
10 local modulemanager; -- This gets set from modulemanager
11 local array = require "util.array";
12 local set = require "util.set";
13 local logger = require "util.logger";
14 local pluginloader = require "util.pluginloader";
15 local timer = require "util.timer";
16 local resolve_relative_path = require"util.paths".resolve_relative_path;
17 local measure = require "core.statsmanager".measure;
18
19 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
20 local error, setmetatable, type = error, setmetatable, type;
21 local ipairs, pairs, select = ipairs, pairs, select;
22 local tonumber, tostring = tonumber, tostring;
23 local require = require;
24 local pack = table.pack or function(...) return {n=select("#",...), ...}; end -- table.pack is only in 5.2
25 local unpack = table.unpack or unpack; -- renamed in 5.2
26
27 local prosody = prosody;
28 local hosts = prosody.hosts;
29
30 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
31 local core_post_stanza = assert(prosody.core_post_stanza,
32         "prosody.core_post_stanza is nil, please report this as a bug");
33
34 -- Registry of shared module data
35 local shared_data = setmetatable({}, { __mode = "v" });
36
37 local NULL = {};
38
39 local api = {};
40
41 -- Returns the name of the current module
42 function api:get_name()
43         return self.name;
44 end
45
46 -- Returns the host that the current module is serving
47 function api:get_host()
48         return self.host;
49 end
50
51 function api:get_host_type()
52         return (self.host == "*" and "global") or hosts[self.host].type or "local";
53 end
54
55 function api:set_global()
56         self.host = "*";
57         -- Update the logger
58         local _log = logger.init("mod_"..self.name);
59         self.log = function (self, ...) return _log(...); end;
60         self._log = _log;
61         self.global = true;
62 end
63
64 function api:add_feature(xmlns)
65         self:add_item("feature", xmlns);
66 end
67 function api:add_identity(category, type, name)
68         self:add_item("identity", {category = category, type = type, name = name});
69 end
70 function api:add_extension(data)
71         self:add_item("extension", data);
72 end
73 function api:has_feature(xmlns)
74         for _, feature in ipairs(self:get_host_items("feature")) do
75                 if feature == xmlns then return true; end
76         end
77         return false;
78 end
79 function api:has_identity(category, type, name)
80         for _, id in ipairs(self:get_host_items("identity")) do
81                 if id.category == category and id.type == type and id.name == name then
82                         return true;
83                 end
84         end
85         return false;
86 end
87
88 function api:fire_event(...)
89         return (hosts[self.host] or prosody).events.fire_event(...);
90 end
91
92 function api:hook_object_event(object, event, handler, priority)
93         self.event_handlers:set(object, event, handler, true);
94         return object.add_handler(event, handler, priority);
95 end
96
97 function api:unhook_object_event(object, event, handler)
98         return object.remove_handler(event, handler);
99 end
100
101 function api:hook(event, handler, priority)
102         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
103 end
104
105 function api:hook_global(event, handler, priority)
106         return self:hook_object_event(prosody.events, event, handler, priority);
107 end
108
109 function api:hook_tag(xmlns, name, handler, priority)
110         if not handler and type(name) == "function" then
111                 -- If only 2 options then they specified no xmlns
112                 xmlns, name, handler, priority = nil, xmlns, name, handler;
113         elseif not (handler and name) then
114                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
115                 return;
116         end
117         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
118 end
119 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
120
121 function api:unhook(event, handler)
122         return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
123 end
124
125 function api:require(lib)
126         local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
127         if not f then
128                 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
129         end
130         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
131         return f();
132 end
133
134 function api:depends(name)
135         if not self.dependencies then
136                 self.dependencies = {};
137                 self:hook("module-reloaded", function (event)
138                         if self.dependencies[event.module] and not self.reloading then
139                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
140                                 modulemanager.reload(self.host, self.name);
141                                 return;
142                         end
143                 end);
144                 self:hook("module-unloaded", function (event)
145                         if self.dependencies[event.module] then
146                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
147                                 modulemanager.unload(self.host, self.name);
148                         end
149                 end);
150         end
151         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
152         if mod and mod.module.host == "*" and self.host ~= "*"
153         and modulemanager.module_has_method(mod, "add_host") then
154                 mod = nil; -- Target is a shared module, so we still want to load it on our host
155         end
156         if not mod then
157                 local err;
158                 mod, err = modulemanager.load(self.host, name);
159                 if not mod then
160                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
161                 end
162         end
163         self.dependencies[name] = true;
164         return mod;
165 end
166
167 -- Returns one or more shared tables at the specified virtual paths
168 -- Intentionally does not allow the table at a path to be _set_, it
169 -- is auto-created if it does not exist.
170 function api:shared(...)
171         if not self.shared_data then self.shared_data = {}; end
172         local paths = { n = select("#", ...), ... };
173         local data_array = {};
174         local default_path_components = { self.host, self.name };
175         for i = 1, paths.n do
176                 local path = paths[i];
177                 if path:sub(1,1) ~= "/" then -- Prepend default components
178                         local n_components = select(2, path:gsub("/", "%1"));
179                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
180                 end
181                 local shared = shared_data[path];
182                 if not shared then
183                         shared = {};
184                         if path:match("%-cache$") then
185                                 setmetatable(shared, { __mode = "kv" });
186                         end
187                         shared_data[path] = shared;
188                 end
189                 t_insert(data_array, shared);
190                 self.shared_data[path] = shared;
191         end
192         return unpack(data_array);
193 end
194
195 function api:get_option(name, default_value)
196         local value = config.get(self.host, name);
197         if value == nil then
198                 value = default_value;
199         end
200         return value;
201 end
202
203 function api:get_option_string(name, default_value)
204         local value = self:get_option(name, default_value);
205         if type(value) == "table" then
206                 if #value > 1 then
207                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
208                 end
209                 value = value[1];
210         end
211         if value == nil then
212                 return nil;
213         end
214         return tostring(value);
215 end
216
217 function api:get_option_number(name, ...)
218         local value = self:get_option(name, ...);
219         if type(value) == "table" then
220                 if #value > 1 then
221                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
222                 end
223                 value = value[1];
224         end
225         local ret = tonumber(value);
226         if value ~= nil and ret == nil then
227                 self:log("error", "Config option '%s' not understood, expecting a number", name);
228         end
229         return ret;
230 end
231
232 function api:get_option_boolean(name, ...)
233         local value = self:get_option(name, ...);
234         if type(value) == "table" then
235                 if #value > 1 then
236                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
237                 end
238                 value = value[1];
239         end
240         if value == nil then
241                 return nil;
242         end
243         local ret = value == true or value == "true" or value == 1 or nil;
244         if ret == nil then
245                 ret = (value == false or value == "false" or value == 0);
246                 if ret then
247                         ret = false;
248                 else
249                         ret = nil;
250                 end
251         end
252         if ret == nil then
253                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
254         end
255         return ret;
256 end
257
258 function api:get_option_array(name, ...)
259         local value = self:get_option(name, ...);
260
261         if value == nil then
262                 return nil;
263         end
264
265         if type(value) ~= "table" then
266                 return array{ value }; -- Assume any non-list is a single-item list
267         end
268
269         return array():append(value); -- Clone
270 end
271
272 function api:get_option_set(name, ...)
273         local value = self:get_option_array(name, ...);
274
275         if value == nil then
276                 return nil;
277         end
278
279         return set.new(value);
280 end
281
282 function api:get_option_inherited_set(name, ...)
283         local value = self:get_option_set(name, ...);
284         local global_value = self:context("*"):get_option_set(name, ...);
285         if not value then
286                 return global_value;
287         elseif not global_value then
288                 return value;
289         end
290         value:include(global_value);
291         return value;
292 end
293
294 function api:context(host)
295         return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
296 end
297
298 function api:add_item(key, value)
299         self.items = self.items or {};
300         self.items[key] = self.items[key] or {};
301         t_insert(self.items[key], value);
302         self:fire_event("item-added/"..key, {source = self, item = value});
303 end
304 function api:remove_item(key, value)
305         local t = self.items and self.items[key] or NULL;
306         for i = #t,1,-1 do
307                 if t[i] == value then
308                         t_remove(self.items[key], i);
309                         self:fire_event("item-removed/"..key, {source = self, item = value});
310                         return value;
311                 end
312         end
313 end
314
315 function api:get_host_items(key)
316         local result = modulemanager.get_items(key, self.host) or {};
317         return result;
318 end
319
320 function api:handle_items(type, added_cb, removed_cb, existing)
321         self:hook("item-added/"..type, added_cb);
322         self:hook("item-removed/"..type, removed_cb);
323         if existing ~= false then
324                 for _, item in ipairs(self:get_host_items(type)) do
325                         added_cb({ item = item });
326                 end
327         end
328 end
329
330 function api:provides(name, item)
331         -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
332         if not item then
333                 item = {}
334                 for k,v in pairs(self.environment) do
335                         if k ~= "module" then item[k] = v; end
336                 end
337         end
338         if not item.name then
339                 local item_name = self.name;
340                 -- Strip a provider prefix to find the item name
341                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
342                 if item_name:find(name.."_", 1, true) == 1 then
343                         item_name = item_name:sub(#name+2);
344                 end
345                 item.name = item_name;
346         end
347         item._provided_by = self.name;
348         self:add_item(name.."-provider", item);
349 end
350
351 function api:send(stanza)
352         return core_post_stanza(hosts[self.host], stanza);
353 end
354
355 local timer_methods = { }
356 local timer_mt = {
357         __index = timer_methods;
358 }
359 function timer_methods:stop( )
360         timer.stop(self.id);
361 end
362 timer_methods.disarm = timer_methods.stop
363 function timer_methods:reschedule(delay)
364         timer.reschedule(self.id, delay)
365 end
366
367 local function timer_callback(now, id, t)
368         if t.module_env.loaded == false then return; end
369         return t.callback(now, unpack(t, 1, t.n));
370 end
371
372 function api:add_timer(delay, callback, ...)
373         local t = pack(...)
374         t.module_env = self;
375         t.callback = callback;
376         t.id = timer.add_task(delay, timer_callback, t);
377         return setmetatable(t, timer_mt);
378 end
379
380 local path_sep = package.config:sub(1,1);
381 function api:get_directory()
382         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
383 end
384
385 function api:load_resource(path, mode)
386         path = resolve_relative_path(self:get_directory(), path);
387         return io.open(path, mode);
388 end
389
390 function api:open_store(name, type)
391         return require"core.storagemanager".open(self.host, name or self.name, type);
392 end
393
394 function api:measure(name, type)
395         return measure(type, "/"..self.host.."/mod_"..self.name.."/"..name);
396 end
397
398 function api.init(mm)
399         modulemanager = mm;
400         return api;
401 end
402
403 return api;