Updated Events - use glob for finding nested modules/etc.

This commit is contained in:
Bryan Ashby 2017-06-22 22:19:34 -06:00
parent b7ad850bdc
commit 7343ab2ff2
9 changed files with 96 additions and 67 deletions

View File

@ -9,9 +9,7 @@
const conf = require('./config.js'); const conf = require('./config.js');
const logger = require('./logger.js'); const logger = require('./logger.js');
const database = require('./database.js'); const database = require('./database.js');
const clientConns = require('./client_connections.js');
const resolvePath = require('./misc_util.js').resolvePath; const resolvePath = require('./misc_util.js').resolvePath;
const events = require('./events.js');
// deps // deps
const async = require('async'); const async = require('async');
@ -88,8 +86,6 @@ function main() {
} }
], ],
function complete(err) { function complete(err) {
events.registerModules();
// note this is escaped: // note this is escaped:
fs.readFile(paths.join(__dirname, '../misc/startup_banner.asc'), 'utf8', (err, banner) => { fs.readFile(paths.join(__dirname, '../misc/startup_banner.asc'), 'utf8', (err, banner) => {
console.info(ENIGMA_COPYRIGHT); console.info(ENIGMA_COPYRIGHT);
@ -114,11 +110,12 @@ function shutdownSystem() {
async.series( async.series(
[ [
function closeConnections(callback) { function closeConnections(callback) {
const activeConnections = clientConns.getActiveConnections(); const ClientConns = require('./client_connections.js');
const activeConnections = ClientConns.getActiveConnections();
let i = activeConnections.length; let i = activeConnections.length;
while(i--) { while(i--) {
activeConnections[i].term.write('\n\nServer is shutting down NOW! Disconnecting...\n\n'); activeConnections[i].term.write('\n\nServer is shutting down NOW! Disconnecting...\n\n');
clientConns.removeClient(activeConnections[i]); ClientConns.removeClient(activeConnections[i]);
} }
callback(null); callback(null);
}, },
@ -240,6 +237,9 @@ function initialize(cb) {
function readyMessageNetworkSupport(callback) { function readyMessageNetworkSupport(callback) {
return require('./msg_network.js').startup(callback); return require('./msg_network.js').startup(callback);
}, },
function readyEvents(callback) {
return require('./events.js').startup(callback);
},
function listenConnections(callback) { function listenConnections(callback) {
return require('./listening_server.js').startup(callback); return require('./listening_server.js').startup(callback);
}, },

View File

@ -3,7 +3,7 @@
// ENiGMA½ // ENiGMA½
const logger = require('./logger.js'); const logger = require('./logger.js');
const events = require('./events.js'); const Events = require('./events.js');
// deps // deps
const _ = require('lodash'); const _ = require('lodash');
@ -77,7 +77,7 @@ function addNewClient(client, clientSock) {
client.log.info(connInfo, 'Client connected'); client.log.info(connInfo, 'Client connected');
events.emit('codes.l33t.enigma.system.connected', {'client': client}); Events.emit('codes.l33t.enigma.system.connected', { client : client, connectionCount : clientConnections.length } );
return id; return id;
} }
@ -97,7 +97,7 @@ function removeClient(client) {
'Client disconnected' 'Client disconnected'
); );
events.emit('codes.l33t.enigma.system.disconnected', {'client': client}); Events.emit('codes.l33t.enigma.system.disconnected', { client : client, connectionCount : clientConnections.length } );
} }
} }

View File

@ -3,7 +3,7 @@
// ENiGMA½ // ENiGMA½
const ansi = require('./ansi_term.js'); const ansi = require('./ansi_term.js');
const events = require('./events.js'); const Events = require('./events.js');
// deps // deps
const async = require('async'); const async = require('async');
@ -177,7 +177,7 @@ function connectEntry(client, nextMenu) {
displayBanner(term); displayBanner(term);
// fire event // fire event
events.emit('codes.l33t.enigma.system.term_detected', {'client': client}); Events.emit('codes.l33t.enigma.system.term_detected', { client : client } );
setTimeout( () => { setTimeout( () => {
return client.menuStack.goto(nextMenu); return client.menuStack.goto(nextMenu);

View File

@ -1,50 +1,73 @@
/* jslint node: true */ /* jslint node: true */
'use strict'; 'use strict';
const Config = require('./config.js'); const paths = require('path');
const fs = require('fs'); const events = require('events');
const path = require('path'); const Log = require('./logger.js').log;
const events = require('events');
const logger = require('./logger.js');
var eventEmitter = new events.EventEmitter(); // deps
const _ = require('lodash');
const async = require('async');
const glob = require('glob');
var self = module.exports = { module.exports = new class Events extends events.EventEmitter {
emit: function(eventName, args) { constructor() {
logger.log.debug("Emit "+eventName); super();
eventEmitter.emit(eventName, args); }
},
on: function(eventName, listener) {
logger.log.debug("Register listener for "+eventName);
eventEmitter.on(eventName, listener);
},
remove: function(eventName, listener) {
logger.log.debug("Remove listener for "+eventName);
eventEmitter.removeListener(eventName, listener);
},
registerModules: function() {
const moduleUtil = require('./module_util.js');
moduleUtil.getModulePaths().forEach(function(modulePath) { addListener(event, listener) {
var mods = fs.readdirSync(modulePath); Log.trace( { event : event }, 'Registering event listener');
mods.forEach(function(item) { return super.addListener(event, listener);
var modPath = modulePath+item; }
if (item.substr(item.length-3) != '.js') {
modPath += path.sep+item+'.js'; emit(event, ...args) {
Log.trace( { event : event }, 'Emitting event');
return super.emit(event, args);
}
on(event, listener) {
Log.trace( { event : event }, 'Registering event listener');
return super.on(event, listener);
}
once(event, listener) {
Log.trace( { event : event }, 'Registering single use event listener');
return super.once(event, listener);
}
removeListener(event, listener) {
Log.trace( { event : event }, 'Removing listener');
return super.removeListener(event, listener);
}
startup(cb) {
async.each(require('./module_util.js').getModulePaths(), (modulePath, nextPath) => {
glob('*{.js,/*.js}', { cwd : modulePath }, (err, files) => {
if(err) {
return nextPath(err);
} }
if (fs.existsSync(modPath)) {
var module = require(modPath);
if (module.registerEvents !== undefined) { async.each(files, (moduleName, nextModule) => {
logger.log.debug(modPath+" calling registerEvents function"); modulePath = paths.join(modulePath, moduleName);
module.registerEvents();
} else { try {
logger.log.debug(modPath+" has no registerEvents function"); const mod = require(modulePath);
if(_.isFunction(mod.registerEvents)) {
// :TODO: ... or just systemInit() / systemShutdown() & mods could call Events.on() / Events.removeListener() ?
mod.registerEvents(this);
}
} catch(e) {
} }
} else {
logger.log.debug(modPath+" - file not found"); return nextModule(null);
} }, err => {
return nextPath(err);
});
}); });
}, err => {
return cb(err);
}); });
} }
} };

View File

@ -101,6 +101,9 @@ function loadModulesForCategory(category, iterator, complete) {
function getModulePaths() { function getModulePaths() {
return [ return [
Config.paths.mods Config.paths.mods,
Config.paths.loginServers,
Config.paths.contentServers,
Config.paths.scannerTossers,
]; ];
} }

View File

@ -297,10 +297,10 @@ function FTNMessageScanTossModule() {
}); });
}, (err, finalSuffix) => { }, (err, finalSuffix) => {
if(finalSuffix) { if(finalSuffix) {
cb(null, paths.join(basePath, fileName + finalSuffix)); return cb(null, paths.join(basePath, fileName + finalSuffix));
} else {
cb(new Error('Could not acquire a bundle filename!'));
} }
return cb(new Error('Could not acquire a bundle filename!'));
}); });
}; };

View File

@ -37,14 +37,16 @@ function userLogin(client, username, password, cb) {
}); });
if(existingClientConnection) { if(existingClientConnection) {
client.log.info( { client.log.info(
existingClientId : existingClientConnection.session.id, {
username : user.username, existingClientId : existingClientConnection.session.id,
userId : user.userId }, username : user.username,
userId : user.userId
},
'Already logged in' 'Already logged in'
); );
var existingConnError = new Error('Already logged in as supplied user'); const existingConnError = new Error('Already logged in as supplied user');
existingConnError.existingConn = true; existingConnError.existingConn = true;
// :TODO: We should use EnigError & pass existing connection as second param // :TODO: We should use EnigError & pass existing connection as second param
@ -61,24 +63,24 @@ function userLogin(client, username, password, cb) {
[ [
function setTheme(callback) { function setTheme(callback) {
setClientTheme(client, user.properties.theme_id); setClientTheme(client, user.properties.theme_id);
callback(null); return callback(null);
}, },
function updateSystemLoginCount(callback) { function updateSystemLoginCount(callback) {
StatLog.incrementSystemStat('login_count', 1, callback); return StatLog.incrementSystemStat('login_count', 1, callback);
}, },
function recordLastLogin(callback) { function recordLastLogin(callback) {
StatLog.setUserStat(user, 'last_login_timestamp', StatLog.now, callback); return StatLog.setUserStat(user, 'last_login_timestamp', StatLog.now, callback);
}, },
function updateUserLoginCount(callback) { function updateUserLoginCount(callback) {
StatLog.incrementUserStat(user, 'login_count', 1, callback); return StatLog.incrementUserStat(user, 'login_count', 1, callback);
}, },
function recordLoginHistory(callback) { function recordLoginHistory(callback) {
const LOGIN_HISTORY_MAX = 200; // history of up to last 200 callers const LOGIN_HISTORY_MAX = 200; // history of up to last 200 callers
StatLog.appendSystemLogEntry('user_login_history', user.userId, LOGIN_HISTORY_MAX, StatLog.KeepType.Max, callback); return StatLog.appendSystemLogEntry('user_login_history', user.userId, LOGIN_HISTORY_MAX, StatLog.KeepType.Max, callback);
} }
], ],
function complete(err) { err => {
cb(err); return cb(err);
} }
); );
}); });

View File

@ -45,7 +45,8 @@
"uuid-parse": "^1.0.0", "uuid-parse": "^1.0.0",
"ws" : "^3.0.0", "ws" : "^3.0.0",
"graceful-fs" : "^4.1.11", "graceful-fs" : "^4.1.11",
"exiftool" : "^0.0.3" "exiftool" : "^0.0.3",
"node-glob" : "^1.2.0"
}, },
"devDependencies": {}, "devDependencies": {},
"engines": { "engines": {