Refactor and rename of MRC client and multiplexer

This commit is contained in:
David Stephens 2019-05-22 23:43:41 +01:00
parent 92528fc16f
commit 9f4f1fca13
2 changed files with 152 additions and 129 deletions

View File

@ -4,12 +4,11 @@
// ENiGMA½ // ENiGMA½
const Log = require('./logger.js').log; const Log = require('./logger.js').log;
const { MenuModule } = require('./menu_module.js'); const { MenuModule } = require('./menu_module.js');
const { Errors } = require('./enig_error.js');
const { const {
pipeToAnsi pipeToAnsi
} = require('./color_codes.js'); } = require('./color_codes.js');
const stringFormat = require('./string_format.js'); const stringFormat = require('./string_format.js');
const StringUtil = require('./string_util.js') const StringUtil = require('./string_util.js');
// deps // deps
const _ = require('lodash'); const _ = require('lodash');
@ -23,7 +22,7 @@ exports.moduleInfo = {
author : 'RiPuk', author : 'RiPuk',
packageName : 'codes.l33t.enigma.mrc.client', packageName : 'codes.l33t.enigma.mrc.client',
// Whilst this module was put together by me (RiPuk), it should be noted that a lot of the ideas (and even some code snippets) were // Whilst this module was put together by me (RiPuk), it should be noted that a lot of the ideas (and even some code snippets) were
// borrowed from the Synchronet implementation of MRC by echicken. So...thanks, your code was very helpful in putting this together. // borrowed from the Synchronet implementation of MRC by echicken. So...thanks, your code was very helpful in putting this together.
// Source at http://cvs.synchro.net/cgi-bin/viewcvs.cgi/xtrn/mrc/. // Source at http://cvs.synchro.net/cgi-bin/viewcvs.cgi/xtrn/mrc/.
}; };
@ -45,7 +44,7 @@ var MciViewIds = {
}; };
// TODO: this is a bit shit, could maybe do it with an ansi instead // TODO: this is a bit shit, could maybe do it with an ansi instead
const helpText = ` const helpText = `
General Chat: General Chat:
@ -73,7 +72,7 @@ exports.getModule = class mrcModule extends MenuModule {
this.log = Log.child( { module : 'MRC' } ); this.log = Log.child( { module : 'MRC' } );
this.config = Object.assign({}, _.get(options, 'menuConfig.config'), { extraArgs : options.extraArgs }); this.config = Object.assign({}, _.get(options, 'menuConfig.config'), { extraArgs : options.extraArgs });
this.state = { this.state = {
socket: '', socket: '',
alias: this.client.user.username, alias: this.client.user.username,
@ -82,17 +81,17 @@ exports.getModule = class mrcModule extends MenuModule {
nicks: [], nicks: [],
last_ping: 0 last_ping: 0
}; };
this.menuMethods = { this.menuMethods = {
sendChatMessage : (formData, extraArgs, cb) => { sendChatMessage : (formData, extraArgs, cb) => {
const inputAreaView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.inputArea); const inputAreaView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.inputArea);
const inputData = inputAreaView.getData(); const inputData = inputAreaView.getData();
this.processSentMessage(inputData); this.processOutgoingMessage(inputData);
inputAreaView.clearText(); inputAreaView.clearText();
return cb(null); return cb(null);
}, },
@ -109,7 +108,7 @@ exports.getModule = class mrcModule extends MenuModule {
return cb(null); return cb(null);
} }
} };
} }
mciReady(mciData, cb) { mciReady(mciData, cb) {
@ -129,7 +128,7 @@ exports.getModule = class mrcModule extends MenuModule {
(callback) => { (callback) => {
const connectOpts = { const connectOpts = {
port : 5000, port : 5000,
host : "localhost", host : 'localhost',
}; };
// connect to multiplexer // connect to multiplexer
@ -143,7 +142,7 @@ exports.getModule = class mrcModule extends MenuModule {
// send register to central MRC and get stats every 60s // send register to central MRC and get stats every 60s
setInterval(function () { setInterval(function () {
self.sendHeartbeat(); self.sendHeartbeat();
self.sendServerCommand('STATS') self.sendServerMessage('STATS');
}, 60000); }, 60000);
}); });
@ -159,28 +158,36 @@ exports.getModule = class mrcModule extends MenuModule {
err => { err => {
return cb(err); return cb(err);
} }
); );
}); });
} }
/**
* Adds a message to the chat log on screen
*/
addMessageToChatLog(message) {
const chatLogView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
chatLogView.addText(pipeToAnsi(message));
}
/**
* Processes data received back from the MRC multiplexer
*/
processReceivedMessage(blob) { processReceivedMessage(blob) {
blob.split('\n').forEach( message => { blob.split('\n').forEach( message => {
try { try {
message = JSON.parse(message) message = JSON.parse(message);
} catch (e) { } catch (e) {
return return;
} }
const chatMessageView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
if (message.from_user == 'SERVER') { if (message.from_user == 'SERVER') {
const params = message.body.split(':'); const params = message.body.split(':');
switch (params[0]) { switch (params[0]) {
case 'BANNER': case 'BANNER':
chatMessageView.addText(pipeToAnsi(params[1].replace(/^\s+/, ''))); this.addMessageToChatLog(params[1].replace(/^\s+/, ''));
break; break;
case 'ROOMTOPIC': case 'ROOMTOPIC':
@ -188,13 +195,12 @@ exports.getModule = class mrcModule extends MenuModule {
this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.roomTopic).setText(pipeToAnsi(params[2])); this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.roomTopic).setText(pipeToAnsi(params[2]));
this.state.room = params[1]; this.state.room = params[1];
break; break;
case 'USERLIST': case 'USERLIST':
this.state.nicks = params[1].split(','); this.state.nicks = params[1].split(',');
break; break;
case 'STATS': case 'STATS':
console.log("got stats back")
const stats = params[1].split(' '); const stats = params[1].split(' ');
this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.mrcUsers).setText(stats[2]); this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.mrcUsers).setText(stats[2]);
this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.mrcBbses).setText(stats[0]); this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.mrcBbses).setText(stats[0]);
@ -203,18 +209,25 @@ exports.getModule = class mrcModule extends MenuModule {
break; break;
default: default:
chatMessageView.addText(pipeToAnsi(message.body)); this.addMessageToChatLog(message.body);
break; break;
} }
} else { } else {
if (message.from_user == this.state.alias && message.to_user == "NOTME") { if (message.from_user == this.state.alias && message.to_user == 'NOTME') {
// don't deliver NOTME messages // don't deliver NOTME messages
return; return;
} else { } else {
// if we're here then we want to show it to the user // if we're here then we want to show it to the user
const currentTime = moment().format(this.client.currentTheme.helpers.getTimeFormat()); const currentTime = moment().format(this.client.currentTheme.helpers.getTimeFormat());
chatMessageView.addText(pipeToAnsi("|08" + currentTime + "|00 " + message.body + "|00"));
if (message.to_user == this.state.alias) {
// it's a pm
this.addMessageToChatLog('|08' + currentTime + ' |14PM|00 ' + message.body + '|00');
} else {
// it's not a pm
this.addMessageToChatLog('|08' + currentTime + '|00 ' + message.body + '|00');
}
} }
} }
@ -222,14 +235,17 @@ exports.getModule = class mrcModule extends MenuModule {
}); });
} }
processSentMessage(message, to_user) { /**
* Receives the message input from the user and does something with it based on what it is
*/
processOutgoingMessage(message, to_user) {
if (message.startsWith('/')) { if (message.startsWith('/')) {
this.processSlashCommand(message) this.processSlashCommand(message);
} else { } else {
if (message == '') { if (message == '') {
this.sendServerCommand('STATS'); this.sendServerMessage('STATS');
return; return;
} }
@ -244,7 +260,8 @@ exports.getModule = class mrcModule extends MenuModule {
'|00|10<|02{fromUserName}|10>|00 |03{message}|00'; '|00|10<|02{fromUserName}|10>|00 |03{message}|00';
try { try {
this.sendChat(stringFormat(messageFormat, textFormatObj), to_user || ''); const formattedMessage = stringFormat(messageFormat, textFormatObj);
this.sendMessageToMultiplexer(to_user || '', '', this.state.room, formattedMessage);
} catch(e) { } catch(e) {
this.client.log.warn( { error : e.message }, 'MRC error'); this.client.log.warn( { error : e.message }, 'MRC error');
} }
@ -252,60 +269,63 @@ exports.getModule = class mrcModule extends MenuModule {
} }
/**
* Processes a message that begins with a slash
*/
processSlashCommand(message) { processSlashCommand(message) {
// get the chat log view in case we need it // get the chat log view in case we need it
const chatLogView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog) const chatLogView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
const cmd = message.split(' '); const cmd = message.split(' ');
cmd[0] = cmd[0].substr(1).toLowerCase(); cmd[0] = cmd[0].substr(1).toLowerCase();
switch (cmd[0]) { switch (cmd[0]) {
case 'pm': case 'pm':
this.processSentMessage(cmd[2], cmd[1]) this.processOutgoingMessage(cmd[2], cmd[1]);
break; break;
case 'rainbow': case 'rainbow':
// this is brutal, but i love it // this is brutal, but i love it
const line = message.replace(/^\/rainbow\s/, '').split(' ').reduce(function (a, c) { const line = message.replace(/^\/rainbow\s/, '').split(' ').reduce(function (a, c) {
var cc = Math.floor((Math.random() * 31) + 1).toString().padStart(2, '0'); const cc = Math.floor((Math.random() * 31) + 1).toString().padStart(2, '0');
a += `|${cc}${c}|00 `; a += `|${cc}${c}|00 `;
return a; return a;
}, '').substr(0, 140).replace(/\\s\|\d*$/, ''); }, '').substr(0, 140).replace(/\\s\|\d*$/, '');
this.processSentMessage(line); this.processOutgoingMessage(line);
break; break;
case 'l33t': case 'l33t':
this.processSentMessage(StringUtil.stylizeString(message.substr(5), 'l33t')); this.processOutgoingMessage(StringUtil.stylizeString(message.substr(5), 'l33t'));
break; break;
case 'kewl': case 'kewl':
const text_modes = Array('f','v','V','i','M'); const text_modes = Array('f','v','V','i','M');
const mode = text_modes[Math.floor(Math.random() * text_modes.length)]; const mode = text_modes[Math.floor(Math.random() * text_modes.length)];
this.processSentMessage(StringUtil.stylizeString(message.substr(5), mode)); this.processOutgoingMessage(StringUtil.stylizeString(message.substr(5), mode));
break; break;
case 'whoon': case 'whoon':
this.sendServerCommand('WHOON'); this.sendServerMessage('WHOON');
break; break;
case 'motd': case 'motd':
this.sendServerCommand('MOTD'); this.sendServerMessage('MOTD');
break; break;
case 'meetups': case 'meetups':
this.sendServerCommand('MEETUPS'); this.sendServerMessage('MEETUPS');
break; break;
case 'bbses': case 'bbses':
this.sendServerCommand('CONNECTED'); this.sendServerMessage('CONNECTED');
break; break;
case 'topic': case 'topic':
this.sendServerCommand(`NEWTOPIC:${this.state.room}:${message.substr(7)}`) this.sendServerMessage(`NEWTOPIC:${this.state.room}:${message.substr(7)}`);
break; break;
case 'info': case 'info':
this.sendServerCommand(`INFO ${cmd[1]}`); this.sendServerMessage(`INFO ${cmd[1]}`);
break; break;
case 'join': case 'join':
@ -313,11 +333,11 @@ exports.getModule = class mrcModule extends MenuModule {
break; break;
case 'chatters': case 'chatters':
this.sendServerCommand('CHATTERS'); this.sendServerMessage('CHATTERS');
break; break;
case 'rooms': case 'rooms':
this.sendServerCommand('LIST'); this.sendServerMessage('LIST');
break; break;
case 'clear': case 'clear':
@ -325,20 +345,23 @@ exports.getModule = class mrcModule extends MenuModule {
break; break;
case '?': case '?':
chatLogView.addText(helpText); this.addMessageToChatLog(helpText);
break; break;
default: default:
break; break;
} }
// just do something to get the cursor back to the right place ¯\_(ツ)_/¯ // just do something to get the cursor back to the right place ¯\_(ツ)_/¯
this.sendServerCommand('STATS'); this.sendServerMessage('STATS');
}; }
sendMessage(to_user, to_site, to_room, body) { /**
* Creates a json object, stringifies it and sends it to the MRC multiplexer
*/
sendMessageToMultiplexer(to_user, to_site, to_room, body) {
const message = { const message = {
from_user: this.state.alias, from_user: this.state.alias,
@ -353,36 +376,43 @@ exports.getModule = class mrcModule extends MenuModule {
// TODO: check socket still exists here // TODO: check socket still exists here
this.state.socket.write(JSON.stringify(message) + '\n'); this.state.socket.write(JSON.stringify(message) + '\n');
};
sendServerCommand(command, to_site) {
Log.debug({ module: 'mrc', command: command }, 'Sending server command');
this.sendMessage('SERVER', to_site || '', this.state.room, command);
};
sendHeartbeat() {
this.sendServerCommand('IAMHERE');
} }
/**
* Sends an MRC 'server' message
*/
sendServerMessage(command, to_site) {
Log.debug({ module: 'mrc', command: command }, 'Sending server command');
this.sendMessageToMultiplexer('SERVER', to_site || '', this.state.room, command);
}
/**
* Sends a heartbeat to the MRC server
*/
sendHeartbeat() {
this.sendServerMessage('IAMHERE');
}
/**
* Joins a room, unsurprisingly
*/
joinRoom(room) { joinRoom(room) {
// room names are displayed with a # but referred to without. confusing. // room names are displayed with a # but referred to without. confusing.
room = room.replace(/^#/, ''); room = room.replace(/^#/, '');
this.state.room = room; this.state.room = room;
this.sendServerCommand(`NEWROOM:${this.state.room}:${room}`); this.sendServerMessage(`NEWROOM:${this.state.room}:${room}`);
this.sendServerCommand('USERLIST') this.sendServerMessage('USERLIST');
} }
/**
* Things that happen when a local user connects to the MRC multiplexer
*/
clientConnect() { clientConnect() {
this.sendServerCommand('MOTD'); this.sendServerMessage('MOTD');
this.joinRoom('lobby'); this.joinRoom('lobby');
this.sendServerCommand('STATS'); this.sendServerMessage('STATS');
this.sendHeartbeat(); this.sendHeartbeat();
} }
sendChat(message, to_user) {
this.sendMessage(to_user || '', '', this.state.room, message)
}
}; };

View File

@ -6,8 +6,6 @@ const Log = require('../../logger.js').log;
const { ServerModule } = require('../../server_module.js'); const { ServerModule } = require('../../server_module.js');
const Config = require('../../config.js').get; const Config = require('../../config.js').get;
const { Errors } = require('../../enig_error.js'); const { Errors } = require('../../enig_error.js');
const { wordWrapText } = require('../../word_wrap.js');
const { stripMciColorCodes } = require('../../color_codes.js');
// deps // deps
const net = require('net'); const net = require('net');
@ -41,24 +39,26 @@ exports.getModule = class MrcModule extends ServerModule {
if (!this.enabled) { if (!this.enabled) {
return cb(null); return cb(null);
} }
const self = this;
const config = Config(); const config = Config();
const boardName = config.general.boardName const boardName = config.general.boardName;
const enigmaVersion = "ENiGMA-BBS_" + require('../../../package.json').version const enigmaVersion = 'ENiGMA-BBS_' + require('../../../package.json').version;
const mrcConnectOpts = { const mrcConnectOpts = {
port : 50000, port : 50000,
host : "mrc.bottomlessabyss.net" host : 'mrc.bottomlessabyss.net'
}; };
const handshake = `${boardName}~${enigmaVersion}/${os.platform()}-${os.arch()}/${PROTOCOL_VERSION}` const handshake = `${boardName}~${enigmaVersion}/${os.platform()}-${os.arch()}/${PROTOCOL_VERSION}`;
this.log.debug({ handshake : handshake }, "Handshaking with MRC server") this.log.debug({ handshake : handshake }, 'Handshaking with MRC server');
// create connection to MRC server // create connection to MRC server
this.mrcClient = net.createConnection(mrcConnectOpts, () => { this.mrcClient = net.createConnection(mrcConnectOpts, () => {
this.mrcClient.write(handshake); this.mrcClient.write(handshake);
this.log.info(mrcConnectOpts, 'Connected to MRC server'); this.log.info(mrcConnectOpts, 'Connected to MRC server');
mrcCentralConnection = this.mrcClient mrcCentralConnection = this.mrcClient;
}); });
// do things when we get data from MRC central // do things when we get data from MRC central
@ -66,10 +66,10 @@ exports.getModule = class MrcModule extends ServerModule {
// split on \n to deal with getting messages in batches // split on \n to deal with getting messages in batches
data.toString().split('\n').forEach( item => { data.toString().split('\n').forEach( item => {
if (item == '') return; if (item == '') return;
this.log.debug( { data : item } , `Received data`); this.log.debug( { data : item } , 'Received data');
let message = this.parseMessage(item); let message = this.parseMessage(item);
this.log.debug(message, `Parsed data`); this.log.debug(message, 'Parsed data');
if (message) { if (message) {
this.receiveFromMRC(this.mrcClient, message); this.receiveFromMRC(this.mrcClient, message);
} }
@ -87,20 +87,20 @@ exports.getModule = class MrcModule extends ServerModule {
// start a local server for clients to connect to // start a local server for clients to connect to
this.server = net.createServer( function(socket) { this.server = net.createServer( function(socket) {
socket.setEncoding('ascii'); socket.setEncoding('ascii');
socket.on('data', data => { socket.on('data', data => {
// split on \n to deal with getting messages in batches // split on \n to deal with getting messages in batches
data.toString().split('\n').forEach( item => { data.toString().split('\n').forEach( item => {
if (item == '') return; if (item == '') return;
// save username with socket // save username with socket
if(item.startsWith('--DUDE-ITS--')) { if(item.startsWith('--DUDE-ITS--')) {
connectedSockets.add(socket); connectedSockets.add(socket);
socket.username = item.split('|')[1]; socket.username = item.split('|')[1];
Log.debug( { server : 'MRC', user: socket.username } , `User connected`); Log.debug( { server : 'MRC', user: socket.username } , 'User connected');
} } else {
else { self.receiveFromClient(socket.username, item);
receiveFromClient(socket.username, item);
} }
}); });
@ -112,7 +112,7 @@ exports.getModule = class MrcModule extends ServerModule {
socket.on('error', err => { socket.on('error', err => {
if('ECONNRESET' !== err.code) { // normal if('ECONNRESET' !== err.code) { // normal
console.log(err.message); this.log.error( { error: err.message }, 'MRC error' );
} }
}); });
}); });
@ -156,26 +156,21 @@ exports.getModule = class MrcModule extends ServerModule {
} }
receiveFromMRC(socket, message) { receiveFromMRC(socket, message) {
const config = Config(); const config = Config();
const siteName = slugify(config.general.boardName) const siteName = slugify(config.general.boardName);
if (message.from_user == 'SERVER' && message.body == 'HELLO') { if (message.from_user == 'SERVER' && message.body == 'HELLO') {
// initial server hello, can ignore // initial server hello, can ignore
return;
} else if (message.from_user == 'SERVER' && message.body.toUpperCase() == 'PING') { } else if (message.from_user == 'SERVER' && message.body.toUpperCase() == 'PING') {
// reply to heartbeat // reply to heartbeat
// this.log.debug('Respond to heartbeat'); // this.log.debug('Respond to heartbeat');
let message = sendToMrcServer(socket, 'CLIENT', '', 'SERVER', 'ALL', '', `IMALIVE:${siteName}`); this.sendToMrcServer(socket, 'CLIENT', '', 'SERVER', 'ALL', '', `IMALIVE:${siteName}`);
return message;
} else { } else {
// if not a heartbeat, and we have clients then we need to send something to them // if not a heartbeat, and we have clients then we need to send something to them
//console.log(this.connectedSockets);
this.sendToClient(message); this.sendToClient(message);
return;
} }
} }
@ -197,6 +192,34 @@ exports.getModule = class MrcModule extends ServerModule {
}; };
} }
receiveFromClient(username, message) {
try {
message = JSON.parse(message);
} catch (e) {
Log.debug({ server : 'MRC', user : username, message : message }, 'Dodgy message received from client');
}
this.sendToMrcServer(mrcCentralConnection, message.from_user, message.from_room, message.to_user, message.to_site, message.to_room, message.body);
}
// send a message back to the mrc central server
sendToMrcServer(socket, fromUser, fromRoom, toUser, toSite, toRoom, messageBody) {
const config = Config();
const siteName = slugify(config.general.boardName);
const line = [
fromUser,
siteName,
sanitiseRoomName(fromRoom),
sanitiseName(toUser || ''),
sanitiseName(toSite || ''),
sanitiseRoomName(toRoom || ''),
sanitiseMessage(messageBody)
].join('~') + '~';
Log.debug({ server : 'MRC', data : line }, 'Sending data');
return socket.write(line + '\n');
}
}; };
@ -219,41 +242,11 @@ function sanitiseMessage(message) {
return message.replace(/[^\x20-\x7D]/g, ''); return message.replace(/[^\x20-\x7D]/g, '');
} }
function receiveFromClient(username, message) { function slugify(text) {
try { return text.toString()
message = JSON.parse(message) .replace(/\s+/g, '_') // Replace spaces with _
} catch (e) { .replace(/[^\w\-]+/g, '') // Remove all non-word chars
Log.debug({ server : 'MRC', user : username, message : message }, 'Dodgy message received from client'); .replace(/\-\-+/g, '_') // Replace multiple - with single -
} .replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
sendToMrcServer(mrcCentralConnection, message.from_user, message.from_room, message.to_user, message.to_site, message.to_room, message.body)
}
// send a message back to the mrc central server
function sendToMrcServer(socket, fromUser, fromRoom, toUser, toSite, toRoom, messageBody) {
const config = Config();
const siteName = slugify(config.general.boardName)
const line = [
fromUser,
siteName,
sanitiseRoomName(fromRoom),
sanitiseName(toUser || ''),
sanitiseName(toSite || ''),
sanitiseRoomName(toRoom || ''),
sanitiseMessage(messageBody)
].join('~') + '~';
Log.debug({ server : 'MRC', data : line }, 'Sending data');
return socket.write(line + '\n');
}
function slugify(text)
{
return text.toString()
.replace(/\s+/g, '_') // Replace spaces with _
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '_') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
} }