| 1 |
import api from "./Api"; |
| 2 |
import notifier from "./Notifier"; |
| 3 |
import prefs from "./Prefs"; |
| 4 |
import db from "./db"; |
| 5 |
import { topicUrl } from "./utils"; |
| 6 |
import { messageWithSequenceId } from "./notificationUtils"; |
| 7 |
import { EVENT_MESSAGE, EVENT_MESSAGE_CLEAR, EVENT_MESSAGE_DELETE } from "./events"; |
| 8 |
|
| 9 |
export class SubscriptionManager { |
| 10 |
constructor(dbImpl) { |
| 11 |
this.db = dbImpl; |
| 12 |
} |
| 13 |
|
| 14 |
/** All subscriptions, including "new count"; this is a JOIN, see https://dexie.org/docs/API-Reference#joining */ |
| 15 |
async all() { |
| 16 |
const subscriptions = await this.db.subscriptions.toArray(); |
| 17 |
return Promise.all( |
| 18 |
subscriptions.map(async (s) => ({ |
| 19 |
...s, |
| 20 |
new: await this.db.notifications.where({ subscriptionId: s.id, new: 1 }).count(), |
| 21 |
})), |
| 22 |
); |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* List of topics for which Web Push is enabled. This excludes (a) internal topics, (b) topics that are muted, |
| 27 |
* and (c) topics from other hosts. Returns an empty list if Web Push is disabled. |
| 28 |
* |
| 29 |
* It is important to note that "mutedUntil" must be part of the where() query, otherwise the Dexie live query |
| 30 |
* will not react to it, and the Web Push topics will not be updated when the user mutes a topic. |
| 31 |
*/ |
| 32 |
async webPushTopics(pushPossible) { |
| 33 |
if (!pushPossible) { |
| 34 |
return []; |
| 35 |
} |
| 36 |
|
| 37 |
// the Promise.resolve wrapper is not superfluous, without it the live query breaks: |
| 38 |
// https://dexie.org/docs/dexie-react-hooks/useLiveQuery()#calling-non-dexie-apis-from-querier |
| 39 |
const enabled = await Promise.resolve(prefs.webPushEnabled()); |
| 40 |
if (!enabled) { |
| 41 |
return []; |
| 42 |
} |
| 43 |
|
| 44 |
const subscriptions = await this.db.subscriptions.where({ baseUrl: config.base_url, mutedUntil: 0 }).toArray(); |
| 45 |
return subscriptions.filter(({ internal }) => !internal).map(({ topic }) => topic); |
| 46 |
} |
| 47 |
|
| 48 |
async get(subscriptionId) { |
| 49 |
return this.db.subscriptions.get(subscriptionId); |
| 50 |
} |
| 51 |
|
| 52 |
async notify(subscriptionId, notification) { |
| 53 |
if (notification.event !== EVENT_MESSAGE) { |
| 54 |
return; |
| 55 |
} |
| 56 |
const subscription = await this.get(subscriptionId); |
| 57 |
if (subscription.mutedUntil > 0) { |
| 58 |
return; |
| 59 |
} |
| 60 |
const priority = notification.priority ?? 3; |
| 61 |
if (priority < (await prefs.minPriority())) { |
| 62 |
return; |
| 63 |
} |
| 64 |
await notifier.notify(subscription, notification); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Upsert a subscription: create it if it doesn't exist yet, or merge the given fields into the |
| 69 |
* existing one. Merging matters for account sync, which passes the remote display name and |
| 70 |
* reservation -- without it, reserving/unreserving a topic you're already subscribed to would |
| 71 |
* never be reflected locally until the database is recreated (e.g. a fresh login). Local-only |
| 72 |
* state such as mutedUntil and last is preserved on merge. |
| 73 |
* |
| 74 |
* @param {string} baseUrl |
| 75 |
* @param {string} topic |
| 76 |
* @param {object} opts |
| 77 |
* @param {boolean} opts.internal |
| 78 |
* @returns |
| 79 |
*/ |
| 80 |
async upsert(baseUrl, topic, opts = {}) { |
| 81 |
const id = topicUrl(baseUrl, topic); |
| 82 |
|
| 83 |
const existingSubscription = await this.get(id); |
| 84 |
if (existingSubscription) { |
| 85 |
// Avoid a needless write (and the resulting Dexie live-query churn) when nothing changed. |
| 86 |
const changed = Object.keys(opts).some((key) => existingSubscription[key] !== opts[key]); |
| 87 |
if (!changed) { |
| 88 |
return existingSubscription; |
| 89 |
} |
| 90 |
const updatedSubscription = { ...existingSubscription, ...opts }; |
| 91 |
await this.db.subscriptions.put(updatedSubscription); |
| 92 |
return updatedSubscription; |
| 93 |
} |
| 94 |
|
| 95 |
const subscription = { |
| 96 |
...opts, |
| 97 |
id, |
| 98 |
baseUrl, |
| 99 |
topic, |
| 100 |
mutedUntil: 0, |
| 101 |
last: null, |
| 102 |
}; |
| 103 |
|
| 104 |
await this.db.subscriptions.put(subscription); |
| 105 |
|
| 106 |
return subscription; |
| 107 |
} |
| 108 |
|
| 109 |
async syncFromRemote(remoteSubscriptions, remoteReservations) { |
| 110 |
console.log(`[SubscriptionManager] Syncing subscriptions from remote`, remoteSubscriptions); |
| 111 |
|
| 112 |
// Add remote subscriptions |
| 113 |
const remoteIds = await Promise.all( |
| 114 |
remoteSubscriptions.map(async (remote) => { |
| 115 |
const reservation = remoteReservations?.find((r) => remote.base_url === config.base_url && remote.topic === r.topic) || null; |
| 116 |
|
| 117 |
// upsert(): for topics that already exist locally this merges in the latest remote |
| 118 |
// display name and reservation (see upsert() for why this matters). |
| 119 |
const local = await this.upsert(remote.base_url, remote.topic, { |
| 120 |
displayName: remote.display_name, // May be undefined |
| 121 |
reservation, // May be null! |
| 122 |
}); |
| 123 |
|
| 124 |
return local.id; |
| 125 |
}), |
| 126 |
); |
| 127 |
|
| 128 |
// Remove local subscriptions that do not exist remotely |
| 129 |
const localSubscriptions = await this.db.subscriptions.toArray(); |
| 130 |
|
| 131 |
await Promise.all( |
| 132 |
localSubscriptions.map(async (local) => { |
| 133 |
const remoteExists = remoteIds.includes(local.id); |
| 134 |
if (!local.internal && !remoteExists) { |
| 135 |
await this.remove(local); |
| 136 |
} |
| 137 |
}), |
| 138 |
); |
| 139 |
} |
| 140 |
|
| 141 |
async updateWebPushSubscriptions(topics) { |
| 142 |
const hasWebPushTopics = topics.length > 0; |
| 143 |
const browserSubscription = await notifier.webPushSubscription(hasWebPushTopics); |
| 144 |
|
| 145 |
if (!browserSubscription) { |
| 146 |
console.log( |
| 147 |
"[SubscriptionManager] No browser subscription currently exists, so web push was never enabled or the notification permission was removed. Skipping.", |
| 148 |
); |
| 149 |
return; |
| 150 |
} |
| 151 |
|
| 152 |
if (hasWebPushTopics) { |
| 153 |
await api.updateWebPush(browserSubscription, topics); |
| 154 |
} else { |
| 155 |
await api.deleteWebPush(browserSubscription); |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
async updateState(subscriptionId, state) { |
| 160 |
this.db.subscriptions.update(subscriptionId, { state }); |
| 161 |
} |
| 162 |
|
| 163 |
async remove(subscription) { |
| 164 |
await this.db.subscriptions.delete(subscription.id); |
| 165 |
await this.db.notifications.where({ subscriptionId: subscription.id }).delete(); |
| 166 |
} |
| 167 |
|
| 168 |
async first() { |
| 169 |
return this.db.subscriptions.toCollection().first(); // May be undefined |
| 170 |
} |
| 171 |
|
| 172 |
async getNotifications(subscriptionId) { |
| 173 |
// This is quite awkward, but it is the recommended approach as per the Dexie docs. |
| 174 |
// It's actually fine, because the reading and filtering is quite fast. The rendering is what's |
| 175 |
// killing performance. See https://dexie.org/docs/Collection/Collection.offset()#a-better-paging-approach |
| 176 |
|
| 177 |
return this.db.notifications |
| 178 |
.orderBy("time") // Sort by time |
| 179 |
.filter((n) => n.subscriptionId === subscriptionId) |
| 180 |
.reverse() |
| 181 |
.toArray(); |
| 182 |
} |
| 183 |
|
| 184 |
async getAllNotifications() { |
| 185 |
return this.db.notifications |
| 186 |
.orderBy("time") // Efficient, see docs |
| 187 |
.reverse() |
| 188 |
.toArray(); |
| 189 |
} |
| 190 |
|
| 191 |
/** Adds notification, or returns false if it already exists */ |
| 192 |
async addNotification(subscriptionId, notification) { |
| 193 |
const exists = await this.db.notifications.get(notification.id); |
| 194 |
if (exists || notification.event === EVENT_MESSAGE_DELETE || notification.event === EVENT_MESSAGE_CLEAR) { |
| 195 |
return false; |
| 196 |
} |
| 197 |
try { |
| 198 |
// Note: Service worker (sw.js) and addNotifications() duplicates this logic, |
| 199 |
// so if you change it here, change it there too. |
| 200 |
|
| 201 |
// Add notification to database |
| 202 |
await this.db.notifications.add({ |
| 203 |
...messageWithSequenceId(notification), |
| 204 |
subscriptionId, |
| 205 |
new: 1, // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation |
| 206 |
}); |
| 207 |
|
| 208 |
// FIXME consider put() for double tab |
| 209 |
// Update subscription last message id (for ?since=... queries) |
| 210 |
await this.db.subscriptions.update(subscriptionId, { |
| 211 |
last: notification.id, |
| 212 |
}); |
| 213 |
} catch (e) { |
| 214 |
console.error(`[SubscriptionManager] Error adding notification`, e); |
| 215 |
} |
| 216 |
return true; |
| 217 |
} |
| 218 |
|
| 219 |
/** Adds/replaces notifications, will not throw if they exist */ |
| 220 |
async addNotifications(subscriptionId, notifications) { |
| 221 |
const notificationsWithSubscriptionId = notifications.map((notification) => ({ |
| 222 |
...messageWithSequenceId(notification), |
| 223 |
subscriptionId, |
| 224 |
})); |
| 225 |
const lastNotificationId = notifications.at(-1).id; |
| 226 |
await this.db.notifications.bulkPut(notificationsWithSubscriptionId); |
| 227 |
await this.db.subscriptions.update(subscriptionId, { |
| 228 |
last: lastNotificationId, |
| 229 |
}); |
| 230 |
} |
| 231 |
|
| 232 |
async updateNotification(notification) { |
| 233 |
const exists = await this.db.notifications.get(notification.id); |
| 234 |
if (!exists) { |
| 235 |
return false; |
| 236 |
} |
| 237 |
try { |
| 238 |
await this.db.notifications.put({ ...notification }); |
| 239 |
} catch (e) { |
| 240 |
console.error(`[SubscriptionManager] Error updating notification`, e); |
| 241 |
} |
| 242 |
return true; |
| 243 |
} |
| 244 |
|
| 245 |
async deleteNotification(notificationId) { |
| 246 |
await this.db.notifications.delete(notificationId); |
| 247 |
} |
| 248 |
|
| 249 |
async deleteNotificationBySequenceId(subscriptionId, sequenceId) { |
| 250 |
await this.db.notifications.where({ subscriptionId, sequenceId }).delete(); |
| 251 |
} |
| 252 |
|
| 253 |
async deleteNotifications(subscriptionId) { |
| 254 |
await this.db.notifications.where({ subscriptionId }).delete(); |
| 255 |
} |
| 256 |
|
| 257 |
async markNotificationRead(notificationId) { |
| 258 |
await this.db.notifications.where({ id: notificationId }).modify({ new: 0 }); |
| 259 |
} |
| 260 |
|
| 261 |
async markNotificationReadBySequenceId(subscriptionId, sequenceId) { |
| 262 |
await this.db.notifications.where({ subscriptionId, sequenceId }).modify({ new: 0 }); |
| 263 |
} |
| 264 |
|
| 265 |
async markNotificationsRead(subscriptionId) { |
| 266 |
await this.db.notifications.where({ subscriptionId, new: 1 }).modify({ new: 0 }); |
| 267 |
} |
| 268 |
|
| 269 |
async setMutedUntil(subscriptionId, mutedUntil) { |
| 270 |
await this.db.subscriptions.update(subscriptionId, { |
| 271 |
mutedUntil, |
| 272 |
}); |
| 273 |
} |
| 274 |
|
| 275 |
async setDisplayName(subscriptionId, displayName) { |
| 276 |
await this.db.subscriptions.update(subscriptionId, { |
| 277 |
displayName, |
| 278 |
}); |
| 279 |
} |
| 280 |
|
| 281 |
async setReservation(subscriptionId, reservation) { |
| 282 |
await this.db.subscriptions.update(subscriptionId, { |
| 283 |
reservation, |
| 284 |
}); |
| 285 |
} |
| 286 |
|
| 287 |
async update(subscriptionId, params) { |
| 288 |
await this.db.subscriptions.update(subscriptionId, params); |
| 289 |
} |
| 290 |
|
| 291 |
async pruneNotifications(thresholdTimestamp) { |
| 292 |
await this.db.notifications.where("time").below(thresholdTimestamp).delete(); |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
export default new SubscriptionManager(db()); |