fritzfix/fritzfix.js
2024-06-12 10:26:04 +02:00

116 lines
2.8 KiB
JavaScript

const packageJSON = require("./package.json");
const configJSON = require("./config.json");
const logger = require("./libs/logger.js");
const fritzbox = require("./libs/fritzbox.js");
const draytek = require("./libs/draytek.js");
const notification = require("./libs/notify.js");
const timediff = require("./libs/timediff.js");
const INTERRUPTS = ["beforeExit", "SIGINT", "SIGTERM"];
global.appName = packageJSON.name;
global.appVersion = packageJSON.version;
global.config = configJSON;
let offlineTimestamp;
let rebootError;
main();
async function main() {
handleExit();
try {
logger.initialize(configJSON);
logger.info(
"launching " + global.appName + " " + global.appVersion + "..."
);
mainLoop();
} catch (err) {
await exit(1, err);
}
}
async function mainLoop() {
const isOnline = await draytek.isOnline();
if (!isOnline) {
if (offlineTimestamp) {
logger.warn(
"draytek seems to be still not responding after " +
timediff.inSeconds(offlineTimestamp) +
" seconds!"
);
} else {
offlineTimestamp = Date.now();
const msg = "draytek seems to be not responding!";
logger.warn(msg);
await notification.send(
"draytek offline!",
msg + "\nwaiting for it to come back online...",
"max",
"scream"
);
}
} else {
if (offlineTimestamp) {
const msg =
"draytek is responding again after " +
timediff.inSeconds(offlineTimestamp) +
" seconds!";
logger.info(msg);
if (!rebootError) {
notification.send(
"rebooting fritzbox...",
msg + "\nrebooting fritzbox now...",
undefined,
"roll_eyes"
);
}
const err = await fritzbox.reboot();
if (err) {
rebootError = err;
notification.send("error rebooting fritzbox!", err, "max", "sob");
} else {
notification.send(
"fritzbox rebooted!",
"successfully rebooted device, the phones should now work again!",
"max",
"partying_face"
);
offlineTimestamp = undefined;
rebootError = undefined;
}
}
}
setTimeout(() => {
mainLoop();
}, configJSON.interval);
}
async function handleExit() {
for (var index = 0; index < INTERRUPTS.length; index++) {
process.on(INTERRUPTS[index], async (code) => {
await exit(code);
});
}
}
async function exit(code, err) {
await fritzbox.quit();
if (code === undefined) {
code = 0;
if (err) {
code = 1;
}
}
if (err) {
logger.error(err);
logger.error(
global.appName + " " + global.appVersion + " ended due to an error"
);
} else {
logger.info(
global.appName + " " + global.appVersion + " shutting down gracefully"
);
}
process.exit(code);
}