diff --git a/app.js b/app.js index 0b923d2..6c758d2 100644 --- a/app.js +++ b/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 -- Telegram Shell!\n\n` + `You are now connected to ${hostname}` + ` as ${username}`); @@ -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); }); diff --git a/lib/listeners.js b/lib/listeners.js new file mode 100644 index 0000000..08089ff --- /dev/null +++ b/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, +};