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