diff --git a/coffee/components-manager.coffee b/coffee/components-manager.coffee index 0c7cc79..717e0e7 100644 --- a/coffee/components-manager.coffee +++ b/coffee/components-manager.coffee @@ -60,8 +60,9 @@ exports.addListener = ( evt, eh ) => # cb ( obj ) where obj should contain at least the HTTP response code and a message exports.processRequest = ( user, obj, cb ) => + console.log obj if commandFunctions[obj.command] - answ = commandFunctions[obj.command] user, obj, cb + answ = commandFunctions[obj.command] user, obj.payload, cb else cb code: 404 @@ -71,21 +72,19 @@ commandFunctions = forge_event_poller: ( user, obj, cb ) => answ = code: 200 - - db.eventPollers.getModule obj.id, ( err, mod ) => - if mod - answ.code = 409 - answ.message = 'Event Poller module name already existing: ' + obj.id - - else - src = obj.data - cm = dynmod.compileString src, obj.id, {}, obj.lang - answ = cm.answ - if answ.code is 200 - if not obj.id or not obj.params - answ.code = 400 - answ.message = "Your request didn't contain all necessary fields! id and params required" - else + if not obj.id or not obj.params + answ.code = 400 + answ.message = "Your request didn't contain all necessary fields! id and params required" + else + db.eventPollers.getModule obj.id, ( err, mod ) => + if mod + answ.code = 409 + answ.message = 'Event Poller module name already existing: ' + obj.id + else + src = obj.data + cm = dynmod.compileString src, obj.id, {}, obj.lang + answ = cm.answ + if answ.code is 200 events = [] events.push name for name, id of cm.module @log.info "CM | Storing new eventpoller with events #{ events }" @@ -186,10 +185,9 @@ commandFunctions = code: 400 message: 'Missing properties in rule!' else - ep = JSON.parse obj.event rule = id: obj.id - event: ep + event: obj.event conditions: JSON.parse obj.conditions actions: JSON.parse obj.actions strRule = JSON.stringify rule diff --git a/coffee/request-handler.coffee b/coffee/request-handler.coffee index 7999944..53ddd82 100644 --- a/coffee/request-handler.coffee +++ b/coffee/request-handler.coffee @@ -65,6 +65,7 @@ objects.* @public handleEvent( *req, resp* ) ### exports.handleEvent = ( req, resp ) -> + console.log 'handleEvent' body = '' req.on 'data', ( data ) -> body += data @@ -74,7 +75,6 @@ exports.handleEvent = ( req, resp ) -> obj = JSON.parse body catch err resp.send 400, 'Badly formed event!' - # If required event properties are present we process the event # if obj and obj.event and not err timestamp = ( new Date ).toISOString() diff --git a/js-coffee/components-manager.js b/js-coffee/components-manager.js index 393e396..2087a1b 100644 --- a/js-coffee/components-manager.js +++ b/js-coffee/components-manager.js @@ -1,5 +1,4 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* Components Manager @@ -7,10 +6,12 @@ Components Manager > The components manager takes care of the dynamic JS modules and the rules. > Event Poller and Action Invoker modules are loaded as strings and stored in the database, > then compiled into node modules and rules and used in the engine and event poller. - */ +*/ + (function() { - var commandFunctions, db, dynmod, events, exports, fs, path, vm; + var commandFunctions, db, dynmod, events, exports, fs, path, vm, + _this = this; db = require('./persistence'); @@ -24,25 +25,22 @@ Components Manager events = require('events'); - /* Module call ----------- Initializes the HTTP listener and its request handler. @param {Object} args - */ + */ - exports = module.exports = (function(_this) { - return function(args) { - _this.log = args.logger; - _this.ee = new events.EventEmitter(); - db(args); - dynmod(args); - return module.exports; - }; - })(this); + exports = module.exports = function(args) { + _this.log = args.logger; + _this.ee = new events.EventEmitter(); + db(args); + dynmod(args); + return module.exports; + }; /* Add an event handler (eh) for a certain event (evt). @@ -54,80 +52,76 @@ Components Manager @public addListener ( *evt, eh* ) @param {String} evt @param {function} eh - */ + */ - exports.addListener = (function(_this) { - return function(evt, eh) { - _this.ee.addListener(evt, eh); - if (evt === 'init') { - return db.getRules(function(err, obj) { - var id, rule, _results; - _results = []; - for (id in obj) { - rule = obj[id]; - _results.push(_this.ee.emit('init', rule)); - } - return _results; - }); - } - }; - })(this); - exports.processRequest = (function(_this) { - return function(user, obj, cb) { - var answ; - if (commandFunctions[obj.command]) { - return answ = commandFunctions[obj.command](user, obj, cb); - } else { - return cb({ - code: 404, - message: 'Strange request!' - }); - } - }; - })(this); + exports.addListener = function(evt, eh) { + _this.ee.addListener(evt, eh); + if (evt === 'init') { + return db.getRules(function(err, obj) { + var id, rule, _results; + _results = []; + for (id in obj) { + rule = obj[id]; + _results.push(_this.ee.emit('init', rule)); + } + return _results; + }); + } + }; + + exports.processRequest = function(user, obj, cb) { + var answ; + console.log(obj); + if (commandFunctions[obj.command]) { + return answ = commandFunctions[obj.command](user, obj.payload, cb); + } else { + return cb({ + code: 404, + message: 'Strange request!' + }); + } + }; commandFunctions = { - forge_event_poller: (function(_this) { - return function(user, obj, cb) { - var answ; - answ = { - code: 200 - }; - return db.eventPollers.getModule(obj.id, function(err, mod) { + forge_event_poller: function(user, obj, cb) { + var answ; + answ = { + code: 200 + }; + if (!obj.id || !obj.params) { + answ.code = 400; + return answ.message = "Your request didn't contain all necessary fields! id and params required"; + } else { + db.eventPollers.getModule(obj.id, function(err, mod) { var cm, id, name, src, _ref; if (mod) { answ.code = 409; - answ.message = 'Event Poller module name already existing: ' + obj.id; + return answ.message = 'Event Poller module name already existing: ' + obj.id; } else { src = obj.data; cm = dynmod.compileString(src, obj.id, {}, obj.lang); answ = cm.answ; if (answ.code === 200) { - if (!obj.id || !obj.params) { - answ.code = 400; - answ.message = "Your request didn't contain all necessary fields! id and params required"; - } else { - events = []; - _ref = cm.module; - for (name in _ref) { - id = _ref[name]; - events.push(name); - } - _this.log.info("CM | Storing new eventpoller with events " + events); - answ.message = "Event Poller module successfully stored! Found following event(s): " + events; - obj.events = JSON.stringify(events); - db.eventPollers.storeModule(obj.id, user.username, obj); - if (obj["public"] === 'true') { - db.eventPollers.publish(obj.id); - } + events = []; + _ref = cm.module; + for (name in _ref) { + id = _ref[name]; + events.push(name); + } + _this.log.info("CM | Storing new eventpoller with events " + events); + answ.message = "Event Poller module successfully stored! Found following event(s): " + events; + obj.events = JSON.stringify(events); + db.eventPollers.storeModule(obj.id, user.username, obj); + if (obj["public"] === 'true') { + return db.eventPollers.publish(obj.id); } } } - return cb(answ); }); - }; - })(this), + return cb(answ); + } + }, get_event_pollers: function(user, obj, cb) { return db.eventPollers.getAvailableModuleIds(user.username, function(err, obj) { var fGetEvents, id, oRes, sem, _i, _len, _results; @@ -192,104 +186,99 @@ Components Manager }); }); }, - forge_action_invoker: (function(_this) { - return function(user, obj, cb) { - var answ; - answ = { - code: 200 - }; - return db.actionInvokers.getModule(obj.id, function(err, mod) { - var actions, cm, id, name, src, _ref; - if (mod) { - answ.code = 409; - answ.message = 'Action Invoker module name already existing: ' + obj.id; - } else { - src = obj.data; - cm = dynmod.compileString(src, obj.id, {}, obj.lang); - answ = cm.answ; - if (answ.code === 200) { - if (!obj.id || !obj.params) { - answ.code = 400; - answ.message = "Your request didn't contain all necessary fields! id and params required"; - } else { - actions = []; - _ref = cm.module; - for (name in _ref) { - id = _ref[name]; - actions.push(name); - } - _this.log.info("CM | Storing new eventpoller with actions " + actions); - answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions; - obj.actions = JSON.stringify(actions); - db.actionInvokers.storeModule(obj.id, user.username, obj); - if (obj["public"] === 'true') { - db.actionInvokers.publish(obj.id); - } + forge_action_invoker: function(user, obj, cb) { + var answ; + answ = { + code: 200 + }; + return db.actionInvokers.getModule(obj.id, function(err, mod) { + var actions, cm, id, name, src, _ref; + if (mod) { + answ.code = 409; + answ.message = 'Action Invoker module name already existing: ' + obj.id; + } else { + src = obj.data; + cm = dynmod.compileString(src, obj.id, {}, obj.lang); + answ = cm.answ; + if (answ.code === 200) { + if (!obj.id || !obj.params) { + answ.code = 400; + answ.message = "Your request didn't contain all necessary fields! id and params required"; + } else { + actions = []; + _ref = cm.module; + for (name in _ref) { + id = _ref[name]; + actions.push(name); + } + _this.log.info("CM | Storing new eventpoller with actions " + actions); + answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions; + obj.actions = JSON.stringify(actions); + db.actionInvokers.storeModule(obj.id, user.username, obj); + if (obj["public"] === 'true') { + db.actionInvokers.publish(obj.id); } } } - return cb(answ); - }); - }; - })(this), + } + return cb(answ); + }); + }, get_rules: function(user, obj, cb) { return console.log('CM | Implement get_rules'); }, - forge_rule: (function(_this) { - return function(user, obj, cb) { - return db.getRule(obj.id, function(err, oExisting) { - var answ, arrParams, ep, id, params, rule, strRule; - try { - if (oExisting !== null) { + forge_rule: function(user, obj, cb) { + return db.getRule(obj.id, function(err, oExisting) { + var answ, arrParams, id, params, rule, strRule; + try { + if (oExisting !== null) { + answ = { + code: 409, + message: 'Rule name already existing!' + }; + } else { + if (!obj.id || !obj.event || !obj.conditions || !obj.actions) { answ = { - code: 409, - message: 'Rule name already existing!' + code: 400, + message: 'Missing properties in rule!' }; } else { - if (!obj.id || !obj.event || !obj.conditions || !obj.actions) { - answ = { - code: 400, - message: 'Missing properties in rule!' - }; - } else { - ep = JSON.parse(obj.event); - rule = { - id: obj.id, - event: ep, - conditions: JSON.parse(obj.conditions), - actions: JSON.parse(obj.actions) - }; - strRule = JSON.stringify(rule); - db.storeRule(rule.id, strRule); - db.linkRule(rule.id, user.username); - db.activateRule(rule.id, user.username); - if (obj.event_params) { - db.eventPollers.storeUserParams(ep.module, user.username, obj.event_params); - } - arrParams = JSON.parse(obj.action_params); - for (id in arrParams) { - params = arrParams[id]; - db.actionInvokers.storeUserParams(id, user.username, JSON.stringify(params)); - } - _this.ee.emit('newRule', strRule); - answ = { - code: 200, - message: 'Rule stored and activated!' - }; + rule = { + id: obj.id, + event: obj.event, + conditions: JSON.parse(obj.conditions), + actions: JSON.parse(obj.actions) + }; + strRule = JSON.stringify(rule); + db.storeRule(rule.id, strRule); + db.linkRule(rule.id, user.username); + db.activateRule(rule.id, user.username); + if (obj.event_params) { + db.eventPollers.storeUserParams(ep.module, user.username, obj.event_params); } + arrParams = JSON.parse(obj.action_params); + for (id in arrParams) { + params = arrParams[id]; + db.actionInvokers.storeUserParams(id, user.username, JSON.stringify(params)); + } + _this.ee.emit('newRule', strRule); + answ = { + code: 200, + message: 'Rule stored and activated!' + }; } - } catch (_error) { - err = _error; - answ = { - code: 400, - message: 'bad bad request...' - }; - console.log(err); } - return cb(answ); - }); - }; - })(this) + } catch (_error) { + err = _error; + answ = { + code: 400, + message: 'bad bad request...' + }; + console.log(err); + } + return cb(answ); + }); + } }; }).call(this); diff --git a/js-coffee/config.js b/js-coffee/config.js index 9a172f8..8777084 100644 --- a/js-coffee/config.js +++ b/js-coffee/config.js @@ -1,20 +1,20 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* Configuration ============= > Loads the configuration file and acts as an interface to it. - */ +*/ + (function() { - var exports, fetchProp, fs, loadConfigFile, path; + var exports, fetchProp, fs, loadConfigFile, path, + _this = this; fs = require('fs'); path = require('path'); - /* Module call ----------- @@ -24,23 +24,21 @@ Configuration be generated) and configPath for a custom configuration file path. @param {Object} args - */ + */ - exports = module.exports = (function(_this) { - return function(args) { - args = args != null ? args : {}; - if (args.nolog) { - _this.nolog = true; - } - if (args.configPath) { - loadConfigFile(args.configPath); - } else { - loadConfigFile(path.join('config', 'system.json')); - } - return module.exports; - }; - })(this); + exports = module.exports = function(args) { + args = args != null ? args : {}; + if (args.nolog) { + _this.nolog = true; + } + if (args.configPath) { + loadConfigFile(args.configPath); + } else { + loadConfigFile(path.join('config', 'system.json')); + } + return module.exports; + }; /* Tries to load a configuration file from the path relative to this module's parent folder. @@ -48,102 +46,97 @@ Configuration @private loadConfigFile @param {String} configPath - */ + */ - loadConfigFile = (function(_this) { - return function(configPath) { - var confProperties, e, prop, _i, _len; - _this.config = null; - confProperties = ['log', 'http-port', 'db-port']; - try { - _this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath))); - _this.isReady = true; - for (_i = 0, _len = confProperties.length; _i < _len; _i++) { - prop = confProperties[_i]; - if (!_this.config[prop]) { - _this.isReady = false; - } - } - if (!_this.isReady && !_this.nolog) { - return console.error("Missing property in config file, requires:\n" + (" - " + (confProperties.join("\n - ")))); - } - } catch (_error) { - e = _error; - _this.isReady = false; - if (!_this.nolog) { - return console.error("Failed loading config file: " + e.message); + + loadConfigFile = function(configPath) { + var confProperties, e, prop, _i, _len; + _this.config = null; + confProperties = ['log', 'http-port', 'db-port']; + try { + _this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath))); + _this.isReady = true; + for (_i = 0, _len = confProperties.length; _i < _len; _i++) { + prop = confProperties[_i]; + if (!_this.config[prop]) { + _this.isReady = false; } } - }; - })(this); - + if (!_this.isReady && !_this.nolog) { + return console.error("Missing property in config file, requires:\n" + (" - " + (confProperties.join("\n - ")))); + } + } catch (_error) { + e = _error; + _this.isReady = false; + if (!_this.nolog) { + return console.error("Failed loading config file: " + e.message); + } + } + }; /* Fetch a property from the configuration @private fetchProp( *prop* ) @param {String} prop - */ + */ - fetchProp = (function(_this) { - return function(prop) { - var _ref; - return (_ref = _this.config) != null ? _ref[prop] : void 0; - }; - })(this); + fetchProp = function(prop) { + var _ref; + return (_ref = _this.config) != null ? _ref[prop] : void 0; + }; /* ***Returns*** true if the config file is ready, else false @public isReady() - */ + */ - exports.isReady = (function(_this) { - return function() { - return _this.isReady; - }; - })(this); + exports.isReady = function() { + return _this.isReady; + }; /* ***Returns*** the HTTP port @public getHttpPort() - */ + */ + exports.getHttpPort = function() { return fetchProp('http-port'); }; - /* ***Returns*** the DB port* @public getDBPort() - */ + */ + exports.getDbPort = function() { return fetchProp('db-port'); }; - /* ***Returns*** the log conf object @public getLogConf() - */ + */ + exports.getLogConf = function() { return fetchProp('log'); }; - /* ***Returns*** the crypto key @public getCryptoKey() - */ + */ + exports.getCryptoKey = function() { return fetchProp('crypto-key'); diff --git a/js-coffee/dynamic-modules.js b/js-coffee/dynamic-modules.js index 7c7ec1b..41d2988 100644 --- a/js-coffee/dynamic-modules.js +++ b/js-coffee/dynamic-modules.js @@ -1,15 +1,16 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* Dynamic Modules =============== > Compiles CoffeeScript modules and loads JS modules in a VM, together > with only a few allowed node.js modules. - */ +*/ + (function() { - var cs, exports, needle, vm; + var cs, exports, needle, vm, + _this = this; vm = require('vm'); @@ -17,22 +18,19 @@ Dynamic Modules cs = require('coffee-script'); - /* Module call ----------- Initializes the dynamic module handler. @param {Object} args - */ + */ - exports = module.exports = (function(_this) { - return function(args) { - _this.log = args.logger; - return module.exports; - }; - })(this); + exports = module.exports = function(args) { + _this.log = args.logger; + return module.exports; + }; /* Try to run a JS module from a string, together with the @@ -44,44 +42,43 @@ Dynamic Modules @param {String} id @param {Object} params @param {String} lang - */ + */ - exports.compileString = (function(_this) { - return function(src, id, params, lang) { - var answ, err, ret, sandbox; - answ = { - code: 200, - message: 'Successfully compiled' - }; - if (lang === '0') { - try { - src = cs.compile(src); - } catch (_error) { - err = _error; - answ.code = 400; - answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line; - } - } - sandbox = { - id: id, - params: params, - needle: needle, - log: console.log, - exports: {} - }; + + exports.compileString = function(src, id, params, lang) { + var answ, err, ret, sandbox; + answ = { + code: 200, + message: 'Successfully compiled' + }; + if (lang === '0') { try { - vm.runInNewContext(src, sandbox, id + '.vm'); + src = cs.compile(src); } catch (_error) { err = _error; answ.code = 400; - answ.message = 'Loading Module failed: ' + err.message; + answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line; } - ret = { - answ: answ, - module: sandbox.exports - }; - return ret; + } + sandbox = { + id: id, + params: params, + needle: needle, + log: console.log, + exports: {} }; - })(this); + try { + vm.runInNewContext(src, sandbox, id + '.vm'); + } catch (_error) { + err = _error; + answ.code = 400; + answ.message = 'Loading Module failed: ' + err.message; + } + ret = { + answ: answ, + module: sandbox.exports + }; + return ret; + }; }).call(this); diff --git a/js-coffee/http-listener.js b/js-coffee/http-listener.js index aa686b2..ba133cc 100644 --- a/js-coffee/http-listener.js +++ b/js-coffee/http-listener.js @@ -1,5 +1,4 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* HTTP Listener @@ -7,10 +6,12 @@ HTTP Listener > Receives the HTTP requests to the server at the given port. The requests > (bound to a method) are then redirected to the appropriate handler which > takes care of the request. - */ +*/ + (function() { - var app, exports, express, initRouting, path, qs, requestHandler; + var app, exports, express, initRouting, path, qs, requestHandler, + _this = this; requestHandler = require('./request-handler'); @@ -22,77 +23,73 @@ HTTP Listener app = express(); - /* Module call ----------- Initializes the HTTP listener and its request handler. @param {Object} args - */ + */ - exports = module.exports = (function(_this) { - return function(args) { - _this.log = args.logger; - _this.shutDownSystem = args['shutdown-function']; - requestHandler(args); - initRouting(args['http-port']); - return module.exports; - }; - })(this); + exports = module.exports = function(args) { + _this.log = args.logger; + _this.shutDownSystem = args['shutdown-function']; + requestHandler(args); + initRouting(args['http-port']); + return module.exports; + }; /* Initializes the request routing and starts listening on the given port. @param {int} port @private initRouting( *fShutDown* ) - */ + */ - initRouting = (function(_this) { - return function(port) { - var server, sess_sec; - app.use(express.cookieParser()); - sess_sec = "149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT 'action-invokers' and then stored in the db with the key 'action-invoker:' + ID > (e.g. action-invoker:probinder). > - */ +*/ + (function() { var IndexedModules, crypto, crypto_key, decrypt, encrypt, exports, getSetRecords, hash, redis, replyHandler, + _this = this, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; crypto = require('crypto-js'); @@ -30,50 +31,45 @@ Persistence crypto_key = "}f6y1y}B{.an$}2c$Yl.$mSnF\\HX149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT -1) { + _this.connRefused = true; + return _this.log.error(err, 'DB | Wrong port?'); } - _this.db = redis.createClient(port, 'localhost', { - connect_timeout: 2000 - }); - _this.db.on('error', function(err) { - if (err.message.indexOf('ECONNREFUSED') > -1) { - _this.connRefused = true; - return _this.log.error(err, 'DB | Wrong port?'); - } - }); - exports.eventPollers.setDB(_this.db); - return exports.actionInvokers.setDB(_this.db); - }; - })(this); - + }); + exports.eventPollers.setDB(_this.db); + return exports.actionInvokers.setDB(_this.db); + }; /* Checks whether the db is connected and passes either an error on failure after @@ -81,185 +77,169 @@ Persistence @public isConnected( *cb* ) @param {function} cb - */ + */ - exports.isConnected = (function(_this) { - return function(cb) { - var fCheckConnection, numAttempts; - if (!_this.db) { - return cb(new Error('DB | DB initialization did not occur or failed miserably!')); + + exports.isConnected = function(cb) { + var fCheckConnection, numAttempts; + if (!_this.db) { + return cb(new Error('DB | DB initialization did not occur or failed miserably!')); + } else { + if (_this.db.connected) { + return cb(); } else { - if (_this.db.connected) { - return cb(); - } else { - numAttempts = 0; - fCheckConnection = function() { - if (_this.connRefused) { - return cb(new Error('DB | Connection refused! Wrong port?')); + numAttempts = 0; + fCheckConnection = function() { + if (_this.connRefused) { + return cb(new Error('DB | Connection refused! Wrong port?')); + } else { + if (_this.db.connected) { + _this.log.info('DB | Successfully connected to DB!'); + return cb(); + } else if (numAttempts++ < 10) { + return setTimeout(fCheckConnection, 100); } else { - if (_this.db.connected) { - _this.log.info('DB | Successfully connected to DB!'); - return cb(); - } else if (numAttempts++ < 10) { - return setTimeout(fCheckConnection, 100); - } else { - return cb(new Error('DB | Connection to DB failed!')); - } + return cb(new Error('DB | Connection to DB failed!')); } - }; - return setTimeout(fCheckConnection, 100); - } + } + }; + return setTimeout(fCheckConnection, 100); } - }; - })(this); - + } + }; /* Abstracts logging for simple action replies from the DB. @private replyHandler( *action* ) @param {String} action - */ + */ - replyHandler = (function(_this) { - return function(action) { - return function(err, reply) { - if (err) { - return _this.log.warn(err, "during '" + action + "'"); - } else { - return _this.log.info("DB | " + action + ": " + reply); - } - }; + + replyHandler = function(action) { + return function(err, reply) { + if (err) { + return _this.log.warn(err, "during '" + action + "'"); + } else { + return _this.log.info("DB | " + action + ": " + reply); + } }; - })(this); - + }; /* Push an event into the event queue. @public pushEvent( *oEvent* ) @param {Object} oEvent - */ + */ - exports.pushEvent = (function(_this) { - return function(oEvent) { - if (oEvent) { - _this.log.info("DB | Event pushed into the queue: '" + oEvent.eventid + "'"); - return _this.db.rpush('event_queue', JSON.stringify(oEvent)); - } else { - return _this.log.warn('DB | Why would you give me an empty event...'); - } - }; - })(this); + exports.pushEvent = function(oEvent) { + if (oEvent) { + _this.log.info("DB | Event pushed into the queue: '" + oEvent.eventid + "'"); + return _this.db.rpush('event_queue', JSON.stringify(oEvent)); + } else { + return _this.log.warn('DB | Why would you give me an empty event...'); + } + }; /* Pop an event from the event queue and pass it to cb(err, obj). @public popEvent( *cb* ) @param {function} cb - */ + */ - exports.popEvent = (function(_this) { - return function(cb) { - var makeObj; - makeObj = function(pcb) { - return function(err, obj) { - return pcb(err, JSON.parse(obj)); - }; + + exports.popEvent = function(cb) { + var makeObj; + makeObj = function(pcb) { + return function(err, obj) { + return pcb(err, JSON.parse(obj)); }; - return _this.db.lpop('event_queue', makeObj(cb)); }; - })(this); - + return _this.db.lpop('event_queue', makeObj(cb)); + }; /* Purge the event queue. @public purgeEventQueue() - */ + */ - exports.purgeEventQueue = (function(_this) { - return function() { - return _this.db.del('event_queue', replyHandler('purging event queue')); - }; - })(this); + exports.purgeEventQueue = function() { + return _this.db.del('event_queue', replyHandler('purging event queue')); + }; /* Hashes a string based on SHA-3-512. @private hash( *plainText* ) @param {String} plainText - */ + */ - hash = (function(_this) { - return function(plainText) { - var err; - if (plainText == null) { - return null; - } - try { - return (crypto.SHA3(plainText, { - outputLength: 512 - })).toString(); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during hashing'); - return null; - } - }; - })(this); + hash = function(plainText) { + var err; + if (plainText == null) { + return null; + } + try { + return (crypto.SHA3(plainText, { + outputLength: 512 + })).toString(); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during hashing'); + return null; + } + }; /* Encrypts a string using the crypto key from the config file, based on aes-256-cbc. @private encrypt( *plainText* ) @param {String} plainText - */ + */ - encrypt = (function(_this) { - return function(plainText) { - var err; - if (plainText == null) { - return null; - } - try { - return crypto.AES.encrypt(plainText, crypto_key); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during encryption'); - return null; - } - }; - })(this); + encrypt = function(plainText) { + var err; + if (plainText == null) { + return null; + } + try { + return crypto.AES.encrypt(plainText, crypto_key); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during encryption'); + return null; + } + }; /* Decrypts an encrypted string and hands it back on success or null. @private decrypt( *crypticText* ) @param {String} crypticText - */ + */ - decrypt = (function(_this) { - return function(crypticText) { - var dec, err; - if (crypticText == null) { - return null; - } - try { - dec = crypto.AES.decrypt(crypticText, crypto_key); - return dec.toString(crypto.enc.Utf8); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during decryption'); - return null; - } - }; - })(this); + decrypt = function(crypticText) { + var dec, err; + if (crypticText == null) { + return null; + } + try { + dec = crypto.AES.decrypt(crypticText, crypto_key); + return dec.toString(crypto.enc.Utf8); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during decryption'); + return null; + } + }; /* Fetches all linked data set keys from a linking set, fetches the single @@ -271,51 +251,50 @@ Persistence per set entry @param {function} cb the callback(err, obj) function that receives all the retrieved data or an error - */ + */ - getSetRecords = (function(_this) { - return function(set, fSingle, cb) { - _this.log.info("DB | Fetching set records: '" + set + "'"); - return _this.db.smembers(set, function(err, arrReply) { - var fCallback, objReplies, reply, semaphore, _i, _len, _results; - if (err) { - _this.log.warn(err, "DB | fetching '" + set + "'"); - return cb(err); - } else if (arrReply.length === 0) { - return cb(); - } else { - semaphore = arrReply.length; - objReplies = {}; - setTimeout(function() { - if (semaphore > 0) { - return cb(new Error("Timeout fetching '" + set + "'")); - } - }, 2000); - fCallback = function(prop) { - return function(err, data) { - --semaphore; - if (err) { - _this.log.warn(err, "DB | fetching single element: '" + prop + "'"); - } else if (!data) { - _this.log.warn(new Error("Empty key in DB: '" + prop + "'")); - } else { - objReplies[prop] = data; - } - if (semaphore === 0) { - return cb(null, objReplies); - } - }; - }; - _results = []; - for (_i = 0, _len = arrReply.length; _i < _len; _i++) { - reply = arrReply[_i]; - _results.push(fSingle(reply, fCallback(reply))); + + getSetRecords = function(set, fSingle, cb) { + _this.log.info("DB | Fetching set records: '" + set + "'"); + return _this.db.smembers(set, function(err, arrReply) { + var fCallback, objReplies, reply, semaphore, _i, _len, _results; + if (err) { + _this.log.warn(err, "DB | fetching '" + set + "'"); + return cb(err); + } else if (arrReply.length === 0) { + return cb(); + } else { + semaphore = arrReply.length; + objReplies = {}; + setTimeout(function() { + if (semaphore > 0) { + return cb(new Error("Timeout fetching '" + set + "'")); } - return _results; + }, 2000); + fCallback = function(prop) { + return function(err, data) { + --semaphore; + if (err) { + _this.log.warn(err, "DB | fetching single element: '" + prop + "'"); + } else if (!data) { + _this.log.warn(new Error("Empty key in DB: '" + prop + "'")); + } else { + objReplies[prop] = data; + } + if (semaphore === 0) { + return cb(null, objReplies); + } + }; + }; + _results = []; + for (_i = 0, _len = arrReply.length; _i < _len; _i++) { + reply = arrReply[_i]; + _results.push(fSingle(reply, fCallback(reply))); } - }); - }; - })(this); + return _results; + } + }); + }; IndexedModules = (function() { function IndexedModules(setname, log) { @@ -344,13 +323,13 @@ Persistence return this.log.info("DB | (IdxedMods) Registered new DB connection for '" + this.setname + "'"); }; - /* @private storeModule( *mId, userId, data* ) @param {String} mId @param {String} userId @param {object} data - */ + */ + IndexedModules.prototype.storeModule = function(mId, userId, data) { this.log.info("DB | (IdxedMods) " + this.setname + ".storeModule( " + mId + ", " + userId + ", data )"); @@ -407,20 +386,19 @@ Persistence }; IndexedModules.prototype.deleteModule = function(mId) { + var _this = this; this.log.info("DB | (IdxedMods) " + this.setname + ".deleteModule( " + mId + " )"); this.db.srem("" + this.setname + "s", mId, replyHandler("srem '" + mId + "' from " + this.setname + "s")); this.db.del("" + this.setname + ":" + mId, replyHandler("del of '" + this.setname + ":" + mId + "'")); - return this.db.smembers("" + this.setname + ":" + mId + ":users", (function(_this) { - return function(err, obj) { - var userId, _i, _len, _results; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - userId = obj[_i]; - _results.push(_this.unlinkModule(mId, userId)); - } - return _results; - }; - })(this)); + return this.db.smembers("" + this.setname + ":" + mId + ":users", function(err, obj) { + var userId, _i, _len, _results; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + userId = obj[_i]; + _results.push(_this.unlinkModule(mId, userId)); + } + return _results; + }); }; IndexedModules.prototype.storeUserParams = function(mId, userId, data) { @@ -451,10 +429,9 @@ Persistence })(); - /* - *# Rules - */ + ## Rules + */ /* @@ -463,45 +440,39 @@ Persistence @public getRule( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ - exports.getRule = (function(_this) { - return function(ruleId, cb) { - _this.log.info("DB | getRule: '" + ruleId + "'"); - return _this.db.get("rule:" + ruleId, cb); - }; - })(this); + exports.getRule = function(ruleId, cb) { + _this.log.info("DB | getRule: '" + ruleId + "'"); + return _this.db.get("rule:" + ruleId, cb); + }; /* Fetch all rules and pass them to cb(err, obj). @public getRules( *cb* ) @param {function} cb - */ + */ - exports.getRules = (function(_this) { - return function(cb) { - _this.log.info('DB | Fetching all Rules'); - return getSetRecords('rules', exports.getRule, cb); - }; - })(this); + exports.getRules = function(cb) { + _this.log.info('DB | Fetching all Rules'); + return getSetRecords('rules', exports.getRule, cb); + }; /* Fetch all rule IDs and hand it to cb(err, obj). @public getRuleIds( *cb* ) @param {function} cb - */ + */ - exports.getRuleIds = (function(_this) { - return function(cb) { - _this.log.info('DB | Fetching all Rule IDs'); - return _this.db.smembers('rules', cb); - }; - })(this); + exports.getRuleIds = function(cb) { + _this.log.info('DB | Fetching all Rule IDs'); + return _this.db.smembers('rules', cb); + }; /* Store a string representation of a rule in the DB. @@ -509,16 +480,14 @@ Persistence @public storeRule( *ruleId, data* ) @param {String} ruleId @param {String} data - */ + */ - exports.storeRule = (function(_this) { - return function(ruleId, data) { - _this.log.info("DB | storeRule: '" + ruleId + "'"); - _this.db.sadd('rules', "" + ruleId, replyHandler("storing rule key '" + ruleId + "'")); - return _this.db.set("rule:" + ruleId, data, replyHandler("storing rule '" + ruleId + "'")); - }; - })(this); + exports.storeRule = function(ruleId, data) { + _this.log.info("DB | storeRule: '" + ruleId + "'"); + _this.db.sadd('rules', "" + ruleId, replyHandler("storing rule key '" + ruleId + "'")); + return _this.db.set("rule:" + ruleId, data, replyHandler("storing rule '" + ruleId + "'")); + }; /* Delete a string representation of a rule. @@ -526,42 +495,40 @@ Persistence @public deleteRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ - exports.deleteRule = (function(_this) { - return function(ruleId) { - _this.log.info("DB | deleteRule: '" + ruleId + "'"); - _this.db.srem("rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "'")); - _this.db.del("rule:" + ruleId, replyHandler("Deleting rule '" + ruleId + "'")); - _this.db.smembers("rule:" + ruleId + ":users", function(err, obj) { - var delLinkedUserRule, id, _i, _len, _results; - delLinkedUserRule = function(userId) { - return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in linked user '" + userId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delLinkedUserRule(id)); - } - return _results; - }); - _this.db.del("rule:" + ruleId + ":users", replyHandler("Deleting rule '" + ruleId + "' users")); - _this.db.smembers("rule:" + ruleId + ":active-users", function(err, obj) { - var delActiveUserRule, id, _i, _len, _results; - delActiveUserRule = function(userId) { - return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in active user '" + userId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delActiveUserRule(id)); - } - return _results; - }); - return _this.db.del("rule:" + ruleId + ":active-users", replyHandler("Deleting rule '" + ruleId + "' active users")); - }; - })(this); + exports.deleteRule = function(ruleId) { + _this.log.info("DB | deleteRule: '" + ruleId + "'"); + _this.db.srem("rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "'")); + _this.db.del("rule:" + ruleId, replyHandler("Deleting rule '" + ruleId + "'")); + _this.db.smembers("rule:" + ruleId + ":users", function(err, obj) { + var delLinkedUserRule, id, _i, _len, _results; + delLinkedUserRule = function(userId) { + return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in linked user '" + userId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delLinkedUserRule(id)); + } + return _results; + }); + _this.db.del("rule:" + ruleId + ":users", replyHandler("Deleting rule '" + ruleId + "' users")); + _this.db.smembers("rule:" + ruleId + ":active-users", function(err, obj) { + var delActiveUserRule, id, _i, _len, _results; + delActiveUserRule = function(userId) { + return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in active user '" + userId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delActiveUserRule(id)); + } + return _results; + }); + return _this.db.del("rule:" + ruleId + ":active-users", replyHandler("Deleting rule '" + ruleId + "' active users")); + }; /* Associate a rule to a user. @@ -569,16 +536,14 @@ Persistence @public linkRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ - exports.linkRule = (function(_this) { - return function(ruleId, userId) { - _this.log.info("DB | linkRule: '" + ruleId + "' for user '" + userId + "'"); - _this.db.sadd("rule:" + ruleId + ":users", userId, replyHandler("storing user '" + userId + "' for rule key '" + ruleId + "'")); - return _this.db.sadd("user:" + userId + ":rules", ruleId, replyHandler("storing rule key '" + ruleId + "' for user '" + userId + "'")); - }; - })(this); + exports.linkRule = function(ruleId, userId) { + _this.log.info("DB | linkRule: '" + ruleId + "' for user '" + userId + "'"); + _this.db.sadd("rule:" + ruleId + ":users", userId, replyHandler("storing user '" + userId + "' for rule key '" + ruleId + "'")); + return _this.db.sadd("user:" + userId + ":rules", ruleId, replyHandler("storing rule key '" + ruleId + "' for user '" + userId + "'")); + }; /* Get rules linked to a user and hand it to cb(err, obj). @@ -586,15 +551,13 @@ Persistence @public getUserLinkRule( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ - exports.getUserLinkedRules = (function(_this) { - return function(userId, cb) { - _this.log.info("DB | getUserLinkedRules: for user '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":rules", cb); - }; - })(this); + exports.getUserLinkedRules = function(userId, cb) { + _this.log.info("DB | getUserLinkedRules: for user '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":rules", cb); + }; /* Get users linked to a rule and hand it to cb(err, obj). @@ -602,15 +565,13 @@ Persistence @public getRuleLinkedUsers( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ - exports.getRuleLinkedUsers = (function(_this) { - return function(ruleId, cb) { - _this.log.info("DB | getRuleLinkedUsers: for rule '" + ruleId + "'"); - return _this.db.smembers("rule:" + ruleId + ":users", cb); - }; - })(this); + exports.getRuleLinkedUsers = function(ruleId, cb) { + _this.log.info("DB | getRuleLinkedUsers: for rule '" + ruleId + "'"); + return _this.db.smembers("rule:" + ruleId + ":users", cb); + }; /* Delete an association of a rule to a user. @@ -618,16 +579,14 @@ Persistence @public unlinkRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ - exports.unlinkRule = (function(_this) { - return function(ruleId, userId) { - _this.log.info("DB | unlinkRule: '" + ruleId + ":" + userId + "'"); - _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("removing user '" + userId + "' for rule key '" + ruleId + "'")); - return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("removing rule key '" + ruleId + "' for user '" + userId + "'")); - }; - })(this); + exports.unlinkRule = function(ruleId, userId) { + _this.log.info("DB | unlinkRule: '" + ruleId + ":" + userId + "'"); + _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("removing user '" + userId + "' for rule key '" + ruleId + "'")); + return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("removing rule key '" + ruleId + "' for user '" + userId + "'")); + }; /* Activate a rule. @@ -635,16 +594,14 @@ Persistence @public activateRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ - exports.activateRule = (function(_this) { - return function(ruleId, userId) { - _this.log.info("DB | activateRule: '" + ruleId + "' for '" + userId + "'"); - _this.db.sadd("rule:" + ruleId + ":active-users", userId, replyHandler("storing activated user '" + userId + "' in rule '" + ruleId + "'")); - return _this.db.sadd("user:" + userId + ":active-rules", ruleId, replyHandler("storing activated rule '" + ruleId + "' in user '" + userId + "'")); - }; - })(this); + exports.activateRule = function(ruleId, userId) { + _this.log.info("DB | activateRule: '" + ruleId + "' for '" + userId + "'"); + _this.db.sadd("rule:" + ruleId + ":active-users", userId, replyHandler("storing activated user '" + userId + "' in rule '" + ruleId + "'")); + return _this.db.sadd("user:" + userId + ":active-rules", ruleId, replyHandler("storing activated rule '" + ruleId + "' in user '" + userId + "'")); + }; /* Get rules activated for a user and hand it to cb(err, obj). @@ -652,15 +609,13 @@ Persistence @public getUserLinkRule( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ - exports.getUserActivatedRules = (function(_this) { - return function(userId, cb) { - _this.log.info("DB | getUserActivatedRules: for user '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":active-rules", cb); - }; - })(this); + exports.getUserActivatedRules = function(userId, cb) { + _this.log.info("DB | getUserActivatedRules: for user '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":active-rules", cb); + }; /* Get users activated for a rule and hand it to cb(err, obj). @@ -668,15 +623,13 @@ Persistence @public getRuleActivatedUsers ( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ - exports.getRuleActivatedUsers = (function(_this) { - return function(ruleId, cb) { - _this.log.info("DB | getRuleActivatedUsers: for rule '" + ruleId + "'"); - return _this.db.smembers("rule:" + ruleId + ":active-users", cb); - }; - })(this); + exports.getRuleActivatedUsers = function(ruleId, cb) { + _this.log.info("DB | getRuleActivatedUsers: for rule '" + ruleId + "'"); + return _this.db.smembers("rule:" + ruleId + ":active-users", cb); + }; /* Deactivate a rule. @@ -684,59 +637,55 @@ Persistence @public deactivateRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ - exports.deactivateRule = (function(_this) { - return function(ruleId, userId) { - _this.log.info("DB | deactivateRule: '" + ruleId + "' for '" + userId + "'"); - _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("removing activated user '" + userId + "' in rule '" + ruleId + "'")); - return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("removing activated rule '" + ruleId + "' in user '" + userId + "'")); - }; - })(this); + exports.deactivateRule = function(ruleId, userId) { + _this.log.info("DB | deactivateRule: '" + ruleId + "' for '" + userId + "'"); + _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("removing activated user '" + userId + "' in rule '" + ruleId + "'")); + return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("removing activated rule '" + ruleId + "' in user '" + userId + "'")); + }; /* Fetch all active ruleIds and pass them to cb(err, obj). @public getAllActivatedRuleIds( *cb* ) @param {function} cb - */ + */ - exports.getAllActivatedRuleIdsPerUser = (function(_this) { - return function(cb) { - _this.log.info("DB | Fetching all active rules"); - return _this.db.smembers('users', function(err, obj) { - var fFetchActiveUserRules, result, semaphore, user, _i, _len, _results; - result = {}; - if (obj.length === 0) { - return cb(null, result); - } else { - semaphore = obj.length; - fFetchActiveUserRules = function(userId) { - return _this.db.smembers("user:" + user + ":active-rules", function(err, obj) { - if (obj.length > 0) { - result[userId] = obj; - } - if (--semaphore === 0) { - return cb(null, result); - } - }); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - user = obj[_i]; - _results.push(fFetchActiveUserRules(user)); - } - return _results; + + exports.getAllActivatedRuleIdsPerUser = function(cb) { + _this.log.info("DB | Fetching all active rules"); + return _this.db.smembers('users', function(err, obj) { + var fFetchActiveUserRules, result, semaphore, user, _i, _len, _results; + result = {}; + if (obj.length === 0) { + return cb(null, result); + } else { + semaphore = obj.length; + fFetchActiveUserRules = function(userId) { + return _this.db.smembers("user:" + user + ":active-rules", function(err, obj) { + if (obj.length > 0) { + result[userId] = obj; + } + if (--semaphore === 0) { + return cb(null, result); + } + }); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + user = obj[_i]; + _results.push(fFetchActiveUserRules(user)); } - }); - }; - })(this); - + return _results; + } + }); + }; /* - *# Users - */ + ## Users + */ /* @@ -745,36 +694,32 @@ Persistence @public storeUser( *objUser* ) @param {Object} objUser - */ + */ - exports.storeUser = (function(_this) { - return function(objUser) { - _this.log.info("DB | storeUser: '" + objUser.username + "'"); - if (objUser && objUser.username && objUser.password) { - _this.db.sadd('users', objUser.username, replyHandler("storing user key '" + objUser.username + "'")); - objUser.password = objUser.password; - return _this.db.hmset("user:" + objUser.username, objUser, replyHandler("storing user properties '" + objUser.username + "'")); - } else { - return _this.log.warn(new Error('DB | username or password was missing')); - } - }; - })(this); + exports.storeUser = function(objUser) { + _this.log.info("DB | storeUser: '" + objUser.username + "'"); + if (objUser && objUser.username && objUser.password) { + _this.db.sadd('users', objUser.username, replyHandler("storing user key '" + objUser.username + "'")); + objUser.password = objUser.password; + return _this.db.hmset("user:" + objUser.username, objUser, replyHandler("storing user properties '" + objUser.username + "'")); + } else { + return _this.log.warn(new Error('DB | username or password was missing')); + } + }; /* Fetch all user IDs and pass them to cb(err, obj). @public getUserIds( *cb* ) @param {function} cb - */ + */ - exports.getUserIds = (function(_this) { - return function(cb) { - _this.log.info("DB | getUserIds"); - return _this.db.smembers("users", cb); - }; - })(this); + exports.getUserIds = function(cb) { + _this.log.info("DB | getUserIds"); + return _this.db.smembers("users", cb); + }; /* Fetch a user by id and pass it to cb(err, obj). @@ -782,70 +727,66 @@ Persistence @public getUser( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ - exports.getUser = (function(_this) { - return function(userId, cb) { - _this.log.info("DB | getUser: '" + userId + "'"); - return _this.db.hgetall("user:" + userId, cb); - }; - })(this); + exports.getUser = function(userId, cb) { + _this.log.info("DB | getUser: '" + userId + "'"); + return _this.db.hgetall("user:" + userId, cb); + }; /* Deletes a user and all his associated linked and active rules. @public deleteUser( *userId* ) @param {String} userId - */ + */ - exports.deleteUser = (function(_this) { - return function(userId) { - _this.log.info("DB | deleteUser: '" + userId + "'"); - _this.db.srem("users", userId, replyHandler("Deleting user key '" + userId + "'")); - _this.db.del("user:" + userId, replyHandler("Deleting user '" + userId + "'")); - _this.db.smembers("user:" + userId + ":rules", function(err, obj) { - var delLinkedRuleUser, id, _i, _len, _results; - delLinkedRuleUser = function(ruleId) { - return _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in linked rule '" + ruleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delLinkedRuleUser(id)); - } - return _results; - }); - _this.db.del("user:" + userId + ":rules", replyHandler("Deleting user '" + userId + "' rules")); - _this.db.smembers("user:" + userId + ":active-rules", function(err, obj) { - var delActivatedRuleUser, id, _i, _len, _results; - delActivatedRuleUser = function(ruleId) { - return _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("Deleting user key '" + userId + "' in active rule '" + ruleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delActivatedRuleUser(id)); - } - return _results; - }); - _this.db.del("user:" + userId + ":active-rules", replyHandler("Deleting user '" + userId + "' rules")); - _this.db.smembers("user:" + userId + ":roles", function(err, obj) { - var delRoleUser, id, _i, _len, _results; - delRoleUser = function(roleId) { - return _this.db.srem("role:" + roleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in role '" + roleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delRoleUser(id)); - } - return _results; - }); - return _this.db.del("user:" + userId + ":roles", replyHandler("Deleting user '" + userId + "' roles")); - }; - })(this); + exports.deleteUser = function(userId) { + _this.log.info("DB | deleteUser: '" + userId + "'"); + _this.db.srem("users", userId, replyHandler("Deleting user key '" + userId + "'")); + _this.db.del("user:" + userId, replyHandler("Deleting user '" + userId + "'")); + _this.db.smembers("user:" + userId + ":rules", function(err, obj) { + var delLinkedRuleUser, id, _i, _len, _results; + delLinkedRuleUser = function(ruleId) { + return _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in linked rule '" + ruleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delLinkedRuleUser(id)); + } + return _results; + }); + _this.db.del("user:" + userId + ":rules", replyHandler("Deleting user '" + userId + "' rules")); + _this.db.smembers("user:" + userId + ":active-rules", function(err, obj) { + var delActivatedRuleUser, id, _i, _len, _results; + delActivatedRuleUser = function(ruleId) { + return _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("Deleting user key '" + userId + "' in active rule '" + ruleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delActivatedRuleUser(id)); + } + return _results; + }); + _this.db.del("user:" + userId + ":active-rules", replyHandler("Deleting user '" + userId + "' rules")); + _this.db.smembers("user:" + userId + ":roles", function(err, obj) { + var delRoleUser, id, _i, _len, _results; + delRoleUser = function(roleId) { + return _this.db.srem("role:" + roleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in role '" + roleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delRoleUser(id)); + } + return _results; + }); + return _this.db.del("user:" + userId + ":roles", replyHandler("Deleting user '" + userId + "' roles")); + }; /* Checks the credentials and on success returns the user object to the @@ -857,36 +798,34 @@ Persistence @param {String} userId @param {String} password @param {function} cb - */ + */ - exports.loginUser = (function(_this) { - return function(userId, password, cb) { - var fCheck; - _this.log.info("DB | User '" + userId + "' tries to log in"); - fCheck = function(pw) { - return function(err, obj) { - if (err) { - return cb(err, null); - } else if (obj && obj.password) { - if (pw === obj.password) { - _this.log.info("DB | User '" + obj.username + "' logged in!"); - return cb(null, obj); - } else { - return cb(new Error('Wrong credentials!'), null); - } + + exports.loginUser = function(userId, password, cb) { + var fCheck; + _this.log.info("DB | User '" + userId + "' tries to log in"); + fCheck = function(pw) { + return function(err, obj) { + if (err) { + return cb(err, null); + } else if (obj && obj.password) { + if (pw === obj.password) { + _this.log.info("DB | User '" + obj.username + "' logged in!"); + return cb(null, obj); } else { - return cb(new Error('User not found!'), null); + return cb(new Error('Wrong credentials!'), null); } - }; + } else { + return cb(new Error('User not found!'), null); + } }; - return _this.db.hgetall("user:" + userId, fCheck(password)); }; - })(this); - + return _this.db.hgetall("user:" + userId, fCheck(password)); + }; /* - *# User Roles - */ + ## User Roles + */ /* @@ -895,17 +834,15 @@ Persistence @public storeUserRole( *userId, role* ) @param {String} userId @param {String} role - */ + */ - exports.storeUserRole = (function(_this) { - return function(userId, role) { - _this.log.info("DB | storeUserRole: '" + userId + ":" + role + "'"); - _this.db.sadd('roles', role, replyHandler("adding role '" + role + "' to role index set")); - _this.db.sadd("user:" + userId + ":roles", role, replyHandler("adding role '" + role + "' to user '" + userId + "'")); - return _this.db.sadd("role:" + role + ":users", userId, replyHandler("adding user '" + userId + "' to role '" + role + "'")); - }; - })(this); + exports.storeUserRole = function(userId, role) { + _this.log.info("DB | storeUserRole: '" + userId + ":" + role + "'"); + _this.db.sadd('roles', role, replyHandler("adding role '" + role + "' to role index set")); + _this.db.sadd("user:" + userId + ":roles", role, replyHandler("adding role '" + role + "' to user '" + userId + "'")); + return _this.db.sadd("role:" + role + ":users", userId, replyHandler("adding user '" + userId + "' to role '" + role + "'")); + }; /* Fetch all roles of a user and pass them to cb(err, obj). @@ -913,15 +850,13 @@ Persistence @public getUserRoles( *userId* ) @param {String} userId @param {function} cb - */ + */ - exports.getUserRoles = (function(_this) { - return function(userId, cb) { - _this.log.info("DB | getUserRoles: '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":roles", cb); - }; - })(this); + exports.getUserRoles = function(userId, cb) { + _this.log.info("DB | getUserRoles: '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":roles", cb); + }; /* Fetch all users of a role and pass them to cb(err, obj). @@ -929,15 +864,13 @@ Persistence @public getUserRoles( *role* ) @param {String} role @param {function} cb - */ + */ - exports.getRoleUsers = (function(_this) { - return function(role, cb) { - _this.log.info("DB | getRoleUsers: '" + role + "'"); - return _this.db.smembers("role:" + role + ":users", cb); - }; - })(this); + exports.getRoleUsers = function(role, cb) { + _this.log.info("DB | getRoleUsers: '" + role + "'"); + return _this.db.smembers("role:" + role + ":users", cb); + }; /* Remove a role from a user. @@ -945,28 +878,25 @@ Persistence @public removeRoleFromUser( *role, userId* ) @param {String} role @param {String} userId - */ + */ - exports.removeUserRole = (function(_this) { - return function(userId, role) { - _this.log.info("DB | removeRoleFromUser: role '" + role + "', user '" + userId + "'"); - _this.db.srem("user:" + userId + ":roles", role, replyHandler("Removing role '" + role + "' from user '" + userId + "'")); - return _this.db.srem("role:" + role + ":users", userId, replyHandler("Removing user '" + userId + "' from role '" + role + "'")); - }; - })(this); + exports.removeUserRole = function(userId, role) { + _this.log.info("DB | removeRoleFromUser: role '" + role + "', user '" + userId + "'"); + _this.db.srem("user:" + userId + ":roles", role, replyHandler("Removing role '" + role + "' from user '" + userId + "'")); + return _this.db.srem("role:" + role + ":users", userId, replyHandler("Removing user '" + userId + "' from role '" + role + "'")); + }; /* Shuts down the db link. @public shutDown() - */ + */ - exports.shutDown = (function(_this) { - return function() { - var _ref; - return (_ref = _this.db) != null ? _ref.quit() : void 0; - }; - })(this); + + exports.shutDown = function() { + var _ref; + return (_ref = _this.db) != null ? _ref.quit() : void 0; + }; }).call(this); diff --git a/js-coffee/request-handler.js b/js-coffee/request-handler.js index 212cdc0..0572309 100644 --- a/js-coffee/request-handler.js +++ b/js-coffee/request-handler.js @@ -1,5 +1,4 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* Request Handler @@ -8,10 +7,12 @@ Request Handler > the [HTTP Listener](http-listener.html). It will handle user requests for > pages as well as POST requests such as user login, module storing, event > invocation and also admin commands. - */ +*/ + (function() { - var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage; + var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage, + _this = this; db = require('./persistence'); @@ -27,35 +28,32 @@ Request Handler dirHandlers = path.resolve(__dirname, '..', 'webpages', 'handlers'); - exports = module.exports = (function(_this) { - return function(args) { - var fStoreUser, user, users; - _this.log = args.logger; - _this.userRequestHandler = args['request-service']; - _this.objAdminCmds = { - shutdown: function(obj, cb) { - var data; - data = { - code: 200, - message: 'Shutting down... BYE!' - }; - setTimeout(args['shutdown-function'], 500); - return cb(null, data); - } - }; - db(args); - users = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'config', 'users.json'))); - fStoreUser = function(username, oUser) { - oUser.username = username; - return db.storeUser(oUser); - }; - for (user in users) { - fStoreUser(user, users[user]); + exports = module.exports = function(args) { + var fStoreUser, user, users; + _this.log = args.logger; + _this.userRequestHandler = args['request-service']; + _this.objAdminCmds = { + shutdown: function(obj, cb) { + var data; + data = { + code: 200, + message: 'Shutting down... BYE!' + }; + setTimeout(args['shutdown-function'], 500); + return cb(null, data); } - return module.exports; }; - })(this); - + db(args); + users = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'config', 'users.json'))); + fStoreUser = function(username, oUser) { + oUser.username = username; + return db.storeUser(oUser); + }; + for (user in users) { + fStoreUser(user, users[user]); + } + return module.exports; + }; /* Handles possible events that were posted to this server and pushes them into the @@ -67,10 +65,12 @@ Request Handler objects.* @public handleEvent( *req, resp* ) - */ + */ + exports.handleEvent = function(req, resp) { var body; + console.log('handleEvent'); body = ''; req.on('data', function(data) { return body += data; @@ -103,7 +103,6 @@ Request Handler }); }; - /* Associates the user object with the session if login is successful. @@ -113,34 +112,32 @@ Request Handler objects.* @public handleLogin( *req, resp* ) - */ + */ - exports.handleLogin = (function(_this) { - return function(req, resp) { - var body; - body = ''; - req.on('data', function(data) { - return body += data; - }); - return req.on('end', function() { - var obj; - obj = qs.parse(body); - return db.loginUser(obj.username, obj.password, function(err, usr) { - if (err) { - _this.log.warn("RH | AUTH-UH-OH ( " + obj.username + " ): " + err.message); - } else { - req.session.user = usr; - } - if (req.session.user) { - return resp.send('OK!'); - } else { - return resp.send(401, 'NO!'); - } - }); - }); - }; - })(this); + exports.handleLogin = function(req, resp) { + var body; + body = ''; + req.on('data', function(data) { + return body += data; + }); + return req.on('end', function() { + var obj; + obj = qs.parse(body); + return db.loginUser(obj.username, obj.password, function(err, usr) { + if (err) { + _this.log.warn("RH | AUTH-UH-OH ( " + obj.username + " ): " + err.message); + } else { + req.session.user = usr; + } + if (req.session.user) { + return resp.send('OK!'); + } else { + return resp.send(401, 'NO!'); + } + }); + }); + }; /* A post request retrieved on this handler causes the user object to be @@ -152,7 +149,8 @@ Request Handler objects.* @public handleLogout( *req, resp* ) - */ + */ + exports.handleLogout = function(req, resp) { if (req.session) { @@ -161,25 +159,25 @@ Request Handler } }; - /* Resolves the path to a handler webpage. @private getHandlerPath( *name* ) @param {String} name - */ + */ + getHandlerPath = function(name) { return path.join(dirHandlers, name + '.html'); }; - /* Fetches a template. @private getTemplate( *name* ) @param {String} name - */ + */ + getTemplate = function(name) { var pth; @@ -187,13 +185,13 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; - /* Fetches a script. @private getScript( *name* ) @param {String} name - */ + */ + getScript = function(name) { var pth; @@ -201,13 +199,13 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; - /* Fetches remote scripts snippets. @private getRemoteScripts( *name* ) @param {String} name - */ + */ + getRemoteScripts = function(name) { var pth; @@ -215,7 +213,6 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; - /* Renders a page, with helps of mustache, depending on the user session and returns it. @@ -223,7 +220,8 @@ Request Handler @param {String} name @param {Object} sess @param {Object} msg - */ + */ + renderPage = function(name, req, resp, msg) { var code, content, data, err, menubar, page, pageElements, pathSkel, remote_scripts, script, skeleton; @@ -262,7 +260,6 @@ Request Handler return resp.send(code, mustache.render(page, data)); }; - /* Present the desired forge page to the user. @@ -272,7 +269,8 @@ Request Handler objects.* @public handleForge( *req, resp* ) - */ + */ + exports.handleForge = function(req, resp) { var page; @@ -283,7 +281,6 @@ Request Handler return renderPage(page, req, resp); }; - /* Handles the user command requests. @@ -293,29 +290,27 @@ Request Handler objects.* @public handleUser( *req, resp* ) - */ + */ - exports.handleUserCommand = (function(_this) { - return function(req, resp) { - var body; - if (req.session && req.session.user) { - body = ''; - req.on('data', function(data) { - return body += data; - }); - return req.on('end', function() { - var obj; - obj = qs.parse(body); - return _this.userRequestHandler(req.session.user, obj, function(obj) { - return resp.send(obj.code, obj); - }); - }); - } else { - return resp.send(401, 'Login first!'); - } - }; - })(this); + exports.handleUserCommand = function(req, resp) { + var body; + if (req.session && req.session.user) { + body = ''; + req.on('data', function(data) { + return body += data; + }); + return req.on('end', function() { + var obj; + obj = qs.parse(body); + return _this.userRequestHandler(req.session.user, obj, function(obj) { + return resp.send(obj.code, obj); + }); + }); + } else { + return resp.send(401, 'Login first!'); + } + }; /* Present the admin console to the user if he's allowed to see it. @@ -326,7 +321,8 @@ Request Handler objects.* @public handleForge( *req, resp* ) - */ + */ + exports.handleAdmin = function(req, resp) { var msg, page; @@ -341,7 +337,6 @@ Request Handler return renderPage(page, req, resp, msg); }; - /* Handles the admin command requests. @@ -351,32 +346,31 @@ Request Handler objects.* @public handleAdminCommand( *req, resp* ) - */ + */ - exports.handleAdminCommand = (function(_this) { - return function(req, resp) { - var body; - if (req.session && req.session.user && req.session.user.isAdmin === "true") { - body = ''; - req.on('data', function(data) { - return body += data; - }); - return req.on('end', function() { - var obj; - obj = qs.parse(body); - _this.log.info('RH | Received admin request: ' + obj.command); - if (obj.command && _this.objAdminCmds[obj.command]) { - return _this.objAdminCmds[obj.command](obj, function(err, obj) { - return resp.send(obj.code, obj); - }); - } else { - return resp.send(404, 'Command unknown!'); - } - }); - } else { - return resp.send(401, 'You need to be logged in as admin!'); - } - }; - })(this); + + exports.handleAdminCommand = function(req, resp) { + var body; + if (req.session && req.session.user && req.session.user.isAdmin === "true") { + body = ''; + req.on('data', function(data) { + return body += data; + }); + return req.on('end', function() { + var obj; + obj = qs.parse(body); + _this.log.info('RH | Received admin request: ' + obj.command); + if (obj.command && _this.objAdminCmds[obj.command]) { + return _this.objAdminCmds[obj.command](obj, function(err, obj) { + return resp.send(obj.code, obj); + }); + } else { + return resp.send(404, 'Command unknown!'); + } + }); + } else { + return resp.send(401, 'You need to be logged in as admin!'); + } + }; }).call(this); diff --git a/js-coffee/webapi-eca.js b/js-coffee/webapi-eca.js index 5286c7f..76f78a2 100644 --- a/js-coffee/webapi-eca.js +++ b/js-coffee/webapi-eca.js @@ -1,5 +1,4 @@ -// Generated by CoffeeScript 1.7.1 - +// Generated by CoffeeScript 1.6.3 /* WebAPI-ECA Engine @@ -10,10 +9,12 @@ WebAPI-ECA Engine > node webapi-eca [opt] > > See below in the optimist CLI preparation for allowed optional parameters `[opt]`. - */ +*/ + (function() { - var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage; + var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage, + _this = this; logger = require('./logging'); @@ -39,10 +40,10 @@ WebAPI-ECA Engine procCmds = {}; - /* Let's prepare the optimist CLI optional arguments `[opt]`: - */ + */ + usage = 'This runs your webapi-based ECA engine'; @@ -92,117 +93,113 @@ WebAPI-ECA Engine process.exit(); } - /* This function is invoked right after the module is loaded and starts the server. @private init() - */ + */ - init = (function(_this) { - return function() { - var args, logconf; - conf(argv.c); - if (!conf.isReady()) { - console.error('FAIL: Config file not ready! Shutting down...'); - process.exit(); - } - logconf = conf.getLogConf(); - if (argv.m) { - logconf['mode'] = argv.m; - } - if (argv.i) { - logconf['io-level'] = argv.i; - } - if (argv.f) { - logconf['file-level'] = argv.f; - } - if (argv.p) { - logconf['file-path'] = argv.p; - } - if (argv.n) { - logconf['nolog'] = argv.n; - } - try { - fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path'])); - } catch (_error) {} - _this.log = logger.getLogger(logconf); - _this.log.info('RS | STARTING SERVER'); - args = { - logger: _this.log, - logconf: logconf - }; - args['http-port'] = parseInt(argv.w || conf.getHttpPort()); - args['db-port'] = parseInt(argv.d || conf.getDbPort()); - _this.log.info('RS | Initialzing DB'); - db(args); - return db.isConnected(function(err) { - var cliArgs, poller; - if (err) { - _this.log.error('RS | No DB connection, shutting down system!'); - return shutDown(); - } else { - _this.log.info('RS | Initialzing engine'); - engine(args); - _this.log.info('RS | Forking a child process for the event poller'); - cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']]; - poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs); - _this.log.info('RS | Initialzing module manager'); - cm(args); - cm.addListener('init', function(evt) { - return poller.send({ - event: 'init', - data: evt - }); - }); - cm.addListener('newRule', function(evt) { - return poller.send({ - event: 'newRule', - data: evt - }); - }); - cm.addListener('init', function(evt) { - return engine.internalEvent('init', evt); - }); - cm.addListener('newRule', function(evt) { - return engine.internalEvent('newRule', evt); - }); - _this.log.info('RS | Initialzing http listener'); - args['request-service'] = cm.processRequest; - args['shutdown-function'] = shutDown; - return http(args); - } - }); + + init = function() { + var args, logconf; + conf(argv.c); + if (!conf.isReady()) { + console.error('FAIL: Config file not ready! Shutting down...'); + process.exit(); + } + logconf = conf.getLogConf(); + if (argv.m) { + logconf['mode'] = argv.m; + } + if (argv.i) { + logconf['io-level'] = argv.i; + } + if (argv.f) { + logconf['file-level'] = argv.f; + } + if (argv.p) { + logconf['file-path'] = argv.p; + } + if (argv.n) { + logconf['nolog'] = argv.n; + } + try { + fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path'])); + } catch (_error) {} + _this.log = logger.getLogger(logconf); + _this.log.info('RS | STARTING SERVER'); + args = { + logger: _this.log, + logconf: logconf }; - })(this); - + args['http-port'] = parseInt(argv.w || conf.getHttpPort()); + args['db-port'] = parseInt(argv.d || conf.getDbPort()); + _this.log.info('RS | Initialzing DB'); + db(args); + return db.isConnected(function(err) { + var cliArgs, poller; + if (err) { + _this.log.error('RS | No DB connection, shutting down system!'); + return shutDown(); + } else { + _this.log.info('RS | Initialzing engine'); + engine(args); + _this.log.info('RS | Forking a child process for the event poller'); + cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']]; + poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs); + _this.log.info('RS | Initialzing module manager'); + cm(args); + cm.addListener('init', function(evt) { + return poller.send({ + event: 'init', + data: evt + }); + }); + cm.addListener('newRule', function(evt) { + return poller.send({ + event: 'newRule', + data: evt + }); + }); + cm.addListener('init', function(evt) { + return engine.internalEvent('init', evt); + }); + cm.addListener('newRule', function(evt) { + return engine.internalEvent('newRule', evt); + }); + _this.log.info('RS | Initialzing http listener'); + args['request-service'] = cm.processRequest; + args['shutdown-function'] = shutDown; + return http(args); + } + }); + }; /* Shuts down the server. @private shutDown() - */ + */ - shutDown = (function(_this) { - return function() { - _this.log.warn('RS | Received shut down command!'); - if (db != null) { - db.shutDown(); - } - if (engine != null) { - engine.shutDown(); - } - return process.exit(); - }; - })(this); + shutDown = function() { + _this.log.warn('RS | Received shut down command!'); + if (db != null) { + db.shutDown(); + } + if (engine != null) { + engine.shutDown(); + } + return process.exit(); + }; /* - *# Process Commands + ## Process Commands When the server is run as a child process, this function handles messages from the parent process (e.g. the testing suite) - */ + */ + process.on('message', function(cmd) { return typeof procCmds[cmd] === "function" ? procCmds[cmd]() : void 0; diff --git a/testing/files/testObjects.json b/testing/files/testObjects.json index 451cae8..9d23293 100644 --- a/testing/files/testObjects.json +++ b/testing/files/testObjects.json @@ -1,11 +1,13 @@ { "events": { - "evt1":{ - "eventid": "test_1", - "event": "test_1" + "eventOne":{ + "event": "test_1", + "payload": { + "property": "test_1", + "nestedProperty": "really nested" + } }, - "evt2":{ - "eventid": "test_2", + "eventTwo":{ "event": "test_2" } }, diff --git a/testing/test_components-manager.coffee b/testing/test_components-manager.coffee index 1bfcde1..bd2975a 100644 --- a/testing/test_components-manager.coffee +++ b/testing/test_components-manager.coffee @@ -22,19 +22,31 @@ db = require path.join '..', 'js-coffee', 'persistence' db opts -# exports.testListener = ( test ) -> -# test.expect 2 +exports.testListener = ( test ) => + test.expect 2 -# oRuleOne = objects.rules.ruleOne -# oRuleTwo = objects.rules.ruleOne -# db.storeRule 'test-cm-rule', JSON.stringify oRuleOne -# cm.addListener 'init', ( evt ) => -# test.deepEqual evt, oRuleOne, 'Event is not the same!' -# console.log 'got and checked init' + oUser = objects.users.userOne + oRuleOne = objects.rules.ruleOne + oRuleTwo = objects.rules.ruleTwo + db.storeRule 'test-cm-rule', JSON.stringify oRuleOne + request = + command: 'forge_rule' + payload: oRuleTwo -# cm.addListener 'newRule', ( evt ) => -# console.log 'new rule listener added' -# test.deepEqual evt, oRuleTwo, 'Event is not the same!' -# test.done() -# cm.processRequest oUser, oRuleTwo, ( answ ) => -# console.log answ + cm.addListener 'newRule', ( evt ) => + console.log 'got new rule!' + test.deepEqual evt, oRuleTwo, 'Event is not the same!' + test.done() + + console.log 'new rule listener added' + cm.addListener 'init', ( evt ) => + test.deepEqual evt, oRuleOne, 'Event is not the same!' + console.log 'got and checked init' + + cm.processRequest oUser, request, ( answ ) => + console.log answ + if answ.code isnt 200 + test.ok false, 'testListener failed: ' + answ.message + test.done() + + console.log 'init listener added' diff --git a/testing/test_persistence.coffee b/testing/test_persistence.coffee index 831b4d8..cb3072a 100644 --- a/testing/test_persistence.coffee +++ b/testing/test_persistence.coffee @@ -46,7 +46,7 @@ exports.Availability = testPurgeQueue: ( test ) => test.expect 2 - db.pushEvent objects.events.evt1 + db.pushEvent objects.events.eventOne db.purgeEventQueue() db.popEvent ( err, obj ) => test.ifError err, 'Error during pop after purging!' @@ -85,13 +85,13 @@ exports.EventQueue = testNonEmptyPopping: ( test ) => test.expect 3 - db.pushEvent objects.events.evt1 + db.pushEvent objects.events.eventOne db.popEvent ( err, obj ) => test.ifError err, 'Error during non-empty popping!' test.notStrictEqual obj, null, 'There was no event in the queue!' - test.deepEqual objects.events.evt1, obj, + test.deepEqual objects.events.eventOne, obj, 'Wrong event in queue!' test.done() @@ -105,15 +105,15 @@ exports.EventQueue = test.done() - db.pushEvent objects.events.evt1 - db.pushEvent objects.events.evt2 + db.pushEvent objects.events.eventOne + db.pushEvent objects.events.eventTwo # eventually it would be wise to not care about the order of events db.popEvent ( err, obj ) => test.ifError err, 'Error during multiple push and pop!' test.notStrictEqual obj, null, 'There was no event in the queue!' - test.deepEqual objects.events.evt1, obj, + test.deepEqual objects.events.eventOne, obj, 'Wrong event in queue!' forkEnds() db.popEvent ( err, obj ) => @@ -121,7 +121,7 @@ exports.EventQueue = 'Error during multiple push and pop!' test.notStrictEqual obj, null, 'There was no event in the queue!' - test.deepEqual objects.events.evt2, obj, + test.deepEqual objects.events.eventTwo, obj, 'Wrong event in queue!' forkEnds() diff --git a/testing/test_request-handler.coffee b/testing/test_request-handler.coffee index cd4e952..3387dae 100644 --- a/testing/test_request-handler.coffee +++ b/testing/test_request-handler.coffee @@ -21,6 +21,14 @@ opts = opts[ 'db-port' ] = 6379 db = require path.join '..', 'js-coffee', 'persistence' db opts +rh = require path.join '..', 'js-coffee', 'request-handler' +args = + logger: log +args[ 'request-service' ] = ( usr, obj, cb ) -> + test.ok false, 'testEvent should not cause a service request call' +args[ 'shutdown-function' ] = () -> + test.ok false, 'testEvent should not cause a system shutdown' +rh args createRequest = ( query, origUrl ) -> req = new events.EventEmitter() @@ -56,13 +64,6 @@ createResponse = ( cb ) -> code = 200 cb code, msg -exports.setUp = ( cb ) => - @rh = require path.join '..', 'js-coffee', 'request-handler' - cb() - -exports.tearDown = ( cb ) => - cb() - exports.session = setUp: ( cb ) => @oUsr = objects.users.userOne @@ -76,14 +77,6 @@ exports.session = testLoginAndOut: ( test ) => test.expect 6 - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args - req = createRequest() resp = createResponse ( code, msg ) => @@ -103,23 +96,16 @@ exports.session = test.strictEqual code, 200, 'Logout failed' test.strictEqual req.session.user, null, 'User not removed from session' test.done() - @rh.handleLogout req, resp # set the handler to listening - @rh.handleLogin req, resp # set the handler to listening + rh.handleLogout req, resp # set the handler to listening + rh.handleLogin req, resp # set the handler to listening postRequestData req, qs.stringify @oUsr # emit the data post event - @rh.handleLogin req, resp # set the handler to listening + rh.handleLogin req, resp # set the handler to listening postRequestData req, qs.stringify @oUsr # emit the data post event testWrongLogin: ( test ) => test.expect 2 - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args req = createRequest() resp = createResponse ( code, msg ) => @@ -130,7 +116,7 @@ exports.session = usr = username: @oUsr.username password: 'wrongpassword' - @rh.handleLogin req, resp # set the handler to listening + rh.handleLogin req, resp # set the handler to listening postRequestData req, qs.stringify usr # emit the data post event exports.events = @@ -140,18 +126,8 @@ exports.events = testCorrectEvent: ( test ) => test.expect 2 - - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args - oEvt = - event: 'unittest' - data: 'a lot of data' + oEvt = objects.events.eventOne semaphore = 2 fPopEvent = () => @@ -168,21 +144,13 @@ exports.events = if --semaphore is 0 test.done() - @rh.handleEvent req, resp # set the handler to listening + rh.handleEvent req, resp # set the handler to listening postRequestData req, JSON.stringify oEvt # emit the data post event setTimeout fPopEvent, 200 # try to fetch the db entry testIncorrectEvent: ( test ) => test.expect 2 - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args - oEvt = data: 'event misses event type property' @@ -200,21 +168,13 @@ exports.events = if --semaphore is 0 test.done() - @rh.handleEvent req, resp # set the handler to listening + rh.handleEvent req, resp # set the handler to listening postRequestData req, qs.stringify oEvt # emit the data post event setTimeout fPopEvent, 200 # try to fetch the db entry exports.testLoginOrPage = ( test ) => test.expect 3 - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args - req = createRequest() req.query = page: 'forge_event' @@ -238,28 +198,19 @@ exports.testLoginOrPage = ( test ) => test.ok msg.indexOf( 'document.title = \'Error!\'' ) > 0, 'Didn\' get forge page?' test.done() - @rh.handleForge req, resp # set the handler to listening - @rh.handleForge req, resp # set the handler to listening - @rh.handleForge req, resp # set the handler to listening + rh.handleForge req, resp # set the handler to listening + rh.handleForge req, resp # set the handler to listening + rh.handleForge req, resp # set the handler to listening exports.testUserCommandsNoLogin = ( test ) => test.expect 1 - args = - logger: log - args[ 'request-service' ] = ( usr, obj, cb ) -> - test.ok false, 'testEvent should not cause a service request call' - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args - - req = createRequest() resp = createResponse ( code, msg ) => test.strictEqual code, 401, 'Login did not fail?' test.done() - @rh.handleUserCommand req, resp # set the handler to listening + rh.handleUserCommand req, resp # set the handler to listening exports.testUserCommands = ( test ) => @@ -283,15 +234,13 @@ exports.testUserCommands = ( test ) => args[ 'request-service' ] = ( usr, obj, cb ) -> test.ok true, 'Yay we got the request!' cb oRespData - args[ 'shutdown-function' ] = () -> - test.ok false, 'testEvent should not cause a system shutdown' - @rh args + rh args req = createLoggedInRequest() resp = createResponse ( code, msg ) => test.strictEqual code, 200, 'Service wasn\'t happy with our request' test.deepEqual msg, oRespData, 'Service didn\'t return expected' test.done() - @rh.handleUserCommand req, resp # set the handler to listening + rh.handleUserCommand req, resp # set the handler to listening postRequestData req, qs.stringify oReqData # emit the data post event diff --git a/webpages/handlers/coffee/forge_action_invoker.coffee b/webpages/handlers/coffee/forge_action_invoker.coffee index 5d3eff7..a3a95a3 100644 --- a/webpages/handlers/coffee/forge_action_invoker.coffee +++ b/webpages/handlers/coffee/forge_action_invoker.coffee @@ -55,12 +55,13 @@ fOnLoad = () -> if val isnt "" listParams.push val obj = - id: $( '#input_id' ).val() command: 'forge_action_invoker' - lang: $( '#editor_mode' ).val() - public: $( '#is_public' ).is ':checked' - data: editor.getValue() - params: JSON.stringify listParams + payload: + id: $( '#input_id' ).val() + lang: $( '#editor_mode' ).val() + public: $( '#is_public' ).is ':checked' + data: editor.getValue() + params: JSON.stringify listParams $.post( '/usercommand', obj ) .done ( data ) -> $( '#info' ).text data.message diff --git a/webpages/handlers/coffee/forge_event_poller.coffee b/webpages/handlers/coffee/forge_event_poller.coffee index 7853bb4..b84dbd6 100644 --- a/webpages/handlers/coffee/forge_event_poller.coffee +++ b/webpages/handlers/coffee/forge_event_poller.coffee @@ -55,12 +55,13 @@ fOnLoad = () -> if val isnt "" listParams.push val obj = - id: $( '#input_id' ).val() command: 'forge_event_poller' - lang: $( '#editor_mode' ).val() - public: $( '#is_public' ).is ':checked' - data: editor.getValue() - params: JSON.stringify listParams + payload: + id: $( '#input_id' ).val() + lang: $( '#editor_mode' ).val() + public: $( '#is_public' ).is ':checked' + data: editor.getValue() + params: JSON.stringify listParams $.post( '/usercommand', obj ) .done ( data ) -> $( '#info' ).text data.message diff --git a/webpages/handlers/coffee/forge_rule.coffee b/webpages/handlers/coffee/forge_rule.coffee index 092f7b0..979a883 100644 --- a/webpages/handlers/coffee/forge_rule.coffee +++ b/webpages/handlers/coffee/forge_rule.coffee @@ -168,25 +168,23 @@ fOnLoad = () -> throw new Error "'#{ key }' missing for '#{ id }'" params[key] = val ap[id] = params - acts = {} + acts = [] $( '#selected_actions .title' ).each () -> - arrAct = $( this ).text().split ' -> ' - if not acts[arrAct[0]] - acts[arrAct[0]] = - functions: [] - acts[arrAct[0]].functions.push arrAct[1] + acts.push $( this ).text() - arrEP = $( '#select_event option:selected' ).val().split ' -> ' obj = command: 'forge_rule' - id: $( '#input_id' ).val() - event: JSON.stringify - module: arrEP[0] - function: arrEP[1] - event_params: JSON.stringify ep - conditions: JSON.stringify {} #TODO Add conditions! - actions: JSON.stringify acts - action_params: JSON.stringify ap + payload: + id: $( '#input_id' ).val() + event: $( '#select_event option:selected' ).val() + event_params: ep + conditions: {} #TODO Add conditions! + actions: acts + action_params: ap + # event_params: JSON.stringify ep + # conditions: JSON.stringify {} #TODO Add conditions! + # actions: JSON.stringify acts + # action_params: JSON.stringify ap $.post( '/usercommand', obj ) .done ( data ) -> $( '#info' ).text data.message diff --git a/webpages/handlers/js/admin.js b/webpages/handlers/js/admin.js index 8d7b0aa..d133294 100644 --- a/webpages/handlers/js/admin.js +++ b/webpages/handlers/js/admin.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; diff --git a/webpages/handlers/js/error.js b/webpages/handlers/js/error.js index c97b3f0..2bb94fc 100644 --- a/webpages/handlers/js/error.js +++ b/webpages/handlers/js/error.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_action_invoker.js b/webpages/handlers/js/forge_action_invoker.js index 9b1832e..2819f3a 100644 --- a/webpages/handlers/js/forge_action_invoker.js +++ b/webpages/handlers/js/forge_action_invoker.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; @@ -66,12 +66,14 @@ } }); obj = { - id: $('#input_id').val(), command: 'forge_action_invoker', - lang: $('#editor_mode').val(), - "public": $('#is_public').is(':checked'), - data: editor.getValue(), - params: JSON.stringify(listParams) + payload: { + id: $('#input_id').val(), + lang: $('#editor_mode').val(), + "public": $('#is_public').is(':checked'), + data: editor.getValue(), + params: JSON.stringify(listParams) + } }; return $.post('/usercommand', obj).done(function(data) { $('#info').text(data.message); diff --git a/webpages/handlers/js/forge_event.js b/webpages/handlers/js/forge_event.js index 4951d18..90e5936 100644 --- a/webpages/handlers/js/forge_event.js +++ b/webpages/handlers/js/forge_event.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_event_poller.js b/webpages/handlers/js/forge_event_poller.js index 533d9ae..03f5f16 100644 --- a/webpages/handlers/js/forge_event_poller.js +++ b/webpages/handlers/js/forge_event_poller.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; @@ -66,12 +66,14 @@ } }); obj = { - id: $('#input_id').val(), command: 'forge_event_poller', - lang: $('#editor_mode').val(), - "public": $('#is_public').is(':checked'), - data: editor.getValue(), - params: JSON.stringify(listParams) + payload: { + id: $('#input_id').val(), + lang: $('#editor_mode').val(), + "public": $('#is_public').is(':checked'), + data: editor.getValue(), + params: JSON.stringify(listParams) + } }; return $.post('/usercommand', obj).done(function(data) { $('#info').text(data.message); diff --git a/webpages/handlers/js/forge_rule.js b/webpages/handlers/js/forge_rule.js index 52a077b..3c96c98 100644 --- a/webpages/handlers/js/forge_rule.js +++ b/webpages/handlers/js/forge_rule.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad; @@ -183,7 +183,7 @@ } }); return $('#but_submit').click(function() { - var acts, ap, arrEP, ep, err; + var acts, ap, ep, err; try { if ($('#select_event option:selected').length === 0) { throw new Error('Please create an Event Poller first!'); @@ -220,29 +220,20 @@ }); return ap[id] = params; }); - acts = {}; + acts = []; $('#selected_actions .title').each(function() { - var arrAct; - arrAct = $(this).text().split(' -> '); - if (!acts[arrAct[0]]) { - acts[arrAct[0]] = { - functions: [] - }; - } - return acts[arrAct[0]].functions.push(arrAct[1]); + return acts.push($(this).text()); }); - arrEP = $('#select_event option:selected').val().split(' -> '); obj = { command: 'forge_rule', - id: $('#input_id').val(), - event: JSON.stringify({ - module: arrEP[0], - "function": arrEP[1] - }), - event_params: JSON.stringify(ep), - conditions: JSON.stringify({}), - actions: JSON.stringify(acts), - action_params: JSON.stringify(ap) + payload: { + id: $('#input_id').val(), + event: $('#select_event option:selected').val(), + event_params: ep, + conditions: {}, + actions: acts, + action_params: ap + } }; return $.post('/usercommand', obj).done(function(data) { $('#info').text(data.message); diff --git a/webpages/handlers/js/login.js b/webpages/handlers/js/login.js index 348fc68..0f62b66 100644 --- a/webpages/handlers/js/login.js +++ b/webpages/handlers/js/login.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.7.1 +// Generated by CoffeeScript 1.6.3 (function() { var fOnLoad;