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