Marc Kupietz | 8ef4a6d | 2022-01-15 13:52:33 +0100 | [diff] [blame] | 1 | #!/usr/bin/env node |
| 2 | process.env.NTBA_FIX_319 = 1; |
| 3 | const { Command } = require('commander'); |
| 4 | const Tgfancy = require("tgfancy"); |
| 5 | const { exec } = require("child_process"); |
| 6 | const sleep = require('sleep'); |
| 7 | const program = new Command(); |
| 8 | |
| 9 | program |
| 10 | .arguments('<path-of-folder>') |
| 11 | .description( 'Sends telegram message when there are no modifications to <path-of-folder> since a certain time interval.') |
| 12 | .option('-d, --debug', 'output extra debugging') |
| 13 | .option('-s, --seconds <int>', 'notify if no changes since n seconds', 120) |
| 14 | .option('-p, --poll-interval <int>', 'interval in seconds between polls', 30) |
| 15 | .parse(process.argv); |
| 16 | |
| 17 | const options = program.opts(); |
| 18 | if (options.debug) console.log(options); |
| 19 | |
| 20 | function timeString() { |
| 21 | return "[" + (new Date()).toISOString() + "]" |
| 22 | } |
| 23 | |
| 24 | function waitUntilIdle(filePath, seconds = options.seconds, pollInterval = options.pollInterval, cb = sendTelegramMessage) { |
| 25 | exec(`find ${filePath} -maxdepth 1 -newermt '-${seconds} seconds'`, (error, stdout, stderr) => { |
| 26 | if (error) { |
| 27 | const message = `error: ${error.message}` |
| 28 | console.log(message); |
| 29 | cb(message); |
| 30 | return; |
| 31 | } |
| 32 | if (stderr) { |
| 33 | const message = `stderr: ${stderr}` |
| 34 | console.log(message); |
| 35 | cb(message); |
| 36 | return; |
| 37 | } |
| 38 | if (stdout.length == 0) { |
| 39 | const message = `No modifications in ${filePath} since ${seconds} seconds` |
| 40 | console.log(`${timeString()}: ${message}`) |
| 41 | cb(message); |
| 42 | } else { |
| 43 | var message = `${timeString()}: still processing ${stdout.trim()}`; |
| 44 | console.log(message); |
| 45 | sleep.sleep(pollInterval); |
| 46 | waitUntilIdle(filePath, seconds, pollInterval, cb) |
| 47 | } |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | function sendTelegramMessage(message, bot = new Tgfancy(process.env.TELEGRAM_TOKEN), chatId = process.env.TELEGRAM_CHAT_ID) { |
| 52 | bot.sendMessage(chatId, message); |
| 53 | } |
| 54 | |
| 55 | waitUntilIdle(program.args[0]); |