ntfy/web/src/app/Notifier.js

65 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-03-06 18:02:27 +13:00
import {formatMessage, formatTitleWithDefault, openUrl, playSound, topicShortUrl} from "./utils";
2022-03-03 10:16:30 +13:00
import prefs from "./Prefs";
import subscriptionManager from "./SubscriptionManager";
2022-02-27 04:14:43 +13:00
2022-03-06 18:02:27 +13:00
class Notifier {
async notify(subscriptionId, notification, onClickFallback) {
const subscription = await subscriptionManager.get(subscriptionId);
const shouldNotify = await this.shouldNotify(subscription, notification);
if (!shouldNotify) {
return;
}
2022-03-03 10:16:30 +13:00
const shortUrl = topicShortUrl(subscription.baseUrl, subscription.topic);
2022-02-27 04:14:43 +13:00
const message = formatMessage(notification);
2022-03-05 06:10:11 +13:00
const title = formatTitleWithDefault(notification, shortUrl);
2022-03-03 10:16:30 +13:00
2022-03-06 18:02:27 +13:00
// Show notification
console.log(`[Notifier, ${shortUrl}] Displaying notification ${notification.id}: ${message}`);
2022-02-27 04:14:43 +13:00
const n = new Notification(title, {
body: message,
icon: '/static/img/favicon.png'
});
if (notification.click) {
n.onclick = (e) => openUrl(notification.click);
2022-02-27 04:14:43 +13:00
} else {
n.onclick = onClickFallback;
}
2022-03-06 18:02:27 +13:00
// Play sound
const sound = await prefs.sound();
if (sound && sound !== "none") {
try {
await playSound(sound);
} catch (e) {
console.log(`[Notifier, ${shortUrl}] Error playing audio`, e);
// FIXME show no sound allowed popup
}
}
2022-02-27 04:14:43 +13:00
}
granted() {
return Notification.permission === 'granted';
}
maybeRequestPermission(cb) {
if (!this.granted()) {
Notification.requestPermission().then((permission) => {
const granted = permission === 'granted';
cb(granted);
});
}
}
async shouldNotify(subscription, notification) {
const priority = (notification.priority) ? notification.priority : 3;
2022-03-03 10:16:30 +13:00
const minPriority = await prefs.minPriority();
if (priority < minPriority) {
return false;
}
return true;
}
2022-02-27 04:14:43 +13:00
}
2022-03-06 18:02:27 +13:00
const notifier = new Notifier();
export default notifier;