2022-02-26 17:45:39 +01:00
|
|
|
import {formatMessage, formatTitleWithFallback, topicShortUrl} from "./utils";
|
2022-03-01 22:22:47 +01:00
|
|
|
import repository from "./Repository";
|
2022-02-26 16:14:43 +01:00
|
|
|
|
|
|
|
class NotificationManager {
|
2022-03-02 04:41:49 +01:00
|
|
|
async notify(subscription, notification, onClickFallback) {
|
|
|
|
const shouldNotify = await this.shouldNotify(subscription, notification);
|
|
|
|
if (!shouldNotify) {
|
2022-03-01 22:22:47 +01:00
|
|
|
return;
|
|
|
|
}
|
2022-02-26 16:14:43 +01:00
|
|
|
const message = formatMessage(notification);
|
2022-02-26 17:45:39 +01:00
|
|
|
const title = formatTitleWithFallback(notification, topicShortUrl(subscription.baseUrl, subscription.topic));
|
2022-02-26 16:14:43 +01:00
|
|
|
const n = new Notification(title, {
|
|
|
|
body: message,
|
|
|
|
icon: '/static/img/favicon.png'
|
|
|
|
});
|
|
|
|
if (notification.click) {
|
|
|
|
n.onclick = (e) => window.open(notification.click);
|
|
|
|
} else {
|
|
|
|
n.onclick = onClickFallback;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
granted() {
|
|
|
|
return Notification.permission === 'granted';
|
|
|
|
}
|
|
|
|
|
|
|
|
maybeRequestPermission(cb) {
|
|
|
|
if (!this.granted()) {
|
|
|
|
Notification.requestPermission().then((permission) => {
|
|
|
|
const granted = permission === 'granted';
|
|
|
|
cb(granted);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2022-03-01 22:22:47 +01:00
|
|
|
|
2022-03-02 04:41:49 +01:00
|
|
|
async shouldNotify(subscription, notification) {
|
2022-03-01 22:22:47 +01:00
|
|
|
const priority = (notification.priority) ? notification.priority : 3;
|
2022-03-02 04:41:49 +01:00
|
|
|
const minPriority = await repository.getMinPriority();
|
|
|
|
if (priority < minPriority) {
|
2022-03-01 22:22:47 +01:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
2022-02-26 16:14:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const notificationManager = new NotificationManager();
|
|
|
|
export default notificationManager;
|