Topicbar usability improvements
[KiwiIRC.git] / server / lib / kiwi_mod.js
1 /*jslint node: true, sloppy: true, forin: true, maxerr: 50, indent: 4 */
2 /*
3 * Kiwi module handler
4 *
5 * To run module events:
6 * kiwi_mod.run(event_name, obj);
7 *
8 * - Each module call must return obj, with or without changes.
9 * - If a module call returns null, the event is considered cancelled
10 * and null is passed back to the caller to take action.
11 * For example, if null is returned for onmsg, kiwi stops sending
12 * the message to any clients.
13 */
14
15 var kiwi = require('../kiwi.js');
16 var fs = require('fs');
17 this.loaded_modules = {};
18
19
20 /*
21 * Load any unloaded modules as set in config
22 */
23 exports.loadModules = function (kiwi_root, config) {
24 var i, mod_name;
25 // Warn each module it is about to be unloaded
26 //this.run('unload');
27 //this.loaded_modules = {};
28
29 // Load each module and run the onload event
30 for (i in kiwi.config.modules) {
31 mod_name = kiwi.config.modules[i];
32 if (typeof this.loaded_modules[mod_name] !== 'undefined') continue;
33
34 this.loaded_modules[mod_name] = require(kiwi.kiwi_root + '/' + kiwi.config.module_dir + mod_name);
35 }
36 this.run('load');
37 };
38
39
40 /*
41 * Unload and reload a specific module
42 */
43 exports.reloadModule = function (mod_name) {
44 fs.realpath(kiwi.kiwi_root + '/' + kiwi.config.module_dir + mod_name + '.js', function(err, resolvedPath){
45 try {
46 var mod_path = resolvedPath;
47
48 if (typeof kiwi.kiwi_mod.loaded_modules[mod_name] !== 'undefined') {
49 delete kiwi.kiwi_mod.loaded_modules[mod_name];
50 }
51 if (typeof require.cache[mod_path] !== 'undefined') {
52 delete require.cache[mod_path];
53 }
54
55 kiwi.kiwi_mod.loaded_modules[mod_name] = null;
56 kiwi.kiwi_mod.loaded_modules[mod_name] = require(mod_path);
57
58 kiwi.log('Module ' + mod_name + ' reloaded.');
59 } catch (e) {
60 kiwi.log('reloadModule error!');
61 kiwi.log(e);
62 return false;
63 }
64 });
65
66 //return this.loaded_modules[mod_name] ? true : false;
67 };
68
69
70 /*
71 * Run an event against all loaded modules
72 */
73 exports.run = function (event_name, event_data, opts) {
74 var ret = event_data,
75 ret_tmp, mod_name;
76
77 event_data = (typeof event_data === 'undefined') ? {} : event_data;
78 opts = (typeof opts === 'undefined') ? {} : opts;
79
80 for (mod_name in this.loaded_modules) {
81 if (typeof this.loaded_modules[mod_name]['on' + event_name] === 'function') {
82 try {
83 ret_tmp = this.loaded_modules[mod_name]['on' + event_name](ret, opts);
84 if (ret_tmp === null) {
85 return null;
86 }
87 ret = ret_tmp;
88 } catch (e) {
89 }
90 }
91 }
92
93 return ret;
94 };
95
96 exports.printMods = function () {
97 var mod_name;
98 kiwi.log('Loaded Kiwi modules:');
99 for (mod_name in this.loaded_modules) {
100 kiwi.log(' - ' + mod_name);
101 }
102 };