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