SubscriptionManager.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. class SubscriptionManager {
  7. constructor(dbImpl) {
  8. this.db = dbImpl;
  9. }
  10. /** All subscriptions, including "new count"; this is a JOIN, see https://dexie.org/docs/API-Reference#joining */
  11. async all() {
  12. const subscriptions = await this.db.subscriptions.toArray();
  13. return Promise.all(
  14. subscriptions.map(async (s) => ({
  15. ...s,
  16. new: await this.db.notifications.where({ subscriptionId: s.id, new: 1 }).count(),
  17. }))
  18. );
  19. }
  20. /**
  21. * List of topics for which Web Push is enabled. This excludes (a) internal topics, (b) topics that are muted,
  22. * and (c) topics from other hosts. Returns an empty list if Web Push is disabled.
  23. *
  24. * It is important to note that "mutedUntil" must be part of the where() query, otherwise the Dexie live query
  25. * will not react to it, and the Web Push topics will not be updated when the user mutes a topic.
  26. */
  27. async webPushTopics(pushPossible) {
  28. if (!pushPossible) {
  29. return [];
  30. }
  31. // the Promise.resolve wrapper is not superfluous, without it the live query breaks:
  32. // https://dexie.org/docs/dexie-react-hooks/useLiveQuery()#calling-non-dexie-apis-from-querier
  33. const enabled = await Promise.resolve(prefs.webPushEnabled());
  34. if (!enabled) {
  35. return [];
  36. }
  37. const subscriptions = await this.db.subscriptions.where({ baseUrl: config.base_url, mutedUntil: 0 }).toArray();
  38. return subscriptions.filter(({ internal }) => !internal).map(({ topic }) => topic);
  39. }
  40. async get(subscriptionId) {
  41. return this.db.subscriptions.get(subscriptionId);
  42. }
  43. async notify(subscriptionId, notification) {
  44. const subscription = await this.get(subscriptionId);
  45. if (subscription.mutedUntil > 0) {
  46. return;
  47. }
  48. const priority = notification.priority ?? 3;
  49. if (priority < (await prefs.minPriority())) {
  50. return;
  51. }
  52. await notifier.notify(subscription, notification);
  53. }
  54. /**
  55. * @param {string} baseUrl
  56. * @param {string} topic
  57. * @param {object} opts
  58. * @param {boolean} opts.internal
  59. * @returns
  60. */
  61. async add(baseUrl, topic, opts = {}) {
  62. const id = topicUrl(baseUrl, topic);
  63. const existingSubscription = await this.get(id);
  64. if (existingSubscription) {
  65. return existingSubscription;
  66. }
  67. const subscription = {
  68. ...opts,
  69. id: topicUrl(baseUrl, topic),
  70. baseUrl,
  71. topic,
  72. mutedUntil: 0,
  73. last: null,
  74. };
  75. await this.db.subscriptions.put(subscription);
  76. return subscription;
  77. }
  78. async syncFromRemote(remoteSubscriptions, remoteReservations) {
  79. console.log(`[SubscriptionManager] Syncing subscriptions from remote`, remoteSubscriptions);
  80. // Add remote subscriptions
  81. const remoteIds = await Promise.all(
  82. remoteSubscriptions.map(async (remote) => {
  83. const reservation = remoteReservations?.find((r) => remote.base_url === config.base_url && remote.topic === r.topic) || null;
  84. const local = await this.add(remote.base_url, remote.topic, {
  85. displayName: remote.display_name, // May be undefined
  86. reservation, // May be null!
  87. });
  88. return local.id;
  89. })
  90. );
  91. // Remove local subscriptions that do not exist remotely
  92. const localSubscriptions = await this.db.subscriptions.toArray();
  93. await Promise.all(
  94. localSubscriptions.map(async (local) => {
  95. const remoteExists = remoteIds.includes(local.id);
  96. if (!local.internal && !remoteExists) {
  97. await this.remove(local);
  98. }
  99. })
  100. );
  101. }
  102. async updateWebPushSubscriptions(topics) {
  103. const hasWebPushTopics = topics.length > 0;
  104. const browserSubscription = await notifier.webPushSubscription(hasWebPushTopics);
  105. if (!browserSubscription) {
  106. console.log(
  107. "[SubscriptionManager] No browser subscription currently exists, so web push was never enabled or the notification permission was removed. Skipping."
  108. );
  109. return;
  110. }
  111. if (hasWebPushTopics) {
  112. await api.updateWebPush(browserSubscription, topics);
  113. } else {
  114. await api.deleteWebPush(browserSubscription);
  115. }
  116. }
  117. async updateState(subscriptionId, state) {
  118. this.db.subscriptions.update(subscriptionId, { state });
  119. }
  120. async remove(subscription) {
  121. await this.db.subscriptions.delete(subscription.id);
  122. await this.db.notifications.where({ subscriptionId: subscription.id }).delete();
  123. }
  124. async first() {
  125. return this.db.subscriptions.toCollection().first(); // May be undefined
  126. }
  127. async getNotifications(subscriptionId) {
  128. // This is quite awkward, but it is the recommended approach as per the Dexie docs.
  129. // It's actually fine, because the reading and filtering is quite fast. The rendering is what's
  130. // killing performance. See https://dexie.org/docs/Collection/Collection.offset()#a-better-paging-approach
  131. const notifications = await this.db.notifications
  132. .orderBy("time") // Sort by time
  133. .filter((n) => n.subscriptionId === subscriptionId)
  134. .reverse()
  135. .toArray();
  136. return this.groupNotificationsBySID(notifications);
  137. }
  138. async getAllNotifications() {
  139. const notifications = await this.db.notifications
  140. .orderBy("time") // Efficient, see docs
  141. .reverse()
  142. .toArray();
  143. return this.groupNotificationsBySID(notifications);
  144. }
  145. // Collapse notification updates based on sids, keeping only the latest version
  146. // Filters out notifications where the latest in the sequence is deleted
  147. groupNotificationsBySID(notifications) {
  148. const latestBySid = {};
  149. notifications.forEach((notification) => {
  150. const key = `${notification.subscriptionId}:${notification.sid}`;
  151. // Keep only the first (latest by time) notification for each sid
  152. if (!(key in latestBySid)) {
  153. latestBySid[key] = notification;
  154. }
  155. });
  156. // Filter out notifications where the latest is deleted
  157. return Object.values(latestBySid).filter((n) => !n.deleted);
  158. }
  159. /** Adds notification, or returns false if it already exists */
  160. async addNotification(subscriptionId, notification) {
  161. const exists = await this.db.notifications.get(notification.id);
  162. if (exists) {
  163. return false;
  164. }
  165. try {
  166. const populatedNotification = notification;
  167. if (!("sid" in populatedNotification)) {
  168. populatedNotification.sid = notification.id;
  169. }
  170. // sw.js duplicates this logic, so if you change it here, change it there too
  171. await this.db.notifications.add({
  172. ...populatedNotification,
  173. subscriptionId,
  174. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  175. new: 1,
  176. }); // FIXME consider put() for double tab
  177. await this.db.subscriptions.update(subscriptionId, {
  178. last: notification.id,
  179. });
  180. } catch (e) {
  181. console.error(`[SubscriptionManager] Error adding notification`, e);
  182. }
  183. return true;
  184. }
  185. /** Adds/replaces notifications, will not throw if they exist */
  186. async addNotifications(subscriptionId, notifications) {
  187. const notificationsWithSubscriptionId = notifications.map((notification) => {
  188. const populatedNotification = notification;
  189. if (!("sid" in populatedNotification)) {
  190. populatedNotification.sid = notification.id;
  191. }
  192. return { ...populatedNotification, subscriptionId };
  193. });
  194. const lastNotificationId = notifications.at(-1).id;
  195. await this.db.notifications.bulkPut(notificationsWithSubscriptionId);
  196. await this.db.subscriptions.update(subscriptionId, {
  197. last: lastNotificationId,
  198. });
  199. }
  200. async updateNotification(notification) {
  201. const exists = await this.db.notifications.get(notification.id);
  202. if (!exists) {
  203. return false;
  204. }
  205. try {
  206. await this.db.notifications.put({ ...notification });
  207. } catch (e) {
  208. console.error(`[SubscriptionManager] Error updating notification`, e);
  209. }
  210. return true;
  211. }
  212. async deleteNotification(notificationId) {
  213. await this.db.notifications.delete(notificationId);
  214. }
  215. async deleteNotifications(subscriptionId) {
  216. await this.db.notifications.where({ subscriptionId }).delete();
  217. }
  218. async markNotificationRead(notificationId) {
  219. await this.db.notifications.where({ id: notificationId }).modify({ new: 0 });
  220. }
  221. async markNotificationsRead(subscriptionId) {
  222. await this.db.notifications.where({ subscriptionId, new: 1 }).modify({ new: 0 });
  223. }
  224. async setMutedUntil(subscriptionId, mutedUntil) {
  225. await this.db.subscriptions.update(subscriptionId, {
  226. mutedUntil,
  227. });
  228. }
  229. async setDisplayName(subscriptionId, displayName) {
  230. await this.db.subscriptions.update(subscriptionId, {
  231. displayName,
  232. });
  233. }
  234. async setReservation(subscriptionId, reservation) {
  235. await this.db.subscriptions.update(subscriptionId, {
  236. reservation,
  237. });
  238. }
  239. async update(subscriptionId, params) {
  240. await this.db.subscriptions.update(subscriptionId, params);
  241. }
  242. async pruneNotifications(thresholdTimestamp) {
  243. await this.db.notifications.where("time").below(thresholdTimestamp).delete();
  244. }
  245. }
  246. export default new SubscriptionManager(db());