Browse Source

[refactor] Deduplicate listeners

master
Muthu Kumar 6 years ago
parent
commit
f58ce30b3e
  1. 22
      app.js
  2. 16
      lib/listeners.js

22
app.js

@ -1,13 +1,21 @@
// Internal
const { spawn } = require('child_process');
const { EOL } = require('os');
const os = require('os');
// Modules
const Telegraf = require('telegraf');
const { path } = require('./util/index.js');
//Config
const config = require('./config.js');
const validator = require('./lib/validator');
// Utils
const { path } = require('./util/index.js');
// Lib
const validator = require('./lib/validator.js');
const responder = require('./lib/responseHandler.js');
const listeners = require('./lib/listeners.js');
const dateOptions = {
weekday: 'long',
@ -40,11 +48,9 @@ bot.command('start',
const newProc = spawn(defaultShell, {
cwd: home
});
newProc.stdout.setEncoding('utf8');
sessions.push(newProc);
sessions.currentSession = newProc;
sessions.currentSession.stdout.on('data', d => responder.success(d)(ctx));
sessions.currentSession.stderr.on('data', e => responder.success(e)(ctx));
listeners.add(sessions.currentSession, responder, ctx);
return ctx.replyWithHTML(`Welcome to tsh -- <code>Telegram Shell!</code>\n\n`
+ `You are now connected to <code>${hostname}</code>`
+ ` as <strong>${username}</strong>`);
@ -64,8 +70,7 @@ bot.command('attach',
if(Number.isNaN(sessionIndex) || !sessions[sessionIndex])
return responder.fail('Session not found. /ls for list of sessions')(ctx);
sessions.currentSession = sessions[sessionIndex];
sessions.currentSession.stdout.on('data', d => responder.success(d)(ctx));
sessions.currentSession.stderr.on('data', e => responder.success(e)(ctx));
listeners.add(sessions.currentSession, responder, ctx);
return responder.success(`Reattached to shell ${sessionIndex}`)(ctx);
});
@ -78,8 +83,7 @@ bot.command('detach',
? sessions.currentSession : sessions[sessionIndex];
if(!currentSession)
return responder.fail('Session not found. /ls for list of sessions.')(ctx);
sessions.currentSession.stdout.removeAllListeners('data');
sessions.currentSession.stderr.removeAllListeners('data');
listeners.remove(sessions.currentSession);
sessions.currentSession = undefined;
return responder.success(`Detached from shell ${sessionIndex}`)(ctx);
});

16
lib/listeners.js

@ -0,0 +1,16 @@
const addListeners = (emitter, responder, ctx) => {
emitter.stdout.setEncoding('utf8');
emitter.stderr.setEncoding('utf8');
emitter.stdout.on('data', d => responder.success(d)(ctx));
emitter.stderr.on('data', e => responder.success(e)(ctx));
};
const removeListeners = emitter => {
emitter.stdout.removeAllListeners('data');
emitter.stderr.removeAllListeners('data');
};
module.exports = {
add: addListeners,
remove: removeListeners,
};
Loading…
Cancel
Save