NotificationLatch/lib/facade.js

117 lines
2.7 KiB
JavaScript

const repository = require('./repository');
const subjectParser = require('./subjectparser');
const { DateTime } = require('luxon');
function init(contacts, maxAttempts, retryInterval)
{
if (global.facadeData)
throw new Error("Facade is already initialized");
const transportMap = {
"pushover": require('./transport/pushover')
}
global.facadeData = {
maxAttempts: maxAttempts,
retryInterval: retryInterval,
contacts: contacts.filter(c =>
{
if (!transportMap.hasOwnProperty(c.type))
{
console.error(`Unknown transport type '${c.type}', skipping contact`)
return false;
}
return true;
}),
transportMap: transportMap
}
}
async function postNotification(subject, message, priority)
{
var parsedSubject = subjectParser.parse(subject);
console.log(parsedSubject);
const token = await repository.storeNotification(parsedSubject.id, parsedSubject.title);
if (token === null)
return;
sendNotification({
id: parsedSubject.id,
token: token,
title: parsedSubject.title,
message: message,
priority: priority,
sound: parsedSubject.sound,
timestamp: Math.floor(DateTime.now().toSeconds()),
url: 'https://www.hierhaduwurlkunnenstaan.nl/'
});
}
async function resetNotification(token)
{
await repository.resetNotification(token);
}
function sendNotification(notification)
{
if (!global.facadeData)
throw new Error('Facade not initialized, call init() first');
global.facadeData.contacts.forEach(contact =>
{
const transport = global.facadeData.transportMap[contact.type];
retryableSend(transport, contact, notification);
});
}
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function retryableSend(transport, contact, notification)
{
let attempt = 1;
while (true)
{
try
{
console.info(`Sending notification '${notification.id}' with token '${notification.token}' to '${contact.description}' (attempt ${attempt})`);
await transport.send(contact, notification);
console.info(`Notification '${notification.id}' succesfully sent to '${contact.description}'`);
return;
}
catch (err)
{
if (attempt >= global.facadeData.maxAttempts)
{
console.info(`Error while sending notification '${notification.id}' to '${contact.description}', max attempts reached: ${err}`);
return;
}
console.info(`Error while sending notification '${notification.id}' to '${contact.description}', retrying in ${global.facadeData.retryInterval} seconds: ${err}`);
await delay(global.facadeData.retryInterval * 1000);
attempt++;
}
}
}
module.exports = {
init,
postNotification,
resetNotification
}