5817894f938e8d88dcad88f085107973ac6244fe
[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 array = require "util.array";
11 local set = require "util.set";
12 local it = require "util.iterators";
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 local st = require "util.stanza";
19
20 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
21 local error, setmetatable, type = error, setmetatable, type;
22 local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
23 local tonumber, tostring = tonumber, tostring;
24 local require = require;
25
26 local prosody = prosody;
27 local hosts = prosody.hosts;
28
29 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
30 local core_post_stanza = assert(prosody.core_post_stanza,
31         "prosody.core_post_stanza is nil, please report this as a bug");
32
33 -- Registry of shared module data
34 local shared_data = setmetatable({}, { __mode = "v" });
35
36 local NULL = {};
37
38 local api = {};
39
40 -- Returns the name of the current module
41 function api:get_name()
42         return self.name;
43 end
44
45 -- Returns the host that the current module is serving
46 function api:get_host()
47         return self.host;
48 end
49
50 function api:get_host_type()
51         return (self.host == "*" and "global") or hosts[self.host].type or "local";
52 end
53
54 function api:set_global()
55         self.host = "*";
56         -- Update the logger
57         local _log = logger.init("mod_"..self.name);
58         self.log = function (self, ...) return _log(...); end; --luacheck: ignore self
59         self._log = _log;
60         self.global = true;
61 end
62
63 function api:add_feature(xmlns)
64         self:add_item("feature", xmlns);
65 end
66 function api:add_identity(category, identity_type, name)
67         self:add_item("identity", {category = category, type = identity_type, name = name});
68 end
69 function api:add_extension(data)
70         self:add_item("extension", data);
71 end
72 function api:has_feature(xmlns)
73         for _, feature in ipairs(self:get_host_items("feature")) do
74                 if feature == xmlns then return true; end
75         end
76         return false;
77 end
78 function api:has_identity(category, identity_type, name)
79         for _, id in ipairs(self:get_host_items("identity")) do
80                 if id.category == category and id.type == identity_type and id.name == name then
81                         return true;
82                 end
83         end
84         return false;
85 end
86
87 function api:fire_event(...)
88         return (hosts[self.host] or prosody).events.fire_event(...);
89 end
90
91 function api:hook_object_event(object, event, handler, priority)
92         self.event_handlers:set(object, event, handler, true);
93         return object.add_handler(event, handler, priority);
94 end
95
96 function api:unhook_object_event(object, event, handler)
97         self.event_handlers:set(object, event, handler, nil);
98         return object.remove_handler(event, handler);
99 end
100
101 function api:hook(event, handler, priority)
102         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
103 end
104
105 function api:hook_global(event, handler, priority)
106         return self:hook_object_event(prosody.events, event, handler, priority);
107 end
108
109 function api:hook_tag(xmlns, name, handler, priority)
110         if not handler and type(name) == "function" then
111                 -- If only 2 options then they specified no xmlns
112                 xmlns, name, handler, priority = nil, xmlns, name, handler;
113         elseif not (handler and name) then
114                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
115                 return;
116         end
117         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
118 end
119 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
120
121 function api:unhook(event, handler)
122         return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
123 end
124
125 function api:wrap_object_event(events_object, event, handler)
126         return self:hook_object_event(assert(events_object.wrappers, "no wrappers"), event, handler);
127 end
128
129 function api:wrap_event(event, handler)
130         return self:wrap_object_event((hosts[self.host] or prosody).events, event, handler);
131 end
132
133 function api:wrap_global(event, handler)
134         return self:hook_object_event(prosody.events, event, handler);
135 end
136
137 function api:require(lib)
138         local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
139         if not f then
140                 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
141         end
142         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
143         return f();
144 end
145
146 function api:depends(name)
147         local modulemanager = require"core.modulemanager";
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 modulemanager = require"core.modulemanager";
330         local result = modulemanager.get_items(key, self.host) or {};
331         return result;
332 end
333
334 function api:handle_items(item_type, added_cb, removed_cb, existing)
335         self:hook("item-added/"..item_type, added_cb);
336         self:hook("item-removed/"..item_type, removed_cb);
337         if existing ~= false then
338                 for _, item in ipairs(self:get_host_items(item_type)) do
339                         added_cb({ item = item });
340                 end
341         end
342 end
343
344 function api:provides(name, item)
345         -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
346         if not item then
347                 item = {}
348                 for k,v in pairs(self.environment) do
349                         if k ~= "module" then item[k] = v; end
350                 end
351         end
352         if not item.name then
353                 local item_name = self.name;
354                 -- Strip a provider prefix to find the item name
355                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
356                 if item_name:find(name.."_", 1, true) == 1 then
357                         item_name = item_name:sub(#name+2);
358                 end
359                 item.name = item_name;
360         end
361         item._provided_by = self.name;
362         self:add_item(name.."-provider", item);
363 end
364
365 function api:send(stanza)
366         return core_post_stanza(hosts[self.host], stanza);
367 end
368
369 function api:broadcast(jids, stanza, iter)
370         for jid in (iter or it.values)(jids) do
371                 local new_stanza = st.clone(stanza);
372                 new_stanza.attr.to = jid;
373                 core_post_stanza(hosts[self.host], new_stanza);
374         end
375 end
376
377 function api:add_timer(delay, callback)
378         return timer.add_task(delay, function (t)
379                 if self.loaded == false then return; end
380                 return callback(t);
381         end);
382 end
383
384 local path_sep = package.config:sub(1,1);
385 function api:get_directory()
386         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
387 end
388
389 function api:load_resource(path, mode)
390         path = resolve_relative_path(self:get_directory(), path);
391         return io.open(path, mode);
392 end
393
394 function api:open_store(name, store_type)
395         return require"core.storagemanager".open(self.host, name or self.name, store_type);
396 end
397
398 function api:measure(name, stat_type)
399         return measure(stat_type, "/"..self.host.."/mod_"..self.name.."/"..name);
400 end
401
402 function api:measure_object_event(events_object, event_name, stat_name)
403         local m = self:measure(stat_name or event_name, "duration");
404         local function handler(handlers, _event_name, _event_data)
405                 local finished = m();
406                 local ret = handlers(_event_name, _event_data);
407                 finished();
408                 return ret;
409         end
410         return self:hook_object_event(events_object, event_name, handler);
411 end
412
413 function api:measure_event(event_name, stat_name)
414         return self:measure_object_event((hosts[self.host] or prosody).events.wrappers, event_name, stat_name);
415 end
416
417 function api:measure_global_event(event_name, stat_name)
418         return self:measure_object_event(prosody.events.wrappers, event_name, stat_name);
419 end
420
421 return api;