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