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 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 local measure = require "core.statsmanager".measure;
19 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
20 local error, setmetatable, type = error, setmetatable, type;
21 local ipairs, pairs, select = ipairs, pairs, select;
22 local tonumber, tostring = tonumber, tostring;
23 local require = require;
24 local pack = table.pack or function(...) return {n=select("#",...), ...}; end -- table.pack is only in 5.2
25 local unpack = table.unpack or unpack; -- renamed in 5.2
27 local prosody = prosody;
28 local hosts = prosody.hosts;
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");
34 -- Registry of shared module data
35 local shared_data = setmetatable({}, { __mode = "v" });
41 -- Returns the name of the current module
42 function api:get_name()
46 -- Returns the host that the current module is serving
47 function api:get_host()
51 function api:get_host_type()
52 return (self.host == "*" and "global") or hosts[self.host].type or "local";
55 function api:set_global()
58 local _log = logger.init("mod_"..self.name);
59 self.log = function (self, ...) return _log(...); end;
64 function api:add_feature(xmlns)
65 self:add_item("feature", xmlns);
67 function api:add_identity(category, type, name)
68 self:add_item("identity", {category = category, type = type, name = name});
70 function api:add_extension(data)
71 self:add_item("extension", data);
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
79 function api:has_identity(category, type, name)
80 for _, id in ipairs(self:get_host_items("identity")) do
81 if id.category == category and id.type == type and id.name == name then
88 function api:fire_event(...)
89 return (hosts[self.host] or prosody).events.fire_event(...);
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);
97 function api:unhook_object_event(object, event, handler)
98 return object.remove_handler(event, handler);
101 function api:hook(event, handler, priority)
102 return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
105 function api:hook_global(event, handler, priority)
106 return self:hook_object_event(prosody.events, event, handler, priority);
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()");
117 return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
119 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
121 function api:unhook(event, handler)
122 return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
125 function api:require(lib)
126 local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
128 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
130 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
134 function api:depends(name)
135 if not self.dependencies then
136 self.dependencies = {};
137 self:hook("module-reloaded", function (event)
138 if self.dependencies[event.module] and not self.reloading then
139 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
140 modulemanager.reload(self.host, self.name);
144 self:hook("module-unloaded", function (event)
145 if self.dependencies[event.module] then
146 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
147 modulemanager.unload(self.host, self.name);
151 local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
152 if mod and mod.module.host == "*" and self.host ~= "*"
153 and modulemanager.module_has_method(mod, "add_host") then
154 mod = nil; -- Target is a shared module, so we still want to load it on our host
158 mod, err = modulemanager.load(self.host, name);
160 return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
163 self.dependencies[name] = true;
167 -- Returns one or more shared tables at the specified virtual paths
168 -- Intentionally does not allow the table at a path to be _set_, it
169 -- is auto-created if it does not exist.
170 function api:shared(...)
171 if not self.shared_data then self.shared_data = {}; end
172 local paths = { n = select("#", ...), ... };
173 local data_array = {};
174 local default_path_components = { self.host, self.name };
175 for i = 1, paths.n do
176 local path = paths[i];
177 if path:sub(1,1) ~= "/" then -- Prepend default components
178 local n_components = select(2, path:gsub("/", "%1"));
179 path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
181 local shared = shared_data[path];
184 if path:match("%-cache$") then
185 setmetatable(shared, { __mode = "kv" });
187 shared_data[path] = shared;
189 t_insert(data_array, shared);
190 self.shared_data[path] = shared;
192 return unpack(data_array);
195 function api:get_option(name, default_value)
196 local value = config.get(self.host, name);
198 value = default_value;
203 function api:get_option_string(name, default_value)
204 local value = self:get_option(name, default_value);
205 if type(value) == "table" then
207 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
214 return tostring(value);
217 function api:get_option_number(name, ...)
218 local value = self:get_option(name, ...);
219 if type(value) == "table" then
221 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
225 local ret = tonumber(value);
226 if value ~= nil and ret == nil then
227 self:log("error", "Config option '%s' not understood, expecting a number", name);
232 function api:get_option_boolean(name, ...)
233 local value = self:get_option(name, ...);
234 if type(value) == "table" then
236 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
243 local ret = value == true or value == "true" or value == 1 or nil;
245 ret = (value == false or value == "false" or value == 0);
253 self:log("error", "Config option '%s' not understood, expecting true/false", name);
258 function api:get_option_array(name, ...)
259 local value = self:get_option(name, ...);
265 if type(value) ~= "table" then
266 return array{ value }; -- Assume any non-list is a single-item list
269 return array():append(value); -- Clone
272 function api:get_option_set(name, ...)
273 local value = self:get_option_array(name, ...);
279 return set.new(value);
282 function api:get_option_inherited_set(name, ...)
283 local value = self:get_option_set(name, ...);
284 local global_value = self:context("*"):get_option_set(name, ...);
287 elseif not global_value then
290 value:include(global_value);
294 function api:context(host)
295 return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
298 function api:add_item(key, value)
299 self.items = self.items or {};
300 self.items[key] = self.items[key] or {};
301 t_insert(self.items[key], value);
302 self:fire_event("item-added/"..key, {source = self, item = value});
304 function api:remove_item(key, value)
305 local t = self.items and self.items[key] or NULL;
307 if t[i] == value then
308 t_remove(self.items[key], i);
309 self:fire_event("item-removed/"..key, {source = self, item = value});
315 function api:get_host_items(key)
316 local result = modulemanager.get_items(key, self.host) or {};
320 function api:handle_items(type, added_cb, removed_cb, existing)
321 self:hook("item-added/"..type, added_cb);
322 self:hook("item-removed/"..type, removed_cb);
323 if existing ~= false then
324 for _, item in ipairs(self:get_host_items(type)) do
325 added_cb({ item = item });
330 function api:provides(name, item)
331 -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
334 for k,v in pairs(self.environment) do
335 if k ~= "module" then item[k] = v; end
338 if not item.name then
339 local item_name = self.name;
340 -- Strip a provider prefix to find the item name
341 -- (e.g. "auth_foo" -> "foo" for an auth provider)
342 if item_name:find(name.."_", 1, true) == 1 then
343 item_name = item_name:sub(#name+2);
345 item.name = item_name;
347 item._provided_by = self.name;
348 self:add_item(name.."-provider", item);
351 function api:send(stanza)
352 return core_post_stanza(hosts[self.host], stanza);
355 local timer_methods = { }
357 __index = timer_methods;
359 function timer_methods:stop( )
362 timer_methods.disarm = timer_methods.stop
363 function timer_methods:reschedule(delay)
364 timer.reschedule(self.id, delay)
367 local function timer_callback(now, id, t)
368 if t.module_env.loaded == false then return; end
369 return t.callback(now, unpack(t, 1, t.n));
372 function api:add_timer(delay, callback, ...)
375 t.callback = callback;
376 t.id = timer.add_task(delay, timer_callback, t);
377 return setmetatable(t, timer_mt);
380 local path_sep = package.config:sub(1,1);
381 function api:get_directory()
382 return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
385 function api:load_resource(path, mode)
386 path = resolve_relative_path(self:get_directory(), path);
387 return io.open(path, mode);
390 function api:open_store(name, type)
391 return require"core.storagemanager".open(self.host, name or self.name, type);
394 function api:measure(name, type)
395 return measure(type, "/"..self.host.."/mod_"..self.name.."/"..name);
398 function api.init(mm)