-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathUnifiedPushNotifications.ts
More file actions
1260 lines (1137 loc) · 39.8 KB
/
Copy pathUnifiedPushNotifications.ts
File metadata and controls
1260 lines (1137 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type IPusherRequest,
type MatrixClient,
MatrixEvent,
MatrixEventEvent,
} from '$types/matrix-sdk';
import { EventType } from 'matrix-js-sdk/lib/@types/event';
import {
resolveNotificationPreviewText,
ENCRYPTED_MESSAGE_PREVIEW,
} from '$utils/notificationStyle';
import { fetch } from '$utils/fetch';
import { getMxIdLocalPart } from '$utils/matrix';
import { getStateEvent } from '$utils/room/hierarchy';
import { createDebugLogger } from '$utils/debugLogger';
import type { DecryptedPushEvent } from '$app/crypto/pushDecrypt';
import { decryptPushEventNatively } from '$app/crypto/pushDecrypt';
import { pushAccount, type PushAccount } from './pushAccount';
import {
registerUnifiedPushTransport,
type UnifiedPushRegistrationResult,
unregisterUnifiedPushTransport,
} from './UnifiedPushTransport';
import {
createUnifiedPushMessageListener,
parseUnifiedPushMessage,
} from './UnifiedPushMessageListener';
import { addPluginListener, invoke, isTauri } from '@tauri-apps/api/core';
import { getSlidingSyncManager } from '$client/initMatrix';
import type { PushTransportConfig } from './NotificationTransport';
import { getTauriNotificationsApi, isMobileTauri } from './TauriNotificationsApiClient';
import {
resolvePushNotifyUrl,
withPushPayloadFormat,
type PushPusherSettings,
} from './PushPusherConfig';
import {
acknowledgeWebPushPusher,
getWebPushServerSupport,
isWebPushActivationPayload,
removeStaleHttpPushers,
} from './webPushSupport';
import { MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND } from '$unstable/prefixes';
const UP_PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
/** The in-app distributor relays through a public gateway unless one is configured. */
export const DEFAULT_EMBEDDED_GATEWAY = 'https://ntfy.sh';
export const DEFAULT_UNIFIED_PUSH_APP_ID = 'moe.sable.up';
const unifiedPushLog = createDebugLogger('unifiedpush');
/**
* Shape of a UnifiedPush payload delivered to the message listener.
* Fields are optional because both rich (full event) and minimal
* (event_id + counts) payloads arrive through the same entry point.
*/
type UnifiedPushPayload = {
type?: string;
content?: Record<string, unknown>;
room_id?: string;
room_name?: string;
sender_display_name?: string;
sender?: string;
event_id?: string;
user_id?: string;
counts?: { unread?: number };
notification?: unknown;
[key: string]: unknown;
};
const UP_REGISTER_TIMEOUT_MS = 30_000;
// Android freezes a channel's importance at creation, so raising `messages` from
// Default to High needs a new id. Mirrored in the plugin's UnifiedPushNotifier.
const MESSAGES_CHANNEL_ID = 'messages.v2';
const INVITES_CHANNEL_ID = 'invites';
const LEGACY_MESSAGES_CHANNEL_ID = 'messages';
async function ensureNotificationChannels(
notificationsApi: Awaited<ReturnType<typeof getTauriNotificationsApi>>
): Promise<void> {
await notificationsApi.createChannel({
id: MESSAGES_CHANNEL_ID,
name: 'Messages',
description: 'Matrix message notifications',
importance: notificationsApi.Importance.High,
vibration: true,
});
await notificationsApi.createChannel({
id: INVITES_CHANNEL_ID,
name: 'Invitations',
description: 'Room and space invitations',
importance: notificationsApi.Importance.Default,
vibration: true,
});
await notificationsApi.removeChannel(LEGACY_MESSAGES_CHANNEL_ID).catch(() => {
// Never created on this device, or already gone.
});
}
export type UnifiedPushTransportConfigInput = Pick<
PushTransportConfig,
'unifiedPushGatewayUrl' | 'unifiedPushAppID' | 'unifiedPushEmbeddedServerUrl'
> & {
vapidPublicKey?: string;
webPushAppID?: string;
pushNotifyUrl?: string;
} & PushPusherSettings;
type UnifiedPushPusherConfig = {
appId: string;
gatewayUrl?: string;
};
function trimConfigValue(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed || undefined;
}
function resolveUnifiedPushPusherConfig(
config?: UnifiedPushTransportConfigInput
): UnifiedPushPusherConfig {
return {
appId: trimConfigValue(config?.unifiedPushAppID) ?? DEFAULT_UNIFIED_PUSH_APP_ID,
gatewayUrl: trimConfigValue(config?.unifiedPushGatewayUrl),
};
}
export type EnableUnifiedPushResult =
| {
status: 'registered';
endpoint: string;
gatewayUrl: string;
distributor: string;
}
| Exclude<UnifiedPushRegistrationResult, { status: 'registered' }>;
async function registerUnifiedPushWithTimeout(
vapid?: string,
embeddedServerUrl?: string,
account?: PushAccount
): Promise<UnifiedPushRegistrationResult> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error('UnifiedPush registration timed out'));
}, UP_REGISTER_TIMEOUT_MS);
});
try {
return await Promise.race([
registerUnifiedPushTransport(vapid, embeddedServerUrl, account),
timeout,
]);
} finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
}
}
/**
* A provider that speaks the Matrix push protocol answers `/_matrix/push/v1/notify`
* with `unifiedpush.gateway == "matrix"`. Preferring it keeps delivery on the provider
* the endpoint already belongs to.
*/
export async function discoverPushGateway(endpoint: string): Promise<string> {
let candidate: string;
try {
candidate = new URL('/_matrix/push/v1/notify', endpoint).toString();
} catch {
return UP_PUBLIC_GATEWAY;
}
const controller = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
(async () => {
const response = await fetch(candidate, { method: 'GET', signal: controller.signal });
if (!response.ok) return UP_PUBLIC_GATEWAY;
const body = (await response.json()) as { unifiedpush?: { gateway?: unknown } };
return body?.unifiedpush?.gateway === 'matrix' ? candidate : UP_PUBLIC_GATEWAY;
})(),
new Promise<string>((resolve) => {
timeoutId = setTimeout(() => {
resolve(UP_PUBLIC_GATEWAY);
controller.abort();
}, 5000);
}),
]);
} catch {
// Unreachable or not JSON: the provider does not proxy.
} finally {
if (timeoutId !== undefined) clearTimeout(timeoutId);
}
return UP_PUBLIC_GATEWAY;
}
export async function tryEnableUnifiedPush(
mx: MatrixClient,
config?: UnifiedPushTransportConfigInput
): Promise<EnableUnifiedPushResult> {
const notificationsApi = await getTauriNotificationsApi();
await ensureNotificationChannels(notificationsApi);
// MSC4174: subscribe with the homeserver VAPID key when it pushes directly.
const webPushSupport = await getWebPushServerSupport(mx);
const vapid = webPushSupport.supported ? webPushSupport.vapidPublicKey : config?.vapidPublicKey;
const registration = await registerUnifiedPushWithTimeout(
vapid,
trimConfigValue(config?.unifiedPushEmbeddedServerUrl) ?? DEFAULT_EMBEDDED_GATEWAY,
pushAccount(mx)
);
if (registration.status !== 'registered') {
return registration;
}
const { endpoint } = registration;
const deviceDisplayName =
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Android Device';
if (registration.p256dh && registration.auth && config?.webPushAppID) {
if (webPushSupport.supported) {
// MSC4174: data.url is the distributor's push endpoint, not a gateway.
await mx.setPusher({
kind: MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND,
app_id: config.webPushAppID,
pushkey: registration.p256dh,
app_display_name: 'Sable (UnifiedPush)',
device_display_name: deviceDisplayName,
lang: navigator.language || 'en',
data: withPushPayloadFormat(
{
url: endpoint,
auth: registration.auth,
default_payload: { user_id: mx.getSafeUserId() },
},
config?.useRichPushPayloads
),
append: false,
} as unknown as IPusherRequest);
await removeStaleHttpPushers(mx, config.webPushAppID, [deviceDisplayName]);
return {
status: 'registered',
endpoint,
gatewayUrl: endpoint,
distributor: registration.distributor,
};
}
if (config?.pushNotifyUrl) {
const pushNotifyUrl = resolvePushNotifyUrl(
config.pushNotifyUrl,
config?.pushNotifyUrlOverride
);
await mx.setPusher({
kind: 'http',
app_id: config.webPushAppID,
pushkey: registration.p256dh,
app_display_name: 'Sable (UnifiedPush)',
device_display_name: deviceDisplayName,
lang: navigator.language || 'en',
data: withPushPayloadFormat(
{
url: pushNotifyUrl,
endpoint,
p256dh: registration.p256dh,
auth: registration.auth,
default_payload: { user_id: mx.getSafeUserId() },
},
config?.useRichPushPayloads
),
append: false,
} as unknown as IPusherRequest);
return {
status: 'registered',
endpoint,
gatewayUrl: pushNotifyUrl,
distributor: registration.distributor,
};
}
}
const resolvedConfig = resolveUnifiedPushPusherConfig(config);
const gatewayUrl = resolvedConfig.gatewayUrl ?? (await discoverPushGateway(endpoint));
await mx.setPusher({
kind: 'http',
app_id: resolvedConfig.appId,
pushkey: endpoint,
app_display_name: 'Sable (UnifiedPush)',
device_display_name: deviceDisplayName,
lang: navigator.language || 'en',
data: withPushPayloadFormat(
{ url: gatewayUrl, default_payload: { user_id: mx.getSafeUserId() } },
config?.useRichPushPayloads
),
append: false,
} as unknown as IPusherRequest);
return {
status: 'registered',
endpoint,
gatewayUrl,
distributor: registration.distributor,
};
}
export async function enableUnifiedPush(
mx: MatrixClient,
config?: UnifiedPushTransportConfigInput
): Promise<{ endpoint: string; gatewayUrl: string }> {
const result = await tryEnableUnifiedPush(mx, config);
if (result.status !== 'registered') {
throw new Error(result.error ?? 'UnifiedPush registration failed');
}
return {
endpoint: result.endpoint,
gatewayUrl: result.gatewayUrl,
};
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0;
}
async function getCurrentDeviceUnifiedPushPushkeys(
mx: MatrixClient,
appId: string
): Promise<string[]> {
const deviceId = mx.getDeviceId() ?? '';
if (!deviceId) {
return [];
}
const currentDevice = await mx.getDevice(deviceId);
const deviceDisplayName = currentDevice?.display_name;
if (!deviceDisplayName) {
return [];
}
const response = await mx.getPushers();
const pushers = response.pushers ?? [];
return pushers
.filter(
(pusher) =>
pusher.app_id === appId &&
pusher.device_display_name === deviceDisplayName &&
(pusher.kind === 'http' || pusher.kind === MATRIX_UNSTABLE_MSC4174_WEBPUSH_PUSHER_KIND) &&
isNonEmptyString(pusher.pushkey)
)
.map((pusher) => pusher.pushkey);
}
async function getUnifiedPushCleanupPushkeys(
mx: MatrixClient,
appId: string,
pushkey?: string
): Promise<string[]> {
const pushkeys = new Set<string>();
if (isNonEmptyString(pushkey)) {
pushkeys.add(pushkey);
}
const currentDevicePushkeys = await getCurrentDeviceUnifiedPushPushkeys(mx, appId);
currentDevicePushkeys.forEach((candidate) => pushkeys.add(candidate));
return Array.from(pushkeys);
}
export type DisableUnifiedPushOptions = {
config?: UnifiedPushTransportConfigInput;
pushkey?: string;
};
export async function disableUnifiedPush(
mx: MatrixClient,
options: DisableUnifiedPushOptions = {}
): Promise<void> {
const { appId } = resolveUnifiedPushPusherConfig(options.config);
const pushkeys = await getUnifiedPushCleanupPushkeys(mx, appId, options.pushkey);
await Promise.allSettled(
pushkeys.map((pushkey) =>
mx.setPusher({
kind: null,
app_id: appId,
pushkey,
} as unknown as IPusherRequest)
)
);
const webPushAppId = trimConfigValue(options.config?.webPushAppID);
if (webPushAppId && webPushAppId !== appId) {
const webPushKeys = await getCurrentDeviceUnifiedPushPushkeys(mx, webPushAppId);
await Promise.allSettled(
webPushKeys.map((pushkey) =>
mx.setPusher({
kind: null,
app_id: webPushAppId,
pushkey,
} as unknown as IPusherRequest)
)
);
}
await unregisterUnifiedPushTransport();
}
type NotificationSettings = {
mx: MatrixClient;
showMessageContent: boolean;
showEncryptedMessageContent: boolean;
notificationSoundEnabled: boolean;
useInAppNotifications: boolean;
};
const NOTIF_GROUP_KEY = 'matrix_messages';
const MAX_MESSAGES = 10;
const MAX_SEEN_EVENT_IDS = 200;
const ENCRYPTED_PREVIEW_RETRY_WINDOW_MS = 5 * 60_000;
type NotifPerson = {
name: string;
key?: string;
};
type NotifMessage = {
text: string;
timestamp: number;
sender?: NotifPerson;
};
function hashCode(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i += 1) {
// eslint-disable-next-line no-bitwise
hash = (Math.imul(31, hash) + str.charCodeAt(i)) | 0;
}
return Math.abs(hash);
}
async function resolvePreviewEvent(
mx: MatrixClient,
roomId: string,
eventId: string
): Promise<MatrixEvent | undefined> {
try {
const evt = await mx.fetchRoomEvent(roomId, eventId);
const mEvent = new MatrixEvent(evt);
if (mEvent.isEncrypted()) {
await mx.decryptEventIfNeeded(mEvent);
}
return mEvent;
} catch (error) {
unifiedPushLog.warn(
'notification',
'Failed to fetch/decrypt event for push preview',
error instanceof Error ? error : new Error(String(error))
);
return undefined;
}
}
/**
* Rebuilds the encrypted event from a rich push payload so it can be decrypted
* locally — no homeserver fetch needed, the Megolm keys are in the crypto store.
*/
function buildEncryptedPreviewEvent(
roomId: string,
eventId: string,
pushData: UnifiedPushPayload
): MatrixEvent | undefined {
if (!pushData.content) return undefined;
return new MatrixEvent({
type: 'm.room.encrypted',
content: pushData.content,
room_id: roomId,
event_id: eventId,
sender: pushData.sender,
origin_server_ts: Date.now(),
});
}
function holdsPlaintext(event: MatrixEvent): boolean {
return (
!event.isDecryptionFailure() && event.getType() !== EventType.RoomMessageEncrypted.toString()
);
}
/**
* Runs `apply` as soon as `event` holds plaintext: right away when it is already
* decrypted, or later once the Megolm key arrives — a backgrounded app routinely
* receives the push before the to-device key, and the SDK retries decryption on
* its own when the key lands.
*/
function whenDecrypted(event: MatrixEvent, apply: () => Promise<void>): void {
if (holdsPlaintext(event)) {
void apply();
return;
}
const onDecrypted = () => {
if (!holdsPlaintext(event)) return;
event.off(MatrixEventEvent.Decrypted, onDecrypted);
clearTimeout(retryWindowTimer);
void apply();
};
event.on(MatrixEventEvent.Decrypted, onDecrypted);
const retryWindowTimer = setTimeout(() => {
event.off(MatrixEventEvent.Decrypted, onDecrypted);
unifiedPushLog.warn('notification', 'Encrypted preview never decrypted within retry window');
}, ENCRYPTED_PREVIEW_RETRY_WINDOW_MS);
}
const roomNotifId = (userId: string, roomId: string) => hashCode(`${userId}\u0000${roomId}`);
const summaryNotifId = (userId: string) => hashCode(`sable-group-summary\u0000${userId}`);
type RoomNotifCache = {
key: string;
generation: number;
roomName: string;
messages: NotifMessage[];
pendingEventIds: Set<string>;
seenEventIds: Set<string>;
isGroupConversation: boolean;
};
const roomNotifCaches = new Map<string, RoomNotifCache>();
const roomNotifGenerations = new Map<string, number>();
const roomNotifQueues = new Map<string, Promise<void>>();
function enqueueRoomOperation<T>(key: string, operation: () => Promise<T>): Promise<T> {
const previous = roomNotifQueues.get(key) ?? Promise.resolve();
const task = previous.then(operation, operation);
const completion = task.then(
() => undefined,
() => undefined
);
roomNotifQueues.set(key, completion);
void completion.then(() => {
if (roomNotifQueues.get(key) === completion) roomNotifQueues.delete(key);
});
return task;
}
function getOrCreateRoomCache(userId: string, roomId: string, roomName: string): RoomNotifCache {
const key = `${userId}\u0000${roomId}`;
let cache = roomNotifCaches.get(key);
if (!cache) {
cache = {
key,
generation: roomNotifGenerations.get(key) ?? 0,
roomName,
messages: [],
pendingEventIds: new Set(),
seenEventIds: new Set(),
isGroupConversation: false,
};
roomNotifCaches.set(key, cache);
}
cache.roomName = roomName;
return cache;
}
function isCurrentRoomCache(cache: RoomNotifCache): boolean {
return (
roomNotifCaches.get(cache.key) === cache &&
(roomNotifGenerations.get(cache.key) ?? 0) === cache.generation
);
}
export function resetUnifiedPushNotificationStateForTests(): void {
roomNotifCaches.clear();
roomNotifGenerations.clear();
roomNotifQueues.clear();
}
// Older versions posted an account-level summary that collapsed every room into
// one entry; Android bundles the per-room notifications on its own.
async function dismissLegacyGroupSummary(userId: string): Promise<void> {
if (!userId) return;
try {
const notificationsApi = await getTauriNotificationsApi();
await notificationsApi.removeActive([{ id: summaryNotifId(userId) }]);
} catch {
// Nothing to dismiss, or the plugin is unavailable.
}
}
export async function clearRoomNotification(userId: string, roomId: string) {
const key = `${userId}\u0000${roomId}`;
await enqueueRoomOperation(key, async () => {
roomNotifCaches.delete(key);
roomNotifGenerations.set(key, (roomNotifGenerations.get(key) ?? 0) + 1);
try {
const notificationsApi = await getTauriNotificationsApi();
await notificationsApi.removeActive([{ id: roomNotifId(userId, roomId) }]);
} catch {
// already dismissed
}
});
}
async function postRoomNotification(
userId: string,
roomId: string,
cache: RoomNotifCache,
isSilent: boolean,
extra: Record<string, unknown>,
isCurrent?: () => boolean
): Promise<boolean> {
const notificationsApi = await getTauriNotificationsApi();
if (isCurrent && !isCurrent()) return false;
const { messages, roomName } = cache;
const latestMsg = messages[messages.length - 1];
const latestBody = latestMsg ? `${latestMsg.sender?.name ?? 'You'}: ${latestMsg.text}` : '';
const inboxLines = messages.slice(-5).map((m) => `${m.sender?.name ?? 'You'}: ${m.text}`);
await notificationsApi.sendNotification({
id: roomNotifId(userId, roomId),
title: roomName,
body: latestBody,
channelId: MESSAGES_CHANNEL_ID,
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
extra,
...(isMobileTauri() ? { actionTypeId: 'sable-message' } : {}),
// Android renders these as a conversation; inbox/big-text covers the rest.
messages: messages.map((m) => ({
body: m.text,
timestamp: m.timestamp,
senderName: m.sender?.name,
senderKey: m.sender?.key,
})),
groupConversation: cache.isGroupConversation,
inboxLines: inboxLines.length > 1 ? inboxLines : undefined,
largeBody: inboxLines.length > 1 ? undefined : latestBody,
});
return true;
}
async function handleRichPushPayload(
pushData: UnifiedPushPayload,
settings: NotificationSettings,
userId: string,
getSettings: () => NotificationSettings
) {
const eventType = pushData.type as EventType;
switch (eventType) {
case EventType.RoomMessage:
case EventType.Sticker:
case EventType.RoomMessageEncrypted: {
const isEncrypted = eventType === EventType.RoomMessageEncrypted;
let previewText = resolveNotificationPreviewText({
content: pushData?.content,
eventType: pushData?.type,
isEncryptedRoom: isEncrypted,
showMessageContent: settings.showMessageContent,
showEncryptedMessageContent: settings.showEncryptedMessageContent,
});
const roomId: string | undefined = pushData?.room_id;
const currentRoom = roomId ? settings.mx.getRoom(roomId) : undefined;
const roomName: string =
pushData?.room_name || currentRoom?.name || pushData?.sender_display_name || 'Unknown Room';
const senderId: string | undefined = pushData?.sender;
const senderName =
pushData?.sender_display_name ||
(senderId
? currentRoom?.getMember(senderId)?.name || getMxIdLocalPart(senderId) || senderId
: undefined);
const isSilent = !settings.notificationSoundEnabled;
if (!roomId) {
const notificationsApi = await getTauriNotificationsApi();
await notificationsApi.sendNotification({
title: roomName,
body: senderName ? `${senderName}: ${previewText}` : previewText,
channelId: MESSAGES_CHANNEL_ID,
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
});
break;
}
const eventId: string | undefined = pushData?.event_id;
let needsEncryptedPreviewEnrichment = false;
if (
previewText === ENCRYPTED_MESSAGE_PREVIEW &&
eventId &&
settings.showMessageContent &&
settings.showEncryptedMessageContent
) {
// Try local timeline first (decryption already done by SDK).
const room = settings.mx.getRoom(roomId);
const mEvent = room
?.getLiveTimeline()
.getEvents()
.find((e) => e.getId() === eventId);
if (mEvent) {
previewText = resolveNotificationPreviewText({
content: mEvent.getContent(),
eventType: mEvent.getType(),
isEncryptedRoom: true,
showMessageContent: settings.showMessageContent,
showEncryptedMessageContent: settings.showEncryptedMessageContent,
});
needsEncryptedPreviewEnrichment =
mEvent.getType() === EventType.RoomMessageEncrypted.toString();
} else {
needsEncryptedPreviewEnrichment = true;
}
}
const sender: NotifPerson | undefined = senderName
? { name: senderName, key: senderId }
: undefined;
const message: NotifMessage = {
text: previewText,
timestamp: Date.now(),
sender,
};
const key = `${userId}\u0000${roomId}`;
let enrichmentCache: RoomNotifCache | undefined;
let enrichmentMessage: NotifMessage | undefined;
const posted = await enqueueRoomOperation(key, async () => {
const cache = getOrCreateRoomCache(userId, roomId, roomName);
if (eventId && (cache.pendingEventIds.has(eventId) || cache.seenEventIds.has(eventId))) {
return false;
}
if (eventId) cache.pendingEventIds.add(eventId);
const previousMessages = cache.messages.slice();
cache.messages.push(message);
if (cache.messages.length > MAX_MESSAGES) {
cache.messages = cache.messages.slice(-MAX_MESSAGES);
}
cache.isGroupConversation =
Boolean(pushData?.room_name || currentRoom?.name) ||
(currentRoom?.getJoinedMemberCount() ?? 0) > 2;
try {
await postRoomNotification(userId, roomId, cache, isSilent, {
room_id: roomId,
event_id: pushData?.event_id,
user_id: pushData?.user_id,
});
} catch {
cache.messages = previousMessages;
if (eventId) cache.pendingEventIds.delete(eventId);
if (cache.messages.length === 0) roomNotifCaches.delete(cache.key);
unifiedPushLog.warn('notification', 'UnifiedPush baseline notification failed');
return false;
}
if (eventId) {
cache.pendingEventIds.delete(eventId);
cache.seenEventIds.add(eventId);
if (cache.seenEventIds.size > MAX_SEEN_EVENT_IDS) {
const oldest = cache.seenEventIds.values().next().value;
if (oldest !== undefined) cache.seenEventIds.delete(oldest);
}
}
enrichmentCache = cache;
enrichmentMessage = message;
return true;
});
if (
posted &&
needsEncryptedPreviewEnrichment &&
eventId &&
enrichmentCache &&
enrichmentMessage
) {
scheduleEncryptedPreviewEnrichment(
pushData,
roomId,
eventId,
enrichmentCache,
enrichmentMessage,
userId,
getSettings
);
}
break;
}
case EventType.RoomMember: {
if (pushData?.content?.membership !== 'invite') break;
const senderName: string | undefined = pushData?.sender_display_name;
const roomName: string | undefined = pushData?.room_name;
let body = '';
if (senderName && roomName) body = `${senderName} invites you to ${roomName}`;
else if (senderName) body = `from ${senderName}`;
else if (roomName) body = `to ${roomName}`;
const notificationsApi = await getTauriNotificationsApi();
await notificationsApi.sendNotification({
title: 'New Invitation',
body,
largeBody: body,
channelId: INVITES_CHANNEL_ID,
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
autoCancel: true,
extra: {
type: 'invite',
room_id: pushData?.room_id,
event_id: pushData?.event_id,
user_id: pushData?.user_id,
},
});
break;
}
default:
break;
}
}
function scheduleEncryptedPreviewEnrichment(
pushData: UnifiedPushPayload,
roomId: string,
eventId: string,
cache: RoomNotifCache,
message: NotifMessage,
userId: string,
getSettings: () => NotificationSettings
): void {
const initialSettings = getSettings();
if (!initialSettings.showMessageContent || !initialSettings.showEncryptedMessageContent) return;
const crypto = initialSettings.mx.getCrypto();
const encryptedContent = pushData.content;
const decrypted = buildEncryptedPreviewEvent(roomId, eventId, pushData);
if (!crypto || !decrypted || !encryptedContent) return;
const applyDecryptedPreview = async (plaintext: DecryptedPushEvent): Promise<void> => {
await enqueueRoomOperation(cache.key, async () => {
const liveSettings = getSettings();
const isAllowed =
liveSettings.showMessageContent &&
liveSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && liveSettings.useInAppNotifications);
if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) {
return;
}
const enrichedPreview = resolveNotificationPreviewText({
content: plaintext.content,
eventType: plaintext.eventType,
isEncryptedRoom: true,
showMessageContent: liveSettings.showMessageContent,
showEncryptedMessageContent: liveSettings.showEncryptedMessageContent,
});
if (!enrichedPreview || enrichedPreview === ENCRYPTED_MESSAGE_PREVIEW) return;
const liveRoom = liveSettings.mx.getRoom(roomId);
const decryptedSender = plaintext.sender;
const senderName = decryptedSender
? (liveRoom?.getMember(decryptedSender)?.name ??
getMxIdLocalPart(decryptedSender) ??
decryptedSender)
: undefined;
const previousText = message.text;
const previousSender = message.sender;
message.text = enrichedPreview;
message.sender = senderName ? { name: senderName, key: decryptedSender } : message.sender;
const current = () => {
const currentSettings = getSettings();
return (
isCurrentRoomCache(cache) &&
cache.messages.includes(message) &&
currentSettings.showMessageContent &&
currentSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && currentSettings.useInAppNotifications)
);
};
try {
const posted = await postRoomNotification(
userId,
roomId,
cache,
true,
{
room_id: roomId,
event_id: eventId,
user_id: pushData?.user_id,
},
current
);
if (!posted) {
message.text = previousText;
message.sender = previousSender;
}
} catch {
message.text = previousText;
message.sender = previousSender;
}
});
};
const fallBackToSdkDecryption = (): void => {
whenDecrypted(decrypted, () =>
applyDecryptedPreview({
content: decrypted.getContent(),
eventType: decrypted.getType(),
sender: decrypted.getSender(),
})
);
void initialSettings.mx.decryptEventIfNeeded(decrypted).catch(() => {
unifiedPushLog.warn('notification', 'Encrypted preview decryption failed');
});
};
// The engine reads the crypto store directly, so it answers without waiting on the SDK
// pipeline; it returns null exactly in the late-key case the SDK path retries.
void decryptPushEventNatively(initialSettings.mx.getUserId(), initialSettings.mx.getDeviceId(), {
roomId,
eventId,
sender: pushData.sender,
content: encryptedContent,
})
.then((plaintext) => {
if (plaintext) {
void applyDecryptedPreview(plaintext);
return;
}
fallBackToSdkDecryption();
})
// Without this the preview would stay at its "Encrypted message" baseline forever.
.catch(fallBackToSdkDecryption);
}
async function handleMinimalPushPayload(
pushData: UnifiedPushPayload,
settings: NotificationSettings,
userId: string,
getSettings: () => NotificationSettings
) {
const roomId: string | undefined = pushData?.room_id;
const eventId: string | undefined = pushData?.event_id;
const unread: number | undefined =
typeof pushData?.counts?.unread === 'number' ? pushData.counts.unread : undefined;
if (!roomId) return;
// Unread count of zero means the room was read — dismiss the notification.
if (unread === 0) {
await clearRoomNotification(userId, roomId);
return;
}
const room = settings.mx.getRoom(roomId);
const roomName =
room?.name || pushData?.room_name || pushData?.sender_display_name || 'Unknown Room';
const isEncryptedRoom = room ? !!getStateEvent(room, EventType.RoomEncryption) : false;
let senderId = pushData?.sender;
let senderName =
pushData?.sender_display_name ||
(senderId
? room?.getMember(senderId)?.name || getMxIdLocalPart(senderId) || senderId
: undefined);
let previewText: string | undefined;
let inMemoryStillEncrypted = false;
if (room && eventId) {
const timeline = room.getLiveTimeline().getEvents();
const mEvent = timeline.find((e) => e.getId() === eventId);
if (mEvent) {
inMemoryStillEncrypted = !holdsPlaintext(mEvent);
const sender = mEvent.getSender();
if (sender) {
const member = room.getMember(sender);
senderName = member?.name ?? getMxIdLocalPart(sender) ?? sender;
senderId = sender;
}
previewText = resolveNotificationPreviewText({
content: mEvent.getContent(),
eventType: mEvent.getType(),
isEncryptedRoom,