7a4d1fa6dcacd3930ec8a29bb256855e3e175374
[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 modulemanager = require "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
16 local multitable_new = require "util.multitable".new;
17
18 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
19 local error, setmetatable, setfenv, type = error, setmetatable, setfenv, type;
20 local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
21 local tonumber, tostring = tonumber, tostring;
22
23 local prosody = prosody;
24 local hosts = prosody.hosts;
25
26 -- Registry of shared module data
27 local shared_data = setmetatable({}, { __mode = "v" });
28
29 local NULL = {};
30
31 local api = {};
32
33 -- Returns the name of the current module
34 function api:get_name()
35         return self.name;
36 end
37
38 -- Returns the host that the current module is serving
39 function api:get_host()
40         return self.host;
41 end
42
43 function api:get_host_type()
44         return hosts[self.host].type;
45 end
46
47 function api:set_global()
48         self.host = "*";
49         -- Update the logger
50         local _log = logger.init("mod_"..self.name);
51         self.log = function (self, ...) return _log(...); end;
52         self._log = _log;
53 end
54
55 function api:add_feature(xmlns)
56         self:add_item("feature", xmlns);
57 end
58 function api:add_identity(category, type, name)
59         self:add_item("identity", {category = category, type = type, name = name});
60 end
61 function api:add_extension(data)
62         self:add_item("extension", data);
63 end
64
65 function api:fire_event(...)
66         return (hosts[self.host] or prosody).events.fire_event(...);
67 end
68
69 function api:hook_object_event(object, event, handler, priority)
70         self.event_handlers[handler] = { name = event, priority = priority, object = object };
71         return object.add_handler(event, handler, priority);
72 end
73
74 function api:hook(event, handler, priority)
75         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
76 end
77
78 function api:hook_global(event, handler, priority)
79         return self:hook_object_event(prosody.events, event, handler, priority);
80 end
81
82 function api:hook_stanza(xmlns, name, handler, priority)
83         if not handler and type(name) == "function" then
84                 -- If only 2 options then they specified no xmlns
85                 xmlns, name, handler, priority = nil, xmlns, name, handler;
86         elseif not (handler and name) then
87                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
88                 return;
89         end
90         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
91 end
92
93 function api:require(lib)
94         local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
95         if not f then
96                 f, n = pluginloader.load_code(lib, lib..".lib.lua");
97         end
98         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
99         setfenv(f, self.environment);
100         return f();
101 end
102
103 function api:depends(name)
104         if not self.dependencies then
105                 self.dependencies = {};
106                 self:hook("module-reloaded", function (event)
107                         if self.dependencies[event.module] then
108                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
109                                 modulemanager.reload(self.host, self.name);
110                                 return;
111                         end
112                 end);
113                 self:hook("module-unloaded", function (event)
114                         if self.dependencies[event.module] then
115                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
116                                 modulemanager.unload(self.host, self.name);
117                         end
118                 end);
119         end
120         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
121         if not mod then
122                 local err;
123                 mod, err = modulemanager.load(self.host, name);
124                 if not mod then
125                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
126                 end
127         end
128         self.dependencies[name] = true;
129         return mod;
130 end
131
132 -- Returns one or more shared tables at the specified virtual paths
133 -- Intentionally does not allow the table at a path to be _set_, it
134 -- is auto-created if it does not exist.
135 function api:shared(...)
136         local paths = { n = select("#", ...), ... };
137         local data_array = {};
138         local default_path_components = { self.host, self.name };
139         for i = 1, paths.n do
140                 local path = paths[i];
141                 if path:sub(1,1) ~= "/" then -- Prepend default components
142                         local n_components = select(2, path:gsub("/", "%1"));
143                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
144                 end
145                 local shared = shared_data[path];
146                 if not shared then
147                         shared = {};
148                         shared_data[path] = shared;
149                 end
150                 t_insert(data_array, shared);
151         end
152         return unpack(data_array);
153 end
154
155 function api:get_option(name, default_value)
156         local value = config.get(self.host, self.name, name);
157         if value == nil then
158                 value = config.get(self.host, "core", name);
159                 if value == nil then
160                         value = default_value;
161                 end
162         end
163         return value;
164 end
165
166 function api:get_option_string(name, default_value)
167         local value = self:get_option(name, default_value);
168         if type(value) == "table" then
169                 if #value > 1 then
170                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
171                 end
172                 value = value[1];
173         end
174         if value == nil then
175                 return nil;
176         end
177         return tostring(value);
178 end
179
180 function api:get_option_number(name, ...)
181         local value = self:get_option(name, ...);
182         if type(value) == "table" then
183                 if #value > 1 then
184                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
185                 end
186                 value = value[1];
187         end
188         local ret = tonumber(value);
189         if value ~= nil and ret == nil then
190                 self:log("error", "Config option '%s' not understood, expecting a number", name);
191         end
192         return ret;
193 end
194
195 function api:get_option_boolean(name, ...)
196         local value = self:get_option(name, ...);
197         if type(value) == "table" then
198                 if #value > 1 then
199                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
200                 end
201                 value = value[1];
202         end
203         if value == nil then
204                 return nil;
205         end
206         local ret = value == true or value == "true" or value == 1 or nil;
207         if ret == nil then
208                 ret = (value == false or value == "false" or value == 0);
209                 if ret then
210                         ret = false;
211                 else
212                         ret = nil;
213                 end
214         end
215         if ret == nil then
216                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
217         end
218         return ret;
219 end
220
221 function api:get_option_array(name, ...)
222         local value = self:get_option(name, ...);
223
224         if value == nil then
225                 return nil;
226         end
227         
228         if type(value) ~= "table" then
229                 return array{ value }; -- Assume any non-list is a single-item list
230         end
231         
232         return array():append(value); -- Clone
233 end
234
235 function api:get_option_set(name, ...)
236         local value = self:get_option_array(name, ...);
237         
238         if value == nil then
239                 return nil;
240         end
241         
242         return set.new(value);
243 end
244
245 local module_items = multitable_new();
246 function api:add_item(key, value)
247         self.items = self.items or {};
248         self.items[key] = self.items[key] or {};
249         t_insert(self.items[key], value);
250         self:fire_event("item-added/"..key, {source = self, item = value});
251 end
252 function api:remove_item(key, value)
253         local t = self.items and self.items[key] or NULL;
254         for i = #t,1,-1 do
255                 if t[i] == value then
256                         t_remove(self.items[key], i);
257                         self:fire_event("item-removed/"..key, {source = self, item = value});
258                         return value;
259                 end
260         end
261 end
262
263 function api:get_host_items(key)
264         local result = {};
265         for mod_name, module in pairs(modulemanager.get_modules(self.host)) do
266                 module = module.module;
267                 if module.items then
268                         for _, item in ipairs(module.items[key] or NULL) do
269                                 t_insert(result, item);
270                         end
271                 end
272         end
273         for mod_name, module in pairs(modulemanager.get_modules("*")) do
274                 module = module.module;
275                 if module.items then
276                         for _, item in ipairs(module.items[key] or NULL) do
277                                 t_insert(result, item);
278                         end
279                 end
280         end
281         return result;
282 end
283
284 function api:handle_items(type, added_cb, removed_cb, existing)
285         self:hook("item-added/"..type, added_cb);
286         self:hook("item-removed/"..type, removed_cb);
287         if existing ~= false then
288                 for _, item in ipairs(self:get_host_items(type)) do
289                         added_cb({ item = item });
290                 end
291         end
292 end
293
294 return api;