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