2017-11-28 20:47:41 +02:00
|
|
|
const notifier = require('node-notifier');
|
|
|
|
|
2017-11-28 00:50:46 +02:00
|
|
|
class AlarmServiceDriverNode {
|
2017-11-28 20:47:41 +02:00
|
|
|
constructor(options) {
|
|
|
|
// Note: appName is required to get the notification to work. It must be the same as the appId defined in package.json
|
|
|
|
// https://github.com/mikaelbr/node-notifier/issues/144#issuecomment-319324058
|
|
|
|
this.appName_ = options.appName;
|
2017-11-28 02:22:38 +02:00
|
|
|
this.notifications_ = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
hasPersistentNotifications() {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
notificationIsSet(id) {
|
|
|
|
return id in this.notifications_;
|
|
|
|
}
|
|
|
|
|
2017-11-28 00:50:46 +02:00
|
|
|
async clearNotification(id) {
|
2017-11-28 02:22:38 +02:00
|
|
|
if (!this.notificationIsSet(id)) return;
|
|
|
|
clearTimeout(this.notifications_[id].timeoutId);
|
|
|
|
delete this.notifications_[id];
|
2017-11-28 00:50:46 +02:00
|
|
|
}
|
2019-07-29 15:43:53 +02:00
|
|
|
|
2017-11-28 00:50:46 +02:00
|
|
|
async scheduleNotification(notification) {
|
2017-11-28 02:22:38 +02:00
|
|
|
const now = Date.now();
|
|
|
|
const interval = notification.date.getTime() - now;
|
|
|
|
if (interval < 0) return;
|
2017-11-28 00:50:46 +02:00
|
|
|
|
2018-12-08 01:42:29 +02:00
|
|
|
if (isNaN(interval)) {
|
|
|
|
throw new Error('Trying to create a notification from an invalid object: ' + JSON.stringify(notification));
|
|
|
|
}
|
|
|
|
|
2017-11-28 02:22:38 +02:00
|
|
|
const timeoutId = setTimeout(() => {
|
2017-11-28 20:47:41 +02:00
|
|
|
const o = {
|
|
|
|
appName: this.appName_,
|
|
|
|
title: notification.title,
|
|
|
|
};
|
|
|
|
if ('body' in notification) o.message = notification.body;
|
|
|
|
notifier.notify(o);
|
2017-11-28 02:22:38 +02:00
|
|
|
this.clearNotification(notification.id);
|
|
|
|
}, interval);
|
2017-11-28 20:47:41 +02:00
|
|
|
|
|
|
|
this.notifications_[notification.id] = Object.assign({}, notification);
|
|
|
|
this.notifications_[notification.id].timeoutId = timeoutId;
|
2017-11-28 00:50:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
module.exports = AlarmServiceDriverNode;
|