mod_storage_none: A null-like storage provider that returns all stores as empty,...
[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
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;
21
22 local prosody = prosody;
23 local hosts = prosody.hosts;
24 local core_post_stanza = prosody.core_post_stanza;
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 self.host ~= "*" and hosts[self.host].type or nil;
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         self.global = true;
54 end
55
56 function api:add_feature(xmlns)
57         self:add_item("feature", xmlns);
58 end
59 function api:add_identity(category, type, name)
60         self:add_item("identity", {category = category, type = type, name = name});
61 end
62 function api:add_extension(data)
63         self:add_item("extension", data);
64 end
65 function api:has_feature(xmlns)
66         for _, feature in ipairs(self:get_host_items("feature")) do
67                 if feature == xmlns then return true; end
68         end
69         return false;
70 end
71 function api:has_identity(category, type, name)
72         for _, id in ipairs(self:get_host_items("identity")) do
73                 if id.category == category and id.type == type and id.name == name then
74                         return true; 
75                 end
76         end
77         return false;
78 end
79
80 function api:fire_event(...)
81         return (hosts[self.host] or prosody).events.fire_event(...);
82 end
83
84 function api:hook_object_event(object, event, handler, priority)
85         self.event_handlers:set(object, event, handler, true);
86         return object.add_handler(event, handler, priority);
87 end
88
89 function api:unhook_object_event(object, event, handler)
90         return object.remove_handler(event, handler);
91 end
92
93 function api:hook(event, handler, priority)
94         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
95 end
96
97 function api:hook_global(event, handler, priority)
98         return self:hook_object_event(prosody.events, event, handler, priority);
99 end
100
101 function api:hook_tag(xmlns, name, handler, priority)
102         if not handler and type(name) == "function" then
103                 -- If only 2 options then they specified no xmlns
104                 xmlns, name, handler, priority = nil, xmlns, name, handler;
105         elseif not (handler and name) then
106                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
107                 return;
108         end
109         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
110 end
111 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
112
113 function api:require(lib)
114         local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
115         if not f then
116                 f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
117         end
118         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
119         return f();
120 end
121
122 function api:depends(name)
123         if not self.dependencies then
124                 self.dependencies = {};
125                 self:hook("module-reloaded", function (event)
126                         if self.dependencies[event.module] and not self.reloading then
127                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
128                                 modulemanager.reload(self.host, self.name);
129                                 return;
130                         end
131                 end);
132                 self:hook("module-unloaded", function (event)
133                         if self.dependencies[event.module] then
134                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
135                                 modulemanager.unload(self.host, self.name);
136                         end
137                 end);
138         end
139         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
140         if mod and mod.module.host == "*" and self.host ~= "*"
141         and modulemanager.module_has_method(mod, "add_host") then
142                 mod = nil; -- Target is a shared module, so we still want to load it on our host
143         end
144         if not mod then
145                 local err;
146                 mod, err = modulemanager.load(self.host, name);
147                 if not mod then
148                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
149                 end
150         end
151         self.dependencies[name] = true;
152         return mod;
153 end
154
155 -- Returns one or more shared tables at the specified virtual paths
156 -- Intentionally does not allow the table at a path to be _set_, it
157 -- is auto-created if it does not exist.
158 function api:shared(...)
159         if not self.shared_data then self.shared_data = {}; end
160         local paths = { n = select("#", ...), ... };
161         local data_array = {};
162         local default_path_components = { self.host, self.name };
163         for i = 1, paths.n do
164                 local path = paths[i];
165                 if path:sub(1,1) ~= "/" then -- Prepend default components
166                         local n_components = select(2, path:gsub("/", "%1"));
167                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
168                 end
169                 local shared = shared_data[path];
170                 if not shared then
171                         shared = {};
172                         if path:match("%-cache$") then
173                                 setmetatable(shared, { __mode = "kv" });
174                         end
175                         shared_data[path] = shared;
176                 end
177                 t_insert(data_array, shared);
178                 self.shared_data[path] = shared;
179         end
180         return unpack(data_array);
181 end
182
183 function api:get_option(name, default_value)
184         local value = config.get(self.host, name);
185         if value == nil then
186                 value = default_value;
187         end
188         return value;
189 end
190
191 function api:get_option_string(name, default_value)
192         local value = self:get_option(name, default_value);
193         if type(value) == "table" then
194                 if #value > 1 then
195                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
196                 end
197                 value = value[1];
198         end
199         if value == nil then
200                 return nil;
201         end
202         return tostring(value);
203 end
204
205 function api:get_option_number(name, ...)
206         local value = self:get_option(name, ...);
207         if type(value) == "table" then
208                 if #value > 1 then
209                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
210                 end
211                 value = value[1];
212         end
213         local ret = tonumber(value);
214         if value ~= nil and ret == nil then
215                 self:log("error", "Config option '%s' not understood, expecting a number", name);
216         end
217         return ret;
218 end
219
220 function api:get_option_boolean(name, ...)
221         local value = self:get_option(name, ...);
222         if type(value) == "table" then
223                 if #value > 1 then
224                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
225                 end
226                 value = value[1];
227         end
228         if value == nil then
229                 return nil;
230         end
231         local ret = value == true or value == "true" or value == 1 or nil;
232         if ret == nil then
233                 ret = (value == false or value == "false" or value == 0);
234                 if ret then
235                         ret = false;
236                 else
237                         ret = nil;
238                 end
239         end
240         if ret == nil then
241                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
242         end
243         return ret;
244 end
245
246 function api:get_option_array(name, ...)
247         local value = self:get_option(name, ...);
248
249         if value == nil then
250                 return nil;
251         end
252         
253         if type(value) ~= "table" then
254                 return array{ value }; -- Assume any non-list is a single-item list
255         end
256         
257         return array():append(value); -- Clone
258 end
259
260 function api:get_option_set(name, ...)
261         local value = self:get_option_array(name, ...);
262         
263         if value == nil then
264                 return nil;
265         end
266         
267         return set.new(value);
268 end
269
270 function api:add_item(key, value)
271         self.items = self.items or {};
272         self.items[key] = self.items[key] or {};
273         t_insert(self.items[key], value);
274         self:fire_event("item-added/"..key, {source = self, item = value});
275 end
276 function api:remove_item(key, value)
277         local t = self.items and self.items[key] or NULL;
278         for i = #t,1,-1 do
279                 if t[i] == value then
280                         t_remove(self.items[key], i);
281                         self:fire_event("item-removed/"..key, {source = self, item = value});
282                         return value;
283                 end
284         end
285 end
286
287 function api:get_host_items(key)
288         local result = modulemanager.get_items(key, self.host) or {};
289         return result;
290 end
291
292 function api:handle_items(type, added_cb, removed_cb, existing)
293         self:hook("item-added/"..type, added_cb);
294         self:hook("item-removed/"..type, removed_cb);
295         if existing ~= false then
296                 for _, item in ipairs(self:get_host_items(type)) do
297                         added_cb({ item = item });
298                 end
299         end
300 end
301
302 function api:provides(name, item)
303         if not item then item = self.environment; end
304         if not item.name then
305                 local item_name = self.name;
306                 -- Strip a provider prefix to find the item name
307                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
308                 if item_name:find(name.."_", 1, true) == 1 then
309                         item_name = item_name:sub(#name+2);
310                 end
311                 item.name = item_name;
312         end
313         self:add_item(name.."-provider", item);
314 end
315
316 function api:send(stanza)
317         return core_post_stanza(hosts[self.host], stanza);
318 end
319
320 function api:add_timer(delay, callback)
321         return timer.add_task(delay, function (t)
322                 if self.loaded == false then return; end
323                 return callback(t);
324         end);
325 end
326
327 local path_sep = package.config:sub(1,1);
328 function api:get_directory()
329         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
330 end
331
332 function api:load_resource(path, mode)
333         path = config.resolve_relative_path(self:get_directory(), path);
334         return io.open(path, mode);
335 end
336
337 return api;