enigma-bbs/core/mrc.js

576 lines
19 KiB
JavaScript
Raw Normal View History

2019-05-17 23:25:35 +00:00
/* jslint node: true */
'use strict';
// ENiGMA½
const Log = require('./logger.js').log;
const { MenuModule } = require('./menu_module.js');
const {
2019-05-25 23:14:36 +00:00
pipeToAnsi,
stripMciColorCodes
2019-05-17 23:25:35 +00:00
} = require('./color_codes.js');
2019-05-25 23:14:36 +00:00
const stringFormat = require('./string_format.js');
const StringUtil = require('./string_util.js');
const Config = require('./config.js').get;
2019-05-17 23:25:35 +00:00
// deps
const _ = require('lodash');
const async = require('async');
2019-05-25 23:14:36 +00:00
const net = require('net');
const moment = require('moment');
2019-05-17 23:25:35 +00:00
exports.moduleInfo = {
name : 'MRC Client',
desc : 'Connects to an MRC chat server',
author : 'RiPuk',
packageName : 'codes.l33t.enigma.mrc.client',
2019-05-18 23:01:58 +00:00
// 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
2019-05-18 23:01:58 +00:00
// 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/.
2019-05-17 23:25:35 +00:00
};
const FormIds = {
mrcChat : 0,
};
const MciViewIds = {
2019-05-17 23:25:35 +00:00
mrcChat : {
chatLog : 1,
inputArea : 2,
roomName : 3,
roomTopic : 4,
2019-05-18 23:01:58 +00:00
mrcUsers : 5,
mrcBbses : 6,
customRangeStart : 20, // 20+ = customs
2019-05-17 23:25:35 +00:00
}
};
2019-05-20 22:37:32 +00:00
2019-05-20 22:37:32 +00:00
// TODO: this is a bit shit, could maybe do it with an ansi instead
const helpText = `
|15General Chat|08:
|03/|11rooms |08& |03/|11join |03<room> |08- |07List all or join a room
|03/|11pm |03<user> <message> |08- |07Send a private message
2019-05-20 22:37:32 +00:00
----
|03/|11whoon |08- |07Who's on what BBS
|03/|11chatters |08- |07Who's in what room
|03/|11clear |08- |07Clear back buffer
2019-06-08 17:58:21 +00:00
|03/|11topic |03<message> |08- |07Set the room topic
|03/|11bbses |08& |03/|11info <id> |08- |07Info about BBS's connected
|03/|11meetups |08- |07Info about MRC MeetUps
2019-05-20 22:37:32 +00:00
---
2019-06-08 17:58:21 +00:00
|03/|11l33t |03<your message> |08- |07l337 5p34k
|03/|11kewl |03<your message> |08- |07BBS KeWL SPeaK
|03/|11rainbow |03<your message> |08- |07Crazy rainbow text
2019-05-20 22:37:32 +00:00
`;
2019-05-17 23:25:35 +00:00
exports.getModule = class mrcModule extends MenuModule {
constructor(options) {
super(options);
this.log = Log.child( { module : 'MRC' } );
this.config = Object.assign({}, _.get(options, 'menuConfig.config'), { extraArgs : options.extraArgs });
this.config.maxScrollbackLines = this.config.maxScrollbackLines || 500;
2019-05-20 22:37:32 +00:00
this.state = {
socket: '',
alias: this.client.user.username,
room: '',
room_topic: '',
nicks: [],
lastSentMsg : {}, // used for latency est.
2019-05-20 22:37:32 +00:00
};
this.customFormatObj = {
roomName : '',
roomTopic : '',
roomUserCount : 0,
userCount : 0,
boardCount : 0,
roomCount : 0,
2019-06-11 02:12:17 +00:00
latencyMs : 0,
activityLevel : 0,
activityLevelIndicator : ' ',
};
2019-05-17 23:25:35 +00:00
this.menuMethods = {
2019-05-18 23:01:58 +00:00
2019-05-17 23:25:35 +00:00
sendChatMessage : (formData, extraArgs, cb) => {
2019-05-17 23:25:35 +00:00
const inputAreaView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.inputArea);
const inputData = inputAreaView.getData();
2019-05-18 23:01:58 +00:00
this.processOutgoingMessage(inputData);
2019-05-17 23:25:35 +00:00
inputAreaView.clearText();
2019-05-17 23:25:35 +00:00
return cb(null);
2019-05-18 23:01:58 +00:00
},
movementKeyPressed : (formData, extraArgs, cb) => {
const bodyView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
2019-05-18 23:01:58 +00:00
switch(formData.key.name) {
case 'down arrow' : bodyView.scrollDocumentUp(); break;
case 'up arrow' : bodyView.scrollDocumentDown(); break;
case 'page up' : bodyView.keyPressPageUp(); break;
case 'page down' : bodyView.keyPressPageDown(); break;
}
this.viewControllers.mrcChat.switchFocus(MciViewIds.mrcChat.inputArea);
return cb(null);
2019-05-25 23:14:36 +00:00
},
quit : (formData, extraArgs, cb) => {
return this.prevMenu(cb);
},
clearMessages : (formData, extraArgs, cb) => {
this.clearMessages();
return cb(null);
2019-05-17 23:25:35 +00:00
}
};
2019-05-17 23:25:35 +00:00
}
mciReady(mciData, cb) {
super.mciReady(mciData, err => {
if(err) {
return cb(err);
}
async.series(
2019-05-20 22:37:32 +00:00
[
2019-05-17 23:25:35 +00:00
(callback) => {
return this.prepViewController('mrcChat', FormIds.mrcChat, mciData.menu, callback);
},
(callback) => {
return this.validateMCIByViewIds('mrcChat', [ MciViewIds.mrcChat.chatLog, MciViewIds.mrcChat.inputArea ], callback);
},
(callback) => {
const connectOpts = {
2019-06-09 15:19:34 +00:00
port : _.get(Config(), 'chatServers.mrc.multiplexerPort', 5000),
host : 'localhost',
2019-05-17 23:25:35 +00:00
};
// connect to multiplexer
2019-05-20 22:37:32 +00:00
this.state.socket = net.createConnection(connectOpts, () => {
this.client.once('end', () => {
this.quitServer();
});
2019-05-17 23:25:35 +00:00
// handshake with multiplexer
this.state.socket.write(`--DUDE-ITS--|${this.state.alias}\n`);
2019-05-17 23:25:35 +00:00
this.clientConnect();
2019-05-17 23:25:35 +00:00
2019-05-18 23:01:58 +00:00
// send register to central MRC and get stats every 60s
this.heartbeat = setInterval( () => {
this.sendHeartbeat();
this.sendServerMessage('STATS');
2019-05-20 22:37:32 +00:00
}, 60000);
// override idle logout seconds if configured
const idleLogoutSeconds = parseInt(this.config.idleLogoutSeconds);
if(0 === idleLogoutSeconds) {
this.log.debug('Temporary disable idle monitor due to config');
this.client.stopIdleMonitor();
} else if (!isNaN(idleLogoutSeconds) && idleLogoutSeconds >= 60) {
this.log.debug( { idleLogoutSeconds }, 'Temporary override idle logout seconds due to config');
this.client.overrideIdleLogoutSeconds(idleLogoutSeconds);
}
2019-05-17 23:25:35 +00:00
});
// when we get data, process it
2019-05-20 22:37:32 +00:00
this.state.socket.on('data', data => {
2019-05-17 23:25:35 +00:00
data = data.toString();
this.processReceivedMessage(data);
});
this.state.socket.once('error', err => {
this.log.warn( { error : err.message }, 'MRC multiplexer socket error' );
this.state.socket.destroy();
delete this.state.socket;
// bail with error - fall back to prev menu
return callback(err);
});
2019-05-17 23:25:35 +00:00
return(callback);
}
],
err => {
return cb(err);
}
);
2019-05-17 23:25:35 +00:00
});
}
leave() {
this.quitServer();
// restore idle monitor to previous state
this.log.debug('Restoring idle monitor to previous state');
this.client.restoreIdleLogoutSeconds();
this.client.startIdleMonitor();
return super.leave();
}
quitServer() {
clearInterval(this.heartbeat);
if(this.state.socket) {
this.sendServerMessage('LOGOFF');
this.state.socket.destroy();
2019-06-08 17:58:21 +00:00
delete this.state.socket;
}
}
/**
* Adds a message to the chat log on screen
*/
addMessageToChatLog(message) {
if(!Array.isArray(message)) {
message = [ message ];
2019-05-25 23:14:36 +00:00
}
message.forEach(msg => {
const chatLogView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
const messageLength = stripMciColorCodes(msg).length;
const chatWidth = chatLogView.dimens.width;
let padAmount = 0;
let spaces = 2;
if (messageLength > chatWidth) {
padAmount = chatWidth - (messageLength % chatWidth) - spaces;
} else {
padAmount = chatWidth - messageLength - spaces;
}
if (padAmount < 0) padAmount = 0;
2019-05-31 19:34:07 +00:00
const padding = ' |00' + ' '.repeat(padAmount);
chatLogView.addText(pipeToAnsi(msg + padding));
if(chatLogView.getLineCount() > this.config.maxScrollbackLines) {
chatLogView.deleteLine(0);
}
});
}
/**
2019-05-25 23:14:36 +00:00
* Processes data received from the MRC multiplexer
*/
2019-05-17 23:25:35 +00:00
processReceivedMessage(blob) {
blob.split('\n').forEach( message => {
try {
message = JSON.parse(message);
2019-05-17 23:25:35 +00:00
} catch (e) {
return;
2019-05-17 23:25:35 +00:00
}
if (message.from_user == 'SERVER') {
const params = message.body.split(':');
switch (params[0]) {
case 'BANNER':
this.addMessageToChatLog(params[1].replace(/^\s+/, ''));
2019-05-18 23:01:58 +00:00
break;
2019-05-17 23:25:35 +00:00
case 'ROOMTOPIC':
this.setText(MciViewIds.mrcChat.roomName, `#${params[1]}`);
this.setText(MciViewIds.mrcChat.roomTopic, params[2]);
this.customFormatObj.roomName = params[1];
this.customFormatObj.roomTopic = params[2];
this.updateCustomViews();
2019-05-20 22:37:32 +00:00
this.state.room = params[1];
2019-05-18 23:01:58 +00:00
break;
2019-05-17 23:25:35 +00:00
case 'USERLIST':
2019-05-20 22:37:32 +00:00
this.state.nicks = params[1].split(',');
this.customFormatObj.roomUserCount = this.state.nicks.length;
this.updateCustomViews();
2019-05-18 23:01:58 +00:00
break;
2019-05-25 23:14:36 +00:00
case 'STATS': {
const [
boardCount,
roomCount,
userCount,
activityLevel
] = params[1].split(' ').map(v => parseInt(v));
const activityLevelIndicator = this.getActivityLevelIndicator(activityLevel);
Object.assign(
this.customFormatObj,
{
boardCount, roomCount, userCount,
activityLevel, activityLevelIndicator
}
);
this.setText(MciViewIds.mrcChat.mrcUsers, userCount);
this.setText(MciViewIds.mrcChat.mrcBbses, boardCount);
this.updateCustomViews();
2019-05-18 23:01:58 +00:00
break;
2019-05-25 23:14:36 +00:00
}
2019-05-18 23:01:58 +00:00
default:
this.addMessageToChatLog(message.body);
2019-05-18 23:01:58 +00:00
break;
2019-05-17 23:25:35 +00:00
}
} else {
if(message.body === this.state.lastSentMsg.msg) {
this.customFormatObj.latencyMs =
moment.duration(moment().diff(this.state.lastSentMsg.time)).asMilliseconds();
delete this.state.lastSentMsg.msg;
}
2019-05-25 23:14:36 +00:00
if (message.to_room == this.state.room) {
2019-05-18 23:01:58 +00:00
// if we're here then we want to show it to the user
const currentTime = moment().format(this.client.currentTheme.helpers.getTimeFormat());
2019-05-25 23:14:36 +00:00
this.addMessageToChatLog('|08' + currentTime + '|00 ' + message.body + '|00');
2019-05-18 23:01:58 +00:00
}
2019-05-17 23:25:35 +00:00
}
2019-05-18 23:01:58 +00:00
this.viewControllers.mrcChat.switchFocus(MciViewIds.mrcChat.inputArea);
2019-05-17 23:25:35 +00:00
});
}
2019-05-18 23:01:58 +00:00
getActivityLevelIndicator(level) {
let indicators = this.config.activityLevelIndicators;
if(!Array.isArray(indicators) || indicators.length < level + 1) {
indicators = [ ' ', '░', '▒', '▓' ];
}
2019-06-11 02:12:17 +00:00
return indicators[level];
}
setText(mciId, text) {
return this.setViewText('mrcChat', mciId, text);
}
updateCustomViews() {
return this.updateCustomViewTextsWithFilter(
'mrcChat',
MciViewIds.mrcChat.customRangeStart,
this.customFormatObj
);
}
/**
* Receives the message input from the user and does something with it based on what it is
*/
processOutgoingMessage(message, to_user) {
2019-05-18 23:01:58 +00:00
if (message.startsWith('/')) {
this.processSlashCommand(message);
2019-05-20 22:37:32 +00:00
} else {
if (message == '') {
2019-05-25 23:14:36 +00:00
// don't do anything if message is blank, just update stats
this.sendServerMessage('STATS');
2019-05-20 22:37:32 +00:00
return;
2019-05-18 23:01:58 +00:00
}
2019-05-25 23:14:36 +00:00
// else just format and send
2019-05-18 23:01:58 +00:00
const textFormatObj = {
2019-05-20 22:37:32 +00:00
fromUserName : this.state.alias,
2019-05-25 23:14:36 +00:00
toUserName : to_user,
2019-05-18 23:01:58 +00:00
message : message
};
2019-05-20 22:37:32 +00:00
2019-05-18 23:01:58 +00:00
const messageFormat =
this.config.messageFormat ||
'|00|10<|02{fromUserName}|10>|00 |03{message}|00';
2019-05-25 23:14:36 +00:00
const privateMessageFormat =
this.config.outgoingPrivateMessageFormat ||
'|00|10<|02{fromUserName}|10|14->|02{toUserName}>|00 |03{message}|00';
let formattedMessage = '';
if (to_user == undefined) {
// normal message
formattedMessage = stringFormat(messageFormat, textFormatObj);
} else {
// pm
formattedMessage = stringFormat(privateMessageFormat, textFormatObj);
}
2019-05-18 23:01:58 +00:00
try {
this.state.lastSentMsg = {
msg : formattedMessage,
time : moment(),
};
this.sendMessageToMultiplexer(to_user || '', '', this.state.room, formattedMessage);
2019-05-18 23:01:58 +00:00
} catch(e) {
2019-05-20 22:37:32 +00:00
this.client.log.warn( { error : e.message }, 'MRC error');
2019-05-18 23:01:58 +00:00
}
}
2019-05-20 22:37:32 +00:00
2019-05-18 23:01:58 +00:00
}
2019-05-20 22:37:32 +00:00
/**
* Processes a message that begins with a slash
*/
2019-05-20 22:37:32 +00:00
processSlashCommand(message) {
const cmd = message.split(' ');
cmd[0] = cmd[0].substr(1).toLowerCase();
switch (cmd[0]) {
case 'pm':
this.processOutgoingMessage(cmd[2], cmd[1]);
2019-05-20 22:37:32 +00:00
break;
2019-05-25 23:14:36 +00:00
case 'rainbow': {
2019-05-20 22:37:32 +00:00
// this is brutal, but i love it
const line = message.replace(/^\/rainbow\s/, '').split(' ').reduce(function (a, c) {
const cc = Math.floor((Math.random() * 31) + 1).toString().padStart(2, '0');
2019-05-20 22:37:32 +00:00
a += `|${cc}${c}|00 `;
return a;
}, '').substr(0, 140).replace(/\\s\|\d*$/, '');
this.processOutgoingMessage(line);
2019-05-20 22:37:32 +00:00
break;
2019-05-25 23:14:36 +00:00
}
2019-05-20 22:37:32 +00:00
case 'l33t':
2019-05-25 23:14:36 +00:00
this.processOutgoingMessage(StringUtil.stylizeString(message.substr(6), 'l33t'));
2019-05-20 22:37:32 +00:00
break;
2019-05-25 23:14:36 +00:00
case 'kewl': {
2019-05-20 22:37:32 +00:00
const text_modes = Array('f','v','V','i','M');
const mode = text_modes[Math.floor(Math.random() * text_modes.length)];
2019-05-25 23:14:36 +00:00
this.processOutgoingMessage(StringUtil.stylizeString(message.substr(6), mode));
2019-05-20 22:37:32 +00:00
break;
2019-05-25 23:14:36 +00:00
}
2019-05-20 22:37:32 +00:00
case 'whoon':
this.sendServerMessage('WHOON');
2019-05-20 22:37:32 +00:00
break;
case 'motd':
this.sendServerMessage('MOTD');
2019-05-20 22:37:32 +00:00
break;
case 'meetups':
this.sendServerMessage('MEETUPS');
2019-05-20 22:37:32 +00:00
break;
case 'bbses':
this.sendServerMessage('CONNECTED');
2019-05-20 22:37:32 +00:00
break;
case 'topic':
this.sendServerMessage(`NEWTOPIC:${this.state.room}:${message.substr(7)}`);
2019-05-20 22:37:32 +00:00
break;
case 'info':
this.sendServerMessage(`INFO ${cmd[1]}`);
2019-05-20 22:37:32 +00:00
break;
case 'join':
this.joinRoom(cmd[1]);
break;
case 'chatters':
this.sendServerMessage('CHATTERS');
2019-05-20 22:37:32 +00:00
break;
case 'rooms':
this.sendServerMessage('LIST');
2019-05-20 22:37:32 +00:00
break;
case 'quit' :
return this.prevMenu();
2019-05-20 22:37:32 +00:00
case 'clear':
this.clearMessages();
2019-05-20 22:37:32 +00:00
break;
case '?':
this.addMessageToChatLog(helpText.split(/\n/g));
2019-05-20 22:37:32 +00:00
break;
default:
2019-05-20 22:37:32 +00:00
break;
}
// just do something to get the cursor back to the right place ¯\_(ツ)_/¯
// :TODO: fix me!
this.sendServerMessage('STATS');
}
2019-05-20 22:37:32 +00:00
clearMessages() {
const chatLogView = this.viewControllers.mrcChat.getView(MciViewIds.mrcChat.chatLog);
chatLogView.setText('');
}
2019-05-20 22:37:32 +00:00
/**
* Creates a json object, stringifies it and sends it to the MRC multiplexer
*/
sendMessageToMultiplexer(to_user, to_site, to_room, body) {
2019-05-20 22:37:32 +00:00
const message = {
to_user,
to_site,
to_room,
body,
from_user : this.state.alias,
from_room : this.state.room,
2019-05-20 22:37:32 +00:00
};
if(this.state.socket) {
this.state.socket.write(JSON.stringify(message) + '\n');
}
}
2019-05-20 22:37:32 +00:00
/**
* Sends an MRC 'server' message
*/
sendServerMessage(command, to_site) {
2019-05-20 22:37:32 +00:00
Log.debug({ module: 'mrc', command: command }, 'Sending server command');
this.sendMessageToMultiplexer('SERVER', to_site || '', this.state.room, command);
}
2019-05-17 23:25:35 +00:00
/**
* Sends a heartbeat to the MRC server
*/
2019-05-20 22:37:32 +00:00
sendHeartbeat() {
this.sendServerMessage('IAMHERE');
2019-05-17 23:25:35 +00:00
}
2019-05-20 22:37:32 +00:00
/**
* Joins a room, unsurprisingly
*/
2019-05-20 22:37:32 +00:00
joinRoom(room) {
// room names are displayed with a # but referred to without. confusing.
room = room.replace(/^#/, '');
this.state.room = room;
this.sendServerMessage(`NEWROOM:${this.state.room}:${room}`);
this.sendServerMessage('USERLIST');
2019-05-20 22:37:32 +00:00
}
/**
* Things that happen when a local user connects to the MRC multiplexer
*/
2019-05-20 22:37:32 +00:00
clientConnect() {
this.sendServerMessage('MOTD');
2019-05-20 22:37:32 +00:00
this.joinRoom('lobby');
this.sendServerMessage('STATS');
2019-05-20 22:37:32 +00:00
this.sendHeartbeat();
}
};