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