2020-03-22 22:09:33 +00:00
'use strict' ;
const { spawn } = require ( 'child_process' ) ;
// import TelegramBot from 'node-telegram-bot-api';
import SendMessage from './send_message' ;
2020-03-25 22:40:18 +00:00
import { ITaskConfig } from '../config/config' ;
2020-03-22 22:09:33 +00:00
import { ITaskOptions } from '../utils' ;
import Config from '../config/config'
import InvalidCommandError from '../errors/invalid_command' ;
2020-03-25 22:40:18 +00:00
import InvalidArgumentsError from '../errors/invalid_arguments.error' ;
2020-03-22 22:09:33 +00:00
export default class TaskMessage {
2020-03-25 22:40:18 +00:00
static async run ( config : ITaskConfig , options : ITaskOptions ) {
validate ( config , options ) ;
2020-03-22 22:09:33 +00:00
const exec = spawn ( options . command , options . args ) ;
let errors = await promisifyExec ( exec , options . command ) ;
let msg = config . task_message_template . replace ( '%cmd%' , ` $ ${ options . command } ${ options . args . join ( ' ' ) } ` )
. replace ( '%errors%' , errors ) ;
try {
await SendMessage . send ( config , msg ) ;
} catch ( e ) {
errors = e . message ;
console . error ( ` [ ${ Config . APP_NAME } ]: An error occurred. Error: ${ e . message } ` ) ;
}
return true ;
}
}
2020-03-25 22:40:18 +00:00
function validate ( config : ITaskConfig , options : ITaskOptions ) {
if ( ! config . bot_token || ! config . chat_id || ! config . task_message_template ) throw new InvalidArgumentsError ( ` Config object must have bot_token<string>, chat_id<string>, task_message_template<string> ` ) ;
if ( ! options . command || ! options . args || ! Array . isArray ( options . args ) || typeof options . command !== 'string' ) throw new InvalidArgumentsError ( ` Option object must have command<string>, and args<string[]> ` )
}
2020-03-22 22:09:33 +00:00
function promisifyExec ( exec , command ) : Promise < string > {
let errors = null ;
return new Promise ( ( resolve , reject ) = > {
exec . stdout . on ( 'data' , ( data ) = > {
console . log ( String ( data ) ) ;
} ) ;
exec . on ( 'error' , ( error ) = > {
if ( error . message . indexOf ( 'ENOENT' ) >= 0 ) {
reject ( new InvalidCommandError ( ` Command ' ${ command } ' not found ` ) ) ;
}
} ) ;
exec . stderr . on ( 'data' , ( data ) = > {
console . error ( String ( data ) ) ;
if ( ! errors )
errors = data ;
else
errors += ` \ n ${ data } ` ;
} ) ;
exec . on ( 'close' , async ( code ) = > {
resolve ( errors ) ;
} ) ;
} ) ;
}