| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291 |
- import api from "./Api";
- import notifier from "./Notifier";
- import prefs from "./Prefs";
- import db from "./db";
- import { topicUrl } from "./utils";
- class SubscriptionManager {
- constructor(dbImpl) {
- this.db = dbImpl;
- }
- /** All subscriptions, including "new count"; this is a JOIN, see https://dexie.org/docs/API-Reference#joining */
- async all() {
- const subscriptions = await this.db.subscriptions.toArray();
- return Promise.all(
- subscriptions.map(async (s) => ({
- ...s,
- new: await this.db.notifications.where({ subscriptionId: s.id, new: 1 }).count(),
- }))
- );
- }
- /**
- * List of topics for which Web Push is enabled. This excludes (a) internal topics, (b) topics that are muted,
- * and (c) topics from other hosts. Returns an empty list if Web Push is disabled.
- *
- * It is important to note that "mutedUntil" must be part of the where() query, otherwise the Dexie live query
- * will not react to it, and the Web Push topics will not be updated when the user mutes a topic.
- */
- async webPushTopics(pushPossible) {
- if (!pushPossible) {
- return [];
- }
- // the Promise.resolve wrapper is not superfluous, without it the live query breaks:
- // https://dexie.org/docs/dexie-react-hooks/useLiveQuery()#calling-non-dexie-apis-from-querier
- const enabled = await Promise.resolve(prefs.webPushEnabled());
- if (!enabled) {
- return [];
- }
- const subscriptions = await this.db.subscriptions.where({ baseUrl: config.base_url, mutedUntil: 0 }).toArray();
- return subscriptions.filter(({ internal }) => !internal).map(({ topic }) => topic);
- }
- async get(subscriptionId) {
- return this.db.subscriptions.get(subscriptionId);
- }
- async notify(subscriptionId, notification) {
- const subscription = await this.get(subscriptionId);
- if (subscription.mutedUntil > 0) {
- return;
- }
- const priority = notification.priority ?? 3;
- if (priority < (await prefs.minPriority())) {
- return;
- }
- await notifier.notify(subscription, notification);
- }
- /**
- * @param {string} baseUrl
- * @param {string} topic
- * @param {object} opts
- * @param {boolean} opts.internal
- * @returns
- */
- async add(baseUrl, topic, opts = {}) {
- const id = topicUrl(baseUrl, topic);
- const existingSubscription = await this.get(id);
- if (existingSubscription) {
- return existingSubscription;
- }
- const subscription = {
- ...opts,
- id: topicUrl(baseUrl, topic),
- baseUrl,
- topic,
- mutedUntil: 0,
- last: null,
- };
- await this.db.subscriptions.put(subscription);
- return subscription;
- }
- async syncFromRemote(remoteSubscriptions, remoteReservations) {
- console.log(`[SubscriptionManager] Syncing subscriptions from remote`, remoteSubscriptions);
- // Add remote subscriptions
- const remoteIds = await Promise.all(
- remoteSubscriptions.map(async (remote) => {
- const reservation = remoteReservations?.find((r) => remote.base_url === config.base_url && remote.topic === r.topic) || null;
- const local = await this.add(remote.base_url, remote.topic, {
- displayName: remote.display_name, // May be undefined
- reservation, // May be null!
- });
- return local.id;
- })
- );
- // Remove local subscriptions that do not exist remotely
- const localSubscriptions = await this.db.subscriptions.toArray();
- await Promise.all(
- localSubscriptions.map(async (local) => {
- const remoteExists = remoteIds.includes(local.id);
- if (!local.internal && !remoteExists) {
- await this.remove(local);
- }
- })
- );
- }
- async updateWebPushSubscriptions(topics) {
- const hasWebPushTopics = topics.length > 0;
- const browserSubscription = await notifier.webPushSubscription(hasWebPushTopics);
- if (!browserSubscription) {
- console.log(
- "[SubscriptionManager] No browser subscription currently exists, so web push was never enabled or the notification permission was removed. Skipping."
- );
- return;
- }
- if (hasWebPushTopics) {
- await api.updateWebPush(browserSubscription, topics);
- } else {
- await api.deleteWebPush(browserSubscription);
- }
- }
- async updateState(subscriptionId, state) {
- this.db.subscriptions.update(subscriptionId, { state });
- }
- async remove(subscription) {
- await this.db.subscriptions.delete(subscription.id);
- await this.db.notifications.where({ subscriptionId: subscription.id }).delete();
- }
- async first() {
- return this.db.subscriptions.toCollection().first(); // May be undefined
- }
- async getNotifications(subscriptionId) {
- // This is quite awkward, but it is the recommended approach as per the Dexie docs.
- // It's actually fine, because the reading and filtering is quite fast. The rendering is what's
- // killing performance. See https://dexie.org/docs/Collection/Collection.offset()#a-better-paging-approach
- const notifications = await this.db.notifications
- .orderBy("time") // Sort by time
- .filter((n) => n.subscriptionId === subscriptionId)
- .reverse()
- .toArray();
- return this.groupNotificationsBySID(notifications);
- }
- async getAllNotifications() {
- const notifications = await this.db.notifications
- .orderBy("time") // Efficient, see docs
- .reverse()
- .toArray();
- return this.groupNotificationsBySID(notifications);
- }
- // Collapse notification updates based on sids, keeping only the latest version
- // Filters out notifications where the latest in the sequence is deleted
- groupNotificationsBySID(notifications) {
- const latestBySid = {};
- notifications.forEach((notification) => {
- const key = `${notification.subscriptionId}:${notification.sid}`;
- // Keep only the first (latest by time) notification for each sid
- if (!(key in latestBySid)) {
- latestBySid[key] = notification;
- }
- });
- // Filter out notifications where the latest is deleted
- return Object.values(latestBySid).filter((n) => !n.deleted);
- }
- /** Adds notification, or returns false if it already exists */
- async addNotification(subscriptionId, notification) {
- const exists = await this.db.notifications.get(notification.id);
- if (exists) {
- return false;
- }
- try {
- const populatedNotification = notification;
- if (!("sid" in populatedNotification)) {
- populatedNotification.sid = notification.id;
- }
- // sw.js duplicates this logic, so if you change it here, change it there too
- await this.db.notifications.add({
- ...populatedNotification,
- subscriptionId,
- // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
- new: 1,
- }); // FIXME consider put() for double tab
- await this.db.subscriptions.update(subscriptionId, {
- last: notification.id,
- });
- } catch (e) {
- console.error(`[SubscriptionManager] Error adding notification`, e);
- }
- return true;
- }
- /** Adds/replaces notifications, will not throw if they exist */
- async addNotifications(subscriptionId, notifications) {
- const notificationsWithSubscriptionId = notifications.map((notification) => {
- const populatedNotification = notification;
- if (!("sid" in populatedNotification)) {
- populatedNotification.sid = notification.id;
- }
- return { ...populatedNotification, subscriptionId };
- });
- const lastNotificationId = notifications.at(-1).id;
- await this.db.notifications.bulkPut(notificationsWithSubscriptionId);
- await this.db.subscriptions.update(subscriptionId, {
- last: lastNotificationId,
- });
- }
- async updateNotification(notification) {
- const exists = await this.db.notifications.get(notification.id);
- if (!exists) {
- return false;
- }
- try {
- await this.db.notifications.put({ ...notification });
- } catch (e) {
- console.error(`[SubscriptionManager] Error updating notification`, e);
- }
- return true;
- }
- async deleteNotification(notificationId) {
- await this.db.notifications.delete(notificationId);
- }
- async deleteNotifications(subscriptionId) {
- await this.db.notifications.where({ subscriptionId }).delete();
- }
- async markNotificationRead(notificationId) {
- await this.db.notifications.where({ id: notificationId }).modify({ new: 0 });
- }
- async markNotificationsRead(subscriptionId) {
- await this.db.notifications.where({ subscriptionId, new: 1 }).modify({ new: 0 });
- }
- async setMutedUntil(subscriptionId, mutedUntil) {
- await this.db.subscriptions.update(subscriptionId, {
- mutedUntil,
- });
- }
- async setDisplayName(subscriptionId, displayName) {
- await this.db.subscriptions.update(subscriptionId, {
- displayName,
- });
- }
- async setReservation(subscriptionId, reservation) {
- await this.db.subscriptions.update(subscriptionId, {
- reservation,
- });
- }
- async update(subscriptionId, params) {
- await this.db.subscriptions.update(subscriptionId, params);
- }
- async pruneNotifications(thresholdTimestamp) {
- await this.db.notifications.where("time").below(thresholdTimestamp).delete();
- }
- }
- export default new SubscriptionManager(db());
|