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