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