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 = 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";
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;
22 local prosody = prosody;
23 local hosts = prosody.hosts;
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");
29 -- Registry of shared module data
30 local shared_data = setmetatable({}, { __mode = "v" });
36 -- Returns the name of the current module
37 function api:get_name()
41 -- Returns the host that the current module is serving
42 function api:get_host()
46 function api:get_host_type()
47 return (self.host == "*" and "global") or hosts[self.host].type or "local";
50 function api:set_global()
53 local _log = logger.init("mod_"..self.name);
54 self.log = function (self, ...) return _log(...); end;
59 function api:add_feature(xmlns)
60 self:add_item("feature", xmlns);
62 function api:add_identity(category, type, name)
63 self:add_item("identity", {category = category, type = type, name = name});
65 function api:add_extension(data)
66 self:add_item("extension", data);
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
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
83 function api:fire_event(...)
84 return (hosts[self.host] or prosody).events.fire_event(...);
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);
92 function api:unhook_object_event(object, event, handler)
93 return object.remove_handler(event, handler);
96 function api:hook(event, handler, priority)
97 return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
100 function api:hook_global(event, handler, priority)
101 return self:hook_object_event(prosody.events, event, handler, priority);
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()");
112 return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
114 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
116 function api:unhook(event, handler)
117 return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
120 function api:require(lib)
121 local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
123 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
125 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
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);
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);
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
153 mod, err = modulemanager.load(self.host, name);
155 return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
158 self.dependencies[name] = true;
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;
176 local shared = shared_data[path];
179 if path:match("%-cache$") then
180 setmetatable(shared, { __mode = "kv" });
182 shared_data[path] = shared;
184 t_insert(data_array, shared);
185 self.shared_data[path] = shared;
187 return unpack(data_array);
190 function api:get_option(name, default_value)
191 local value = config.get(self.host, name);
193 value = default_value;
198 function api:get_option_string(name, default_value)
199 local value = self:get_option(name, default_value);
200 if type(value) == "table" then
202 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
209 return tostring(value);
212 function api:get_option_number(name, ...)
213 local value = self:get_option(name, ...);
214 if type(value) == "table" then
216 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
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);
227 function api:get_option_boolean(name, ...)
228 local value = self:get_option(name, ...);
229 if type(value) == "table" then
231 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
238 local ret = value == true or value == "true" or value == 1 or nil;
240 ret = (value == false or value == "false" or value == 0);
248 self:log("error", "Config option '%s' not understood, expecting true/false", name);
253 function api:get_option_array(name, ...)
254 local value = self:get_option(name, ...);
260 if type(value) ~= "table" then
261 return array{ value }; -- Assume any non-list is a single-item list
264 return array():append(value); -- Clone
267 function api:get_option_set(name, ...)
268 local value = self:get_option_array(name, ...);
274 return set.new(value);
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, ...);
282 elseif not global_value then
285 value:include(global_value);
289 function api:context(host)
290 return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
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});
299 function api:remove_item(key, value)
300 local t = self.items and self.items[key] or NULL;
302 if t[i] == value then
303 t_remove(self.items[key], i);
304 self:fire_event("item-removed/"..key, {source = self, item = value});
310 function api:get_host_items(key)
311 local result = modulemanager.get_items(key, self.host) or {};
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 });
325 function api:provides(name, item)
326 -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
329 for k,v in pairs(self.environment) do
330 if k ~= "module" then item[k] = v; 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);
340 item.name = item_name;
342 item._provided_by = self.name;
343 self:add_item(name.."-provider", item);
346 function api:send(stanza)
347 return core_post_stanza(hosts[self.host], stanza);
350 function api:add_timer(delay, callback)
351 return timer.add_task(delay, function (t)
352 if self.loaded == false then return; end
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;
362 function api:load_resource(path, mode)
363 path = config.resolve_relative_path(self:get_directory(), path);
364 return io.open(path, mode);
367 function api:open_store(name, type)
368 return storagemanager.open(self.host, name or self.name, type);