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";
16 local resolve_relative_path = require"util.paths".resolve_relative_path;
18 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
19 local error, setmetatable, type = error, setmetatable, type;
20 local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
21 local tonumber, tostring = tonumber, tostring;
23 local prosody = prosody;
24 local hosts = prosody.hosts;
26 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
27 local core_post_stanza = assert(prosody.core_post_stanza,
28 "prosody.core_post_stanza is nil, please report this as a bug");
30 -- Registry of shared module data
31 local shared_data = setmetatable({}, { __mode = "v" });
37 -- Returns the name of the current module
38 function api:get_name()
42 -- Returns the host that the current module is serving
43 function api:get_host()
47 function api:get_host_type()
48 return (self.host == "*" and "global") or hosts[self.host].type or "local";
51 function api:set_global()
54 local _log = logger.init("mod_"..self.name);
55 self.log = function (self, ...) return _log(...); end;
60 function api:add_feature(xmlns)
61 self:add_item("feature", xmlns);
63 function api:add_identity(category, type, name)
64 self:add_item("identity", {category = category, type = type, name = name});
66 function api:add_extension(data)
67 self:add_item("extension", data);
69 function api:has_feature(xmlns)
70 for _, feature in ipairs(self:get_host_items("feature")) do
71 if feature == xmlns then return true; end
75 function api:has_identity(category, type, name)
76 for _, id in ipairs(self:get_host_items("identity")) do
77 if id.category == category and id.type == type and id.name == name then
84 function api:fire_event(...)
85 return (hosts[self.host] or prosody).events.fire_event(...);
88 function api:hook_object_event(object, event, handler, priority)
89 self.event_handlers:set(object, event, handler, true);
90 return object.add_handler(event, handler, priority);
93 function api:unhook_object_event(object, event, handler)
94 return object.remove_handler(event, handler);
97 function api:hook(event, handler, priority)
98 return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
101 function api:hook_global(event, handler, priority)
102 return self:hook_object_event(prosody.events, event, handler, priority);
105 function api:hook_tag(xmlns, name, handler, priority)
106 if not handler and type(name) == "function" then
107 -- If only 2 options then they specified no xmlns
108 xmlns, name, handler, priority = nil, xmlns, name, handler;
109 elseif not (handler and name) then
110 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
113 return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
115 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
117 function api:unhook(event, handler)
118 return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
121 function api:require(lib)
122 local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
124 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
126 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
130 function api:depends(name)
131 if not self.dependencies then
132 self.dependencies = {};
133 self:hook("module-reloaded", function (event)
134 if self.dependencies[event.module] and not self.reloading then
135 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
136 modulemanager.reload(self.host, self.name);
140 self:hook("module-unloaded", function (event)
141 if self.dependencies[event.module] then
142 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
143 modulemanager.unload(self.host, self.name);
147 local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
148 if mod and mod.module.host == "*" and self.host ~= "*"
149 and modulemanager.module_has_method(mod, "add_host") then
150 mod = nil; -- Target is a shared module, so we still want to load it on our host
154 mod, err = modulemanager.load(self.host, name);
156 return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
159 self.dependencies[name] = true;
163 -- Returns one or more shared tables at the specified virtual paths
164 -- Intentionally does not allow the table at a path to be _set_, it
165 -- is auto-created if it does not exist.
166 function api:shared(...)
167 if not self.shared_data then self.shared_data = {}; end
168 local paths = { n = select("#", ...), ... };
169 local data_array = {};
170 local default_path_components = { self.host, self.name };
171 for i = 1, paths.n do
172 local path = paths[i];
173 if path:sub(1,1) ~= "/" then -- Prepend default components
174 local n_components = select(2, path:gsub("/", "%1"));
175 path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
177 local shared = shared_data[path];
180 if path:match("%-cache$") then
181 setmetatable(shared, { __mode = "kv" });
183 shared_data[path] = shared;
185 t_insert(data_array, shared);
186 self.shared_data[path] = shared;
188 return unpack(data_array);
191 function api:get_option(name, default_value)
192 local value = config.get(self.host, name);
194 value = default_value;
199 function api:get_option_string(name, default_value)
200 local value = self:get_option(name, default_value);
201 if type(value) == "table" then
203 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
210 return tostring(value);
213 function api:get_option_number(name, ...)
214 local value = self:get_option(name, ...);
215 if type(value) == "table" then
217 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
221 local ret = tonumber(value);
222 if value ~= nil and ret == nil then
223 self:log("error", "Config option '%s' not understood, expecting a number", name);
228 function api:get_option_boolean(name, ...)
229 local value = self:get_option(name, ...);
230 if type(value) == "table" then
232 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
239 local ret = value == true or value == "true" or value == 1 or nil;
241 ret = (value == false or value == "false" or value == 0);
249 self:log("error", "Config option '%s' not understood, expecting true/false", name);
254 function api:get_option_array(name, ...)
255 local value = self:get_option(name, ...);
261 if type(value) ~= "table" then
262 return array{ value }; -- Assume any non-list is a single-item list
265 return array():append(value); -- Clone
268 function api:get_option_set(name, ...)
269 local value = self:get_option_array(name, ...);
275 return set.new(value);
278 function api:get_option_inherited_set(name, ...)
279 local value = self:get_option_set(name, ...);
280 local global_value = self:context("*"):get_option_set(name, ...);
283 elseif not global_value then
286 value:include(global_value);
290 function api:context(host)
291 return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
294 function api:add_item(key, value)
295 self.items = self.items or {};
296 self.items[key] = self.items[key] or {};
297 t_insert(self.items[key], value);
298 self:fire_event("item-added/"..key, {source = self, item = value});
300 function api:remove_item(key, value)
301 local t = self.items and self.items[key] or NULL;
303 if t[i] == value then
304 t_remove(self.items[key], i);
305 self:fire_event("item-removed/"..key, {source = self, item = value});
311 function api:get_host_items(key)
312 local result = modulemanager.get_items(key, self.host) or {};
316 function api:handle_items(type, added_cb, removed_cb, existing)
317 self:hook("item-added/"..type, added_cb);
318 self:hook("item-removed/"..type, removed_cb);
319 if existing ~= false then
320 for _, item in ipairs(self:get_host_items(type)) do
321 added_cb({ item = item });
326 function api:provides(name, item)
327 -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
330 for k,v in pairs(self.environment) do
331 if k ~= "module" then item[k] = v; end
334 if not item.name then
335 local item_name = self.name;
336 -- Strip a provider prefix to find the item name
337 -- (e.g. "auth_foo" -> "foo" for an auth provider)
338 if item_name:find(name.."_", 1, true) == 1 then
339 item_name = item_name:sub(#name+2);
341 item.name = item_name;
343 item._provided_by = self.name;
344 self:add_item(name.."-provider", item);
347 function api:send(stanza)
348 return core_post_stanza(hosts[self.host], stanza);
351 function api:add_timer(delay, callback)
352 return timer.add_task(delay, function (t)
353 if self.loaded == false then return; end
358 local path_sep = package.config:sub(1,1);
359 function api:get_directory()
360 return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
363 function api:load_resource(path, mode)
364 path = resolve_relative_path(self:get_directory(), path);
365 return io.open(path, mode);
368 function api:open_store(name, type)
369 return storagemanager.open(self.host, name or self.name, type);