'use strict'; const { spawn } = require('child_process'); // import TelegramBot from 'node-telegram-bot-api'; import SendMessage from './send_message'; import { ITaskConfig } from '../config/config'; import { ITaskOptions } from '../utils'; import Config from '../config/config' import InvalidCommandError from '../errors/invalid_command'; import InvalidArgumentsError from '../errors/invalid_arguments.error'; export default class TaskMessage { static async run(config: ITaskConfig, options: ITaskOptions) { validate(config, options); 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; } } 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, chat_id, task_message_template`); if (!options.command || !options.args || !Array.isArray(options.args) || typeof options.command !== 'string') throw new InvalidArgumentsError(`Option object must have command, and args`) } function promisifyExec(exec, command): Promise { 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); }); }); }