From 143a1dd39b4df33e47bec43295de1d85227c1731 Mon Sep 17 00:00:00 2001 From: Jon Staab Date: Mon, 26 Jan 2026 11:12:15 -0800 Subject: [PATCH] Update notification subscriptions reactively --- package.json | 22 +-- pnpm-lock.yaml | Bin 346469 -> 346469 bytes src/app/components/ProfileCircles.svelte | 4 +- src/app/core/state.ts | 25 ++-- src/app/util/notifications.ts | 168 ++++++++++++++++++----- src/routes/+layout.svelte | 7 +- 6 files changed, 162 insertions(+), 64 deletions(-) diff --git a/package.json b/package.json index 8c4de29c..573cf39a 100644 --- a/package.json +++ b/package.json @@ -60,16 +60,16 @@ "@types/throttle-debounce": "^5.0.2", "@vite-pwa/assets-generator": "^0.2.6", "@vite-pwa/sveltekit": "^0.6.8", - "@welshman/app": "^0.8.1", - "@welshman/content": "^0.8.1", - "@welshman/editor": "^0.8.1", - "@welshman/feeds": "^0.8.1", - "@welshman/lib": "^0.8.1", - "@welshman/net": "^0.8.1", - "@welshman/router": "^0.8.1", - "@welshman/signer": "^0.8.1", - "@welshman/store": "^0.8.1", - "@welshman/util": "^0.8.1", + "@welshman/app": "^0.8.2", + "@welshman/content": "^0.8.2", + "@welshman/editor": "^0.8.2", + "@welshman/feeds": "^0.8.2", + "@welshman/lib": "^0.8.2", + "@welshman/net": "^0.8.2", + "@welshman/router": "^0.8.2", + "@welshman/signer": "^0.8.2", + "@welshman/store": "^0.8.2", + "@welshman/util": "^0.8.2", "compressorjs": "^1.2.1", "daisyui": "^4.12.24", "date-picker-svelte": "^2.17.0", @@ -79,7 +79,7 @@ "husky": "^9.1.7", "idb": "^8.0.3", "nostr-signer-capacitor-plugin": "^0.0.4", - "nostr-tools": "^2.19.4", + "nostr-tools": "^2.19.4", "prettier-plugin-tailwindcss": "^0.6.14", "qr-scanner": "^1.4.2", "qrcode": "^1.5.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 57ca8e3beb73db965eaea939325b05f926f64118..c39fe369573f7118b1cdc7e9b0cc45cf639d6953 100644 GIT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1E*vb`lP&LP`o?A8 zvM2qK<0Ab1Lp$b;O9(pJ93N(}K&`H@Y^$E83w8H))|5I!GNA_vpMehARgce*Jm!EQ zYsCn`Vp2`!T6}*uS!VaM01NQH|p*(n~8J^U1J!kv)0|eFGF<&xjq)4nUrHY z1wKe5-H}|HmU^D;SiZPbPjiy&saF{WtObNX(dAk6M}|CwG#{jb1mPWcyI45L4!4_T9dGt3;at#&Z;K(y zO*Dhauu&ZPBQ!1biB5_y4$DKKP}V|nCXw|~Dy{bMUZp>!JYr`vze|F}@u?Ov93K;W zy)Nt51{75#+xb*YOqc}I)zY<6wHb*UwFV!H^_x|?+6Z)U1~)@ZI;M6SY{z6$QBfYEX^Gucc&(Al$dtdHM)`7{?b|84 z0^hsmn1z82Wb;4Kt^13s@Zkn>V=T0W5_+DHciC_W$0D4TQF(W!qkFrlL|*W0^H@F@ zFhxD1M6vRgAaqD>z{#AKZOK~(pJ?;7#BPQvvO8)oILzmKS+Y&4^nuX(x%H{bx&*No zkrN~ETqRYklu0$#D>t_)T8*Juy&VjvLv$!oD{e)~)p&wWdr?Zy@&k94&v;5%B^-;& z6)Ht{Q6_`yM!VIe@V+M2+f^y)VW`lz zvGD9F_@=$ysKvScz_zt}t3bB-KBK3x-aq}p-ogeLfYJGltJ!|@HeGaY<{DUW97f{D zet`cUscUQX--$hG{azu!WyqZXF8J}Uz$|=30D5{1pKAKp1uy)C4`5Hz267}AOe3FF z1`b*?ds7?myC2zS^DjTJ`{n(5{*?Rt*BijLmroqX6$&hlzc|_jzcopRaV0->1H5!( z+)?9gJy>+XZ+{JlM#h=aLuN)_Xps5 Onb`z;%;wDeiGKq?ywC~& diff --git a/src/app/components/ProfileCircles.svelte b/src/app/components/ProfileCircles.svelte index 454afee7..f907ed6c 100644 --- a/src/app/components/ProfileCircles.svelte +++ b/src/app/components/ProfileCircles.svelte @@ -1,5 +1,6 @@
- {#each visiblePubkeys.toSorted().slice(0, 15) as pubkey (pubkey)} + {#each visiblePubkeys.toSorted().slice(0, limit) as pubkey (pubkey)}
diff --git a/src/app/core/state.ts b/src/app/core/state.ts index bb144c99..07ce75f0 100644 --- a/src/app/core/state.ts +++ b/src/app/core/state.ts @@ -338,19 +338,7 @@ export const relaysMostlyRestricted = writable>({}) // Push notifications export const notificationSettings = withGetter( - writable<{ - push: boolean - sound: boolean - badge: boolean - spaces: boolean - mentions: boolean - messages: boolean - token?: string - subscription?: { - key: string - callback: string - } - }>({ + writable({ push: false, sound: false, badge: false, @@ -360,6 +348,17 @@ export const notificationSettings = withGetter( }), ) +export const notificationState = withGetter( + writable<{ + token?: string + subscription?: { + key: string + callback: string + } + }>({}), +) + + // Chats export type Chat = { diff --git a/src/app/util/notifications.ts b/src/app/util/notifications.ts index c631b842..0f462947 100644 --- a/src/app/util/notifications.ts +++ b/src/app/util/notifications.ts @@ -4,7 +4,7 @@ import {Capacitor} from "@capacitor/core" import {Badge} from "@capawesome/capacitor-badge" import {PushNotifications} from "@capacitor/push-notifications" import type {ActionPerformed, RegistrationError, Token} from "@capacitor/push-notifications" -import {synced, throttled} from "@welshman/store" +import {synced, throttled, deriveDeduplicated, deriveDeduplicatedByValue} from "@welshman/store" import { pubkey, tracker, @@ -12,9 +12,9 @@ import { relaysByUrl, signer, publishThunk, - getPubkeyRelays, loadRelay, waitForThunkError, + userMessagingRelayList, } from "@welshman/app" import { on, @@ -32,6 +32,8 @@ import { now, groupBy, postJson, + nth, + nthEq, } from "@welshman/lib" import type {TrustedEvent, RelayProfile, Filter} from "@welshman/util" import {deriveEventsByIdByUrl} from "@welshman/store" @@ -40,12 +42,14 @@ import { EVENT_TIME, THREAD, COMMENT, + DELETE, getTagValue, getPubkeyTagValues, + getRelaysFromList, matchFilters, sortEventsDesc, makeEvent, - RelayMode, + Address, } from "@welshman/util" import {buildUrl} from "@lib/util" import { @@ -66,6 +70,7 @@ import { PUSH_BRIDGE, PUSH_SERVER, notificationSettings, + notificationState, chatsById, hasNip29, getSettings, @@ -75,6 +80,7 @@ import { getSpaceRoomsFromGroupList, makeCommentFilter, userSpaceUrls, + splitRoomId, makeRoomId, } from "@app/core/state" import {kv} from "@app/core/storage" @@ -342,6 +348,7 @@ if (Capacitor.isNativePlatform()) { PushNotifications.addListener( "pushNotificationActionPerformed", async (action: ActionPerformed) => { + console.log('=======', JSON.stringify(action)) const event = parseJson(action.notification.data.event) const relays = [action.notification.data.relay] @@ -362,7 +369,7 @@ class CapacitorNotifications implements IPushAdapter { return status.receive } - let {token} = notificationSettings.get() + let {token} = notificationState.get() if (!token) { PushNotifications.addListener("registration", ({value}: Token) => { @@ -381,32 +388,38 @@ class CapacitorNotifications implements IPushAdapter { }), ]) - notificationSettings.update(assoc("token", token)) + notificationState.update(assoc("token", token)) } return token ? "granted" : "denied" } async syncServer(signal: AbortSignal) { - const {token} = notificationSettings.get() + const {token, subscription} = notificationState.get() if (!token) { throw new Error("Attempted to sync push server without a token") } - const channel = Capacitor.getPlatform() === "ios" ? "apns" : "fcm" - const url = buildUrl(PUSH_SERVER, "subscription", channel) - const json = await postJson(url, {token}, {signal}) + if (!subscription) { + const channel = Capacitor.getPlatform() === "ios" ? "apns" : "fcm" + const url = buildUrl(PUSH_SERVER, "subscription", channel) + const json = await postJson(url, {token}, {signal}) - if (json?.callback && json?.id) { - notificationSettings.update(assoc("subscription", json)) - } else { - console.warn("Failed to register with push server") + if (json?.callback && json?.key) { + notificationState.update(assoc("subscription", json)) + } else { + console.warn("Failed to register with push server") + } } } async syncRelays(signal: AbortSignal) { - const {subscription} = notificationSettings.get() + const {subscription} = notificationState.get() + + if (signal.aborted) { + return + } if (!subscription) { throw new Error("Attempted to sync relays without a subscription") @@ -433,10 +446,6 @@ class CapacitorNotifications implements IPushAdapter { filters: Filter[], ignore: Filter[] = [], ) => { - if (signal.aborted) { - return - } - const stuff = await getPushStuff(relay) if (!stuff) { @@ -475,25 +484,114 @@ class CapacitorNotifications implements IPushAdapter { } } - for (const relay of get(userSpaceUrls)) { - const {muted_rooms} = getSettings() + const unsyncRelay = async (key: string, relay: string) => { + const stuff = await getPushStuff(relay) + + if (!stuff) { + console.warn(`Failed to unsubscribe ${relay} from ${key} notifications: unsupported`) + } else { + const identifier = String(hash(subscription.callback + relay + key)) + const address = new Address(30390, pubkey.get()!, identifier).toString() + + const thunk = publishThunk({ + signal, + relays: [stuff.url], + event: makeEvent(DELETE, {tags: [["a", address]]}), + }) + + const error = await waitForThunkError(thunk) + + if (error) { + console.warn(`Failed to unsubscribe ${relay} from ${key} notifications:`, error) + } + } + } + + const syncedSpaceUrls = new Set() + + const syncSpaceRelay = (url: string) => { + const {spaces, mentions} = notificationSettings.get() const filters = [{kinds: MESSAGE_KINDS}, makeCommentFilter(CONTENT_KINDS)] - const ignore = [{"#h": [muted_rooms]}] + const mutedRooms = getSettings().muted_rooms.map(splitRoomId).filter(nthEq(0, url)).map(nth(1)) - syncRelay("spaces", relay, filters, ignore) + if (spaces) { + syncRelay("spaces", url, filters, [{"#h": [mutedRooms]}]) + } else { + unsyncRelay("spaces", url) + } + + if (mentions) { + const mentionFilters = filters.map(assoc("#p", [pubkey.get()!])) + + if (!spaces) { + syncRelay("mentions", url, mentionFilters) + } else if (mutedRooms.length > 0) { + syncRelay("mentions", url, mentionFilters.map(assoc('#h', [mutedRooms]))) + } else { + unsyncRelay("mentions", url) + } + } else { + unsyncRelay("mentions", url) + } } - const $pubkey = pubkey.get()! + const syncSpaceRelays = () => { + const $userSpaceUrls = get(userSpaceUrls) + const {spaces, mentions} = notificationSettings.get() - for (const relay of getPubkeyRelays($pubkey, RelayMode.Messaging)) { - const filters = [{kinds: DM_KINDS, "#p": [$pubkey]}] + for (const url of $userSpaceUrls) { + syncSpaceRelay(url) + syncedSpaceUrls.add(url) + } - syncRelay("messages", relay, filters) + for (const url of syncedSpaceUrls) { + if (!$userSpaceUrls.includes(url)) { + unsyncRelay("spaces", url) + syncedSpaceUrls.delete(url) + } + } } + + const syncedMessagingUrls = new Set() + + const syncMessagingRelay = (url: string) => { + const {messages} = notificationSettings.get() + + if (messages) { + syncRelay("messages", url, [{kinds: DM_KINDS, "#p": [pubkey.get()!]}]) + } else { + unsyncRelay("messages", url) + } + } + + const syncMessagingRelays = () => { + const messagingRelayUrls = getRelaysFromList(get(userMessagingRelayList)) + + for (const url of messagingRelayUrls) { + syncMessagingRelay(url) + syncedMessagingUrls.add(url) + } + + for (const url of syncedMessagingUrls) { + if (!messagingRelayUrls.includes(url)) { + unsyncRelay("messages", url) + syncedMessagingUrls.delete(url) + } + } + } + + const unsubscribers = [ + userSpaceUrls.subscribe(syncSpaceRelays), + userMessagingRelayList.subscribe(syncMessagingRelays), + userSettingsValues.subscribe(syncSpaceRelays), + userSettingsValues.subscribe(syncMessagingRelays), + ] + + signal.addEventListener("abort", () => unsubscribers.forEach(call)) } start() { - const {token} = notificationSettings.get() + const {token} = notificationState.get() const controller = new AbortController() const {signal} = controller @@ -502,13 +600,8 @@ class CapacitorNotifications implements IPushAdapter { } else { call(async () => { try { - if (!notificationSettings.get().subscription) { - await this.syncServer(signal) - } - - if (notificationSettings.get().subscription) { - await this.syncRelays(signal) - } + await this.syncServer(signal) + await this.syncRelays(signal) } catch (e) { console.error(e) } @@ -523,9 +616,7 @@ class CapacitorNotifications implements IPushAdapter { } async disable() { - const {subscription, ...settings} = notificationSettings.get() - - await PushNotifications.unregister() + const {subscription} = notificationState.get() if (subscription) { const res = await fetch(buildUrl(PUSH_SERVER, "subscription", subscription.key), { @@ -537,7 +628,8 @@ class CapacitorNotifications implements IPushAdapter { } } - notificationSettings.set({...settings, push: false}) + notificationSettings.update(assoc('push', false)) + notificationState.set({}) } } diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index d51b5977..ae93d224 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -27,7 +27,7 @@ import {setupAnalytics} from "@app/util/analytics" import {authPolicy, blockPolicy, trustPolicy, mostlyRestrictedPolicy} from "@app/util/policies" import {kv, db} from "@app/core/storage" - import {userSettingsValues, notificationSettings} from "@app/core/state" + import {userSettingsValues, notificationSettings, notificationState} from "@app/core/state" import {syncApplicationData} from "@app/core/sync" import * as commands from "@app/core/commands" import * as requests from "@app/core/requests" @@ -107,6 +107,11 @@ store: notificationSettings, storage: kv, }), + sync({ + key: "notificationState", + store: notificationState, + storage: kv, + }), ]) // Set up our storage adapters