Merge 0.9->0.10
[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"; -- 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;
17
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;
22
23 local prosody = prosody;
24 local hosts = prosody.hosts;
25
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");
29
30 -- Registry of shared module data
31 local shared_data = setmetatable({}, { __mode = "v" });
32
33 local NULL = {};
34
35 local api = {};
36
37 -- Returns the name of the current module
38 function api:get_name()
39         return self.name;
40 end
41
42 -- Returns the host that the current module is serving
43 function api:get_host()
44         return self.host;
45 end
46
47 function api:get_host_type()
48         return (self.host == "*" and "global") or hosts[self.host].type or "local";
49 end
50
51 function api:set_global()
52         self.host = "*";
53         -- Update the logger
54         local _log = logger.init("mod_"..self.name);
55         self.log = function (self, ...) return _log(...); end;
56         self._log = _log;
57         self.global = true;
58 end
59
60 function api:add_feature(xmlns)
61         self:add_item("feature", xmlns);
62 end
63 function api:add_identity(category, type, name)
64         self:add_item("identity", {category = category, type = type, name = name});
65 end
66 function api:add_extension(data)
67         self:add_item("extension", data);
68 end
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
72         end
73         return false;
74 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
78                         return true;
79                 end
80         end
81         return false;
82 end
83
84 function api:fire_event(...)
85         return (hosts[self.host] or prosody).events.fire_event(...);
86 end
87
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);
91 end
92
93 function api:unhook_object_event(object, event, handler)
94         return object.remove_handler(event, handler);
95 end
96
97 function api:hook(event, handler, priority)
98         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
99 end
100
101 function api:hook_global(event, handler, priority)
102         return self:hook_object_event(prosody.events, event, handler, priority);
103 end
104
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()");
111                 return;
112         end
113         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
114 end
115 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
116
117 function api:unhook(event, handler)
118         return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
119 end
120
121 function api:require(lib)
122         local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
123         if not f then
124                 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
125         end
126         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
127         return f();
128 end
129
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);
137                                 return;
138                         end
139                 end);
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);
144                         end
145                 end);
146         end
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
151         end
152         if not mod then
153                 local err;
154                 mod, err = modulemanager.load(self.host, name);
155                 if not mod then
156                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
157                 end
158         end
159         self.dependencies[name] = true;
160         return mod;
161 end
162
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;
176                 end
177                 local shared = shared_data[path];
178                 if not shared then
179                         shared = {};
180                         if path:match("%-cache$") then
181                                 setmetatable(shared, { __mode = "kv" });
182                         end
183                         shared_data[path] = shared;
184                 end
185                 t_insert(data_array, shared);
186                 self.shared_data[path] = shared;
187         end
188         return unpack(data_array);
189 end
190
191 function api:get_option(name, default_value)
192         local value = config.get(self.host, name);
193         if value == nil then
194                 value = default_value;
195         end
196         return value;
197 end
198
199 function api:get_option_string(name, default_value)
200         local value = self:get_option(name, default_value);
201         if type(value) == "table" then
202                 if #value > 1 then
203                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
204                 end
205                 value = value[1];
206         end
207         if value == nil then
208                 return nil;
209         end
210         return tostring(value);
211 end
212
213 function api:get_option_number(name, ...)
214         local value = self:get_option(name, ...);
215         if type(value) == "table" then
216                 if #value > 1 then
217                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
218                 end
219                 value = value[1];
220         end
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);
224         end
225         return ret;
226 end
227
228 function api:get_option_boolean(name, ...)
229         local value = self:get_option(name, ...);
230         if type(value) == "table" then
231                 if #value > 1 then
232                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
233                 end
234                 value = value[1];
235         end
236         if value == nil then
237                 return nil;
238         end
239         local ret = value == true or value == "true" or value == 1 or nil;
240         if ret == nil then
241                 ret = (value == false or value == "false" or value == 0);
242                 if ret then
243                         ret = false;
244                 else
245                         ret = nil;
246                 end
247         end
248         if ret == nil then
249                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
250         end
251         return ret;
252 end
253
254 function api:get_option_array(name, ...)
255         local value = self:get_option(name, ...);
256
257         if value == nil then
258                 return nil;
259         end
260
261         if type(value) ~= "table" then
262                 return array{ value }; -- Assume any non-list is a single-item list
263         end
264
265         return array():append(value); -- Clone
266 end
267
268 function api:get_option_set(name, ...)
269         local value = self:get_option_array(name, ...);
270
271         if value == nil then
272                 return nil;
273         end
274
275         return set.new(value);
276 end
277
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, ...);
281         if not value then
282                 return global_value;
283         elseif not global_value then
284                 return value;
285         end
286         value:include(global_value);
287         return value;
288 end
289
290 function api:context(host)
291         return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
292 end
293
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});
299 end
300 function api:remove_item(key, value)
301         local t = self.items and self.items[key] or NULL;
302         for i = #t,1,-1 do
303                 if t[i] == value then
304                         t_remove(self.items[key], i);
305                         self:fire_event("item-removed/"..key, {source = self, item = value});
306                         return value;
307                 end
308         end
309 end
310
311 function api:get_host_items(key)
312         local result = modulemanager.get_items(key, self.host) or {};
313         return result;
314 end
315
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 });
322                 end
323         end
324 end
325
326 function api:provides(name, item)
327         -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
328         if not item then
329                 item = {}
330                 for k,v in pairs(self.environment) do
331                         if k ~= "module" then item[k] = v; end
332                 end
333         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);
340                 end
341                 item.name = item_name;
342         end
343         item._provided_by = self.name;
344         self:add_item(name.."-provider", item);
345 end
346
347 function api:send(stanza)
348         return core_post_stanza(hosts[self.host], stanza);
349 end
350
351 function api:add_timer(delay, callback)
352         return timer.add_task(delay, function (t)
353                 if self.loaded == false then return; end
354                 return callback(t);
355         end);
356 end
357
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;
361 end
362
363 function api:load_resource(path, mode)
364         path = resolve_relative_path(self:get_directory(), path);
365         return io.open(path, mode);
366 end
367
368 function api:open_store(name, type)
369         return storagemanager.open(self.host, name or self.name, type);
370 end
371
372 return api;