2 -- Copyright (C) 2008-2012 Matthew Wild
3 -- Copyright (C) 2008-2012 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
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";
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 = ipairs, pairs, select;
23 local tonumber, tostring = tonumber, tostring;
24 local require = require;
25 local pack = table.pack or function(...) return {n=select("#",...), ...}; end -- table.pack is only in 5.2
26 local unpack = table.unpack or unpack; --luacheck: ignore 113 -- renamed in 5.2
28 local prosody = prosody;
29 local hosts = prosody.hosts;
31 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
32 local core_post_stanza = assert(prosody.core_post_stanza,
33 "prosody.core_post_stanza is nil, please report this as a bug");
35 -- Registry of shared module data
36 local shared_data = setmetatable({}, { __mode = "v" });
42 -- Returns the name of the current module
43 function api:get_name()
47 -- Returns the host that the current module is serving
48 function api:get_host()
52 function api:get_host_type()
53 return (self.host == "*" and "global") or hosts[self.host].type or "local";
56 function api:set_global()
59 local _log = logger.init("mod_"..self.name);
60 self.log = function (self, ...) return _log(...); end; --luacheck: ignore self
65 function api:add_feature(xmlns)
66 self:add_item("feature", xmlns);
68 function api:add_identity(category, identity_type, name)
69 self:add_item("identity", {category = category, type = identity_type, name = name});
71 function api:add_extension(data)
72 self:add_item("extension", data);
74 function api:has_feature(xmlns)
75 for _, feature in ipairs(self:get_host_items("feature")) do
76 if feature == xmlns then return true; end
80 function api:has_identity(category, identity_type, name)
81 for _, id in ipairs(self:get_host_items("identity")) do
82 if id.category == category and id.type == identity_type and id.name == name then
89 function api:fire_event(...)
90 return (hosts[self.host] or prosody).events.fire_event(...);
93 function api:hook_object_event(object, event, handler, priority)
94 self.event_handlers:set(object, event, handler, true);
95 return object.add_handler(event, handler, priority);
98 function api:unhook_object_event(object, event, handler)
99 self.event_handlers:set(object, event, handler, nil);
100 return object.remove_handler(event, handler);
103 function api:hook(event, handler, priority)
104 return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
107 function api:hook_global(event, handler, priority)
108 return self:hook_object_event(prosody.events, event, handler, priority);
111 function api:hook_tag(xmlns, name, handler, priority)
112 if not handler and type(name) == "function" then
113 -- If only 2 options then they specified no xmlns
114 xmlns, name, handler, priority = nil, xmlns, name, handler;
115 elseif not (handler and name) then
116 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
119 return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
121 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
123 function api:unhook(event, handler)
124 return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
127 function api:wrap_object_event(events_object, event, handler)
128 return self:hook_object_event(assert(events_object.wrappers, "no wrappers"), event, handler);
131 function api:wrap_event(event, handler)
132 return self:wrap_object_event((hosts[self.host] or prosody).events, event, handler);
135 function api:wrap_global(event, handler)
136 return self:hook_object_event(prosody.events, event, handler);
139 function api:require(lib)
140 local f, n = pluginloader.load_code_ext(self.name, lib, "lib.lua", self.environment);
141 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
145 function api:depends(name)
146 local modulemanager = require"core.modulemanager";
147 if not self.dependencies then
148 self.dependencies = {};
149 self:hook("module-reloaded", function (event)
150 if self.dependencies[event.module] and not self.reloading then
151 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
152 modulemanager.reload(self.host, self.name);
156 self:hook("module-unloaded", function (event)
157 if self.dependencies[event.module] then
158 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
159 modulemanager.unload(self.host, self.name);
163 local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
164 if mod and mod.module.host == "*" and self.host ~= "*"
165 and modulemanager.module_has_method(mod, "add_host") then
166 mod = nil; -- Target is a shared module, so we still want to load it on our host
170 mod, err = modulemanager.load(self.host, name);
172 return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
175 self.dependencies[name] = true;
179 -- Returns one or more shared tables at the specified virtual paths
180 -- Intentionally does not allow the table at a path to be _set_, it
181 -- is auto-created if it does not exist.
182 function api:shared(...)
183 if not self.shared_data then self.shared_data = {}; end
184 local paths = { n = select("#", ...), ... };
185 local data_array = {};
186 local default_path_components = { self.host, self.name };
187 for i = 1, paths.n do
188 local path = paths[i];
189 if path:sub(1,1) ~= "/" then -- Prepend default components
190 local n_components = select(2, path:gsub("/", "%1"));
191 path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
193 local shared = shared_data[path];
196 if path:match("%-cache$") then
197 setmetatable(shared, { __mode = "kv" });
199 shared_data[path] = shared;
201 t_insert(data_array, shared);
202 self.shared_data[path] = shared;
204 return unpack(data_array);
207 function api:get_option(name, default_value)
208 local value = config.get(self.host, name);
210 value = default_value;
215 function api:get_option_string(name, default_value)
216 local value = self:get_option(name, default_value);
217 if type(value) == "table" then
219 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
226 return tostring(value);
229 function api:get_option_number(name, ...)
230 local value = self:get_option(name, ...);
231 if type(value) == "table" then
233 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
237 local ret = tonumber(value);
238 if value ~= nil and ret == nil then
239 self:log("error", "Config option '%s' not understood, expecting a number", name);
244 function api:get_option_boolean(name, ...)
245 local value = self:get_option(name, ...);
246 if type(value) == "table" then
248 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
255 local ret = value == true or value == "true" or value == 1 or nil;
257 ret = (value == false or value == "false" or value == 0);
265 self:log("error", "Config option '%s' not understood, expecting true/false", name);
270 function api:get_option_array(name, ...)
271 local value = self:get_option(name, ...);
277 if type(value) ~= "table" then
278 return array{ value }; -- Assume any non-list is a single-item list
281 return array():append(value); -- Clone
284 function api:get_option_set(name, ...)
285 local value = self:get_option_array(name, ...);
291 return set.new(value);
294 function api:get_option_inherited_set(name, ...)
295 local value = self:get_option_set(name, ...);
296 local global_value = self:context("*"):get_option_set(name, ...);
299 elseif not global_value then
302 value:include(global_value);
306 function api:get_option_path(name, default, parent)
307 if parent == nil then
308 parent = parent or self:get_directory();
309 elseif prosody.paths[parent] then
310 parent = prosody.paths[parent];
312 local value = self:get_option_string(name, default);
316 return resolve_relative_path(parent, value);
320 function api:context(host)
321 return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
324 function api:add_item(key, value)
325 self.items = self.items or {};
326 self.items[key] = self.items[key] or {};
327 t_insert(self.items[key], value);
328 self:fire_event("item-added/"..key, {source = self, item = value});
330 function api:remove_item(key, value)
331 local t = self.items and self.items[key] or NULL;
333 if t[i] == value then
334 t_remove(self.items[key], i);
335 self:fire_event("item-removed/"..key, {source = self, item = value});
341 function api:get_host_items(key)
342 local modulemanager = require"core.modulemanager";
343 local result = modulemanager.get_items(key, self.host) or {};
347 function api:handle_items(item_type, added_cb, removed_cb, existing)
348 self:hook("item-added/"..item_type, added_cb);
349 self:hook("item-removed/"..item_type, removed_cb);
350 if existing ~= false then
351 for _, item in ipairs(self:get_host_items(item_type)) do
352 added_cb({ item = item });
357 function api:provides(name, item)
358 -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
361 for k,v in pairs(self.environment) do
362 if k ~= "module" then item[k] = v; end
365 if not item.name then
366 local item_name = self.name;
367 -- Strip a provider prefix to find the item name
368 -- (e.g. "auth_foo" -> "foo" for an auth provider)
369 if item_name:find(name.."_", 1, true) == 1 then
370 item_name = item_name:sub(#name+2);
372 item.name = item_name;
374 item._provided_by = self.name;
375 self:add_item(name.."-provider", item);
378 function api:send(stanza, origin)
379 return core_post_stanza(origin or hosts[self.host], stanza);
382 function api:broadcast(jids, stanza, iter)
383 for jid in (iter or it.values)(jids) do
384 local new_stanza = st.clone(stanza);
385 new_stanza.attr.to = jid;
386 core_post_stanza(hosts[self.host], new_stanza);
390 local timer_methods = { }
392 __index = timer_methods;
394 function timer_methods:stop( )
397 timer_methods.disarm = timer_methods.stop
398 function timer_methods:reschedule(delay)
399 timer.reschedule(self.id, delay)
402 local function timer_callback(now, id, t) --luacheck: ignore 212/id
403 if t.module_env.loaded == false then return; end
404 return t.callback(now, unpack(t, 1, t.n));
407 function api:add_timer(delay, callback, ...)
410 t.callback = callback;
411 t.id = timer.add_task(delay, timer_callback, t);
412 return setmetatable(t, timer_mt);
415 local path_sep = package.config:sub(1,1);
416 function api:get_directory()
417 return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
420 function api:load_resource(path, mode)
421 path = resolve_relative_path(self:get_directory(), path);
422 return io.open(path, mode);
425 function api:open_store(name, store_type)
426 return require"core.storagemanager".open(self.host, name or self.name, store_type);
429 function api:measure(name, stat_type)
430 return measure(stat_type, "/"..self.host.."/mod_"..self.name.."/"..name);
433 function api:measure_object_event(events_object, event_name, stat_name)
434 local m = self:measure(stat_name or event_name, "duration");
435 local function handler(handlers, _event_name, _event_data)
436 local finished = m();
437 local ret = handlers(_event_name, _event_data);
441 return self:hook_object_event(events_object, event_name, handler);
444 function api:measure_event(event_name, stat_name)
445 return self:measure_object_event((hosts[self.host] or prosody).events.wrappers, event_name, stat_name);
448 function api:measure_global_event(event_name, stat_name)
449 return self:measure_object_event(prosody.events.wrappers, event_name, stat_name);