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