mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-06 00:32:26 -08:00
call notif improvements
This commit is contained in:
1 parent
0ba0b7f67c
commit
b74a8406fc
8 files changed
+463
-18
No files matched your search
@@ -37,6 +37,7 @@ import {
|
||||
type IncomingCall,
|
||||
} from '$state/callEmbed';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { dismissSystemCallNotifications } from '$features/call/callNotificationBridge';
|
||||
import { RoomAvatar } from './room-avatar';
|
||||
import { UserAvatar } from './user-avatar';
|
||||
|
||||
@@ -162,6 +163,7 @@ export function IncomingCallInternal({ room, incomingCall, onClose }: IncomingCa
|
||||
|
||||
setMutedRoomId(room.roomId);
|
||||
setAutoJoinIntent({ roomId: room.roomId, video: isVideoIntent });
|
||||
void dismissSystemCallNotifications(room.roomId);
|
||||
onClose();
|
||||
navigateRoom(room.roomId);
|
||||
};
|
||||
@@ -204,6 +206,7 @@ export function IncomingCallInternal({ room, incomingCall, onClose }: IncomingCa
|
||||
}
|
||||
|
||||
setMutedRoomId(room.roomId);
|
||||
void dismissSystemCallNotifications(room.roomId);
|
||||
onClose();
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveIncomingCallFromNotificationData,
|
||||
resolveIncomingCallFromSearchParams,
|
||||
} from './callNotificationBridge';
|
||||
|
||||
describe('callNotificationBridge', () => {
|
||||
it('hydrates incoming call from notification click payload', () => {
|
||||
const now = 1_000_000;
|
||||
const incoming = resolveIncomingCallFromNotificationData(
|
||||
{
|
||||
isCall: true,
|
||||
roomId: '!room:test',
|
||||
eventId: '$notif',
|
||||
callNotificationType: 'ring',
|
||||
callIntentKind: 'video',
|
||||
callRefEventId: '$ref',
|
||||
callSenderId: '@alice:test',
|
||||
callSenderTs: now - 1_000,
|
||||
callExpiresAt: now + 10_000,
|
||||
},
|
||||
true,
|
||||
now
|
||||
);
|
||||
|
||||
expect(incoming).toMatchObject({
|
||||
roomId: '!room:test',
|
||||
notificationEventId: '$notif',
|
||||
refEventId: '$ref',
|
||||
senderId: '@alice:test',
|
||||
notificationType: 'ring',
|
||||
intentKind: 'video',
|
||||
isDirect: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops expired call notifications', () => {
|
||||
const now = 1_000_000;
|
||||
const incoming = resolveIncomingCallFromNotificationData(
|
||||
{
|
||||
isCall: true,
|
||||
roomId: '!room:test',
|
||||
eventId: '$notif',
|
||||
callNotificationType: 'ring',
|
||||
callExpiresAt: now - 1,
|
||||
},
|
||||
false,
|
||||
now
|
||||
);
|
||||
|
||||
expect(incoming).toBeUndefined();
|
||||
});
|
||||
|
||||
it('hydrates incoming call from /to/ deep-link search params', () => {
|
||||
const now = 1_000_000;
|
||||
const params = new URLSearchParams({
|
||||
call: '1',
|
||||
callType: 'notification',
|
||||
callIntentKind: 'audio',
|
||||
callRefEventId: '$ref',
|
||||
callSenderId: '@bob:test',
|
||||
callSenderTs: String(now - 500),
|
||||
callExpiresAt: String(now + 5_000),
|
||||
});
|
||||
|
||||
const incoming = resolveIncomingCallFromSearchParams(
|
||||
params,
|
||||
'!room:test',
|
||||
'$notif',
|
||||
false,
|
||||
now
|
||||
);
|
||||
|
||||
expect(incoming).toMatchObject({
|
||||
roomId: '!room:test',
|
||||
notificationEventId: '$notif',
|
||||
refEventId: '$ref',
|
||||
senderId: '@bob:test',
|
||||
notificationType: 'notification',
|
||||
intentKind: 'audio',
|
||||
isDirect: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { IncomingCall, IncomingCallIntentKind, IncomingCallNotificationType } from '$state/callEmbed';
|
||||
|
||||
const MAX_CALL_NOTIFICATION_LIFETIME_MS = 120_000;
|
||||
|
||||
type CallCandidate = {
|
||||
roomId: string;
|
||||
notificationEventId: string;
|
||||
notificationTypeRaw?: string;
|
||||
intentKindRaw?: string;
|
||||
intentRaw?: string;
|
||||
refEventIdRaw?: string;
|
||||
senderIdRaw?: string;
|
||||
senderTsRaw?: number;
|
||||
expiresAtRaw?: number;
|
||||
isDirect: boolean;
|
||||
};
|
||||
|
||||
const toNotificationType = (
|
||||
value: string | undefined
|
||||
): IncomingCallNotificationType | undefined => {
|
||||
if (value === 'ring' || value === 'notification') return value;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const normalizeIntentKind = (
|
||||
intentKindRaw: string | undefined,
|
||||
intentRaw: string | undefined
|
||||
): IncomingCallIntentKind => {
|
||||
if (intentKindRaw === 'audio' || intentKindRaw === 'video') {
|
||||
return intentKindRaw;
|
||||
}
|
||||
const normalized = intentRaw?.toLowerCase();
|
||||
if (normalized?.includes('video')) return 'video';
|
||||
return 'audio';
|
||||
};
|
||||
|
||||
const fromCandidate = (candidate: CallCandidate, now = Date.now()): IncomingCall | undefined => {
|
||||
const notificationType = toNotificationType(candidate.notificationTypeRaw) ?? 'ring';
|
||||
const senderTs =
|
||||
typeof candidate.senderTsRaw === 'number' && Number.isFinite(candidate.senderTsRaw)
|
||||
? candidate.senderTsRaw
|
||||
: now;
|
||||
const expiresAt =
|
||||
typeof candidate.expiresAtRaw === 'number' && Number.isFinite(candidate.expiresAtRaw)
|
||||
? candidate.expiresAtRaw
|
||||
: senderTs + MAX_CALL_NOTIFICATION_LIFETIME_MS;
|
||||
|
||||
if (now >= expiresAt) return undefined;
|
||||
|
||||
return {
|
||||
roomId: candidate.roomId,
|
||||
notificationEventId: candidate.notificationEventId,
|
||||
refEventId: candidate.refEventIdRaw || candidate.notificationEventId,
|
||||
senderId: candidate.senderIdRaw || 'unknown',
|
||||
senderTs,
|
||||
expiresAt,
|
||||
notificationType,
|
||||
intentKind: normalizeIntentKind(candidate.intentKindRaw, candidate.intentRaw),
|
||||
intentRaw: candidate.intentRaw,
|
||||
isDirect: candidate.isDirect,
|
||||
};
|
||||
};
|
||||
|
||||
export const resolveIncomingCallFromNotificationData = (
|
||||
data: Record<string, unknown>,
|
||||
isDirect: boolean,
|
||||
now = Date.now()
|
||||
): IncomingCall | undefined => {
|
||||
const roomId = typeof data.roomId === 'string' ? data.roomId : undefined;
|
||||
const eventId = typeof data.eventId === 'string' ? data.eventId : undefined;
|
||||
const callType = typeof data.callNotificationType === 'string' ? data.callNotificationType : undefined;
|
||||
|
||||
if (!roomId || !eventId) return undefined;
|
||||
if (data.isCall !== true && !callType) return undefined;
|
||||
|
||||
return fromCandidate(
|
||||
{
|
||||
roomId,
|
||||
notificationEventId: eventId,
|
||||
notificationTypeRaw: callType,
|
||||
intentKindRaw: typeof data.callIntentKind === 'string' ? data.callIntentKind : undefined,
|
||||
intentRaw: typeof data.callIntentRaw === 'string' ? data.callIntentRaw : undefined,
|
||||
refEventIdRaw: typeof data.callRefEventId === 'string' ? data.callRefEventId : undefined,
|
||||
senderIdRaw: typeof data.callSenderId === 'string' ? data.callSenderId : undefined,
|
||||
senderTsRaw: typeof data.callSenderTs === 'number' ? data.callSenderTs : undefined,
|
||||
expiresAtRaw: typeof data.callExpiresAt === 'number' ? data.callExpiresAt : undefined,
|
||||
isDirect,
|
||||
},
|
||||
now
|
||||
);
|
||||
};
|
||||
|
||||
export const resolveIncomingCallFromSearchParams = (
|
||||
searchParams: URLSearchParams,
|
||||
roomId: string,
|
||||
notificationEventId: string | undefined,
|
||||
isDirect: boolean,
|
||||
now = Date.now()
|
||||
): IncomingCall | undefined => {
|
||||
if (searchParams.get('call') !== '1') return undefined;
|
||||
if (!notificationEventId) return undefined;
|
||||
|
||||
const senderTsRaw = Number(searchParams.get('callSenderTs'));
|
||||
const expiresAtRaw = Number(searchParams.get('callExpiresAt'));
|
||||
|
||||
return fromCandidate(
|
||||
{
|
||||
roomId,
|
||||
notificationEventId,
|
||||
notificationTypeRaw: searchParams.get('callType') ?? undefined,
|
||||
intentKindRaw: searchParams.get('callIntentKind') ?? undefined,
|
||||
intentRaw: searchParams.get('callIntentRaw') ?? undefined,
|
||||
refEventIdRaw: searchParams.get('callRefEventId') ?? undefined,
|
||||
senderIdRaw: searchParams.get('callSenderId') ?? undefined,
|
||||
senderTsRaw: Number.isFinite(senderTsRaw) ? senderTsRaw : undefined,
|
||||
expiresAtRaw: Number.isFinite(expiresAtRaw) ? expiresAtRaw : undefined,
|
||||
isDirect,
|
||||
},
|
||||
now
|
||||
);
|
||||
};
|
||||
|
||||
export const dismissSystemCallNotifications = async (roomId?: string): Promise<void> => {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const notifications = roomId
|
||||
? await registration.getNotifications({ tag: `call-${roomId}` })
|
||||
: await registration.getNotifications();
|
||||
notifications.forEach((notification) => {
|
||||
if (!roomId || notification?.data?.room_id === roomId || notification?.data?.roomId === roomId) {
|
||||
notification.close();
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
// Best-effort cleanup; ignore unsupported browsers and transient SW errors.
|
||||
}
|
||||
};
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
resolveIncomingCallToneUrl,
|
||||
resolveOutgoingRingbackToneUrl,
|
||||
} from '$features/call/callRingtone';
|
||||
import { dismissSystemCallNotifications } from '$features/call/callNotificationBridge';
|
||||
import { getCustomCallRingtone } from '$features/call/callRingtoneStorage';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
import { createDebugLogger } from '../utils/debugLogger';
|
||||
@@ -223,8 +224,12 @@ export function useIncomingCallSignaling() {
|
||||
}, []);
|
||||
|
||||
const clearIncomingCall = useCallback(() => {
|
||||
const activeIncomingCall = incomingCallRef.current;
|
||||
stopIncomingRing();
|
||||
setIncomingCall(null);
|
||||
if (activeIncomingCall) {
|
||||
void dismissSystemCallNotifications(activeIncomingCall.roomId);
|
||||
}
|
||||
}, [setIncomingCall, stopIncomingRing]);
|
||||
|
||||
const callAudioAllowed = canPlayCallAudio({
|
||||
@@ -273,6 +278,13 @@ export function useIncomingCallSignaling() {
|
||||
});
|
||||
|
||||
if (nextIncomingCall.notificationType === 'ring') {
|
||||
const appVisible = document.visibilityState === 'visible';
|
||||
if (!appVisible) {
|
||||
stopIncomingRing();
|
||||
setCallSoundBlocked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!incomingRingtoneAllowed) {
|
||||
stopIncomingRing();
|
||||
return;
|
||||
|
||||
@@ -45,6 +45,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
|
||||
import { registrationAtom } from '$state/serviceWorkerRegistration';
|
||||
import { pendingNotificationAtom, inAppBannerAtom, activeSessionIdAtom } from '$state/sessions';
|
||||
import { incomingCallAtom } from '$state/callEmbed';
|
||||
import {
|
||||
buildRoomMessageNotification,
|
||||
resolveNotificationPreviewText,
|
||||
@@ -60,6 +61,7 @@ import { useIncomingCallSignaling } from '$hooks/useCallSignaling';
|
||||
import { getBlobCacheStats } from '$hooks/useBlobCache';
|
||||
import { lastVisitedRoomIdAtom } from '$state/room/lastRoom';
|
||||
import { useSettingsSyncEffect } from '$hooks/useSettingsSync';
|
||||
import { resolveIncomingCallFromNotificationData } from '$features/call/callNotificationBridge';
|
||||
import { getInboxInvitesPath } from '../pathUtils';
|
||||
import { BackgroundNotifications } from './BackgroundNotifications';
|
||||
|
||||
@@ -609,6 +611,8 @@ type ClientNonUIFeaturesProps = {
|
||||
export function HandleNotificationClick() {
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
const setIncomingCall = useSetAtom(incomingCallAtom);
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -634,11 +638,19 @@ export function HandleNotificationClick() {
|
||||
|
||||
if (!roomId) return;
|
||||
setPending({ roomId, eventId, targetSessionId: userId });
|
||||
|
||||
const incomingCall = resolveIncomingCallFromNotificationData(
|
||||
data as Record<string, unknown>,
|
||||
mDirects.has(roomId)
|
||||
);
|
||||
if (incomingCall) {
|
||||
setIncomingCall(incomingCall);
|
||||
}
|
||||
};
|
||||
|
||||
navigator.serviceWorker.addEventListener('message', handleMessage);
|
||||
return () => navigator.serviceWorker.removeEventListener('message', handleMessage);
|
||||
}, [setPending, setActiveSessionId, navigate]);
|
||||
}, [mDirects, navigate, setActiveSessionId, setIncomingCall, setPending]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions';
|
||||
import { mDirectAtom } from '$state/mDirectList';
|
||||
import { incomingCallAtom } from '$state/callEmbed';
|
||||
import { resolveIncomingCallFromSearchParams } from '$features/call/callNotificationBridge';
|
||||
|
||||
// ToRoomEvent handles /to/:user_id/:room_id/:event_id? — the canonical deep-link
|
||||
// URL used by the service worker's notificationclick handler.
|
||||
@@ -17,8 +20,11 @@ import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions';
|
||||
// setActiveSessionId() triggers an account switch.
|
||||
export function ToRoomEvent() {
|
||||
const { user_id: userId, room_id: roomId, event_id: eventId } = useParams();
|
||||
const [searchParams] = useSearchParams();
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
const setIncomingCall = useSetAtom(incomingCallAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (!roomId) return;
|
||||
@@ -26,9 +32,20 @@ export function ToRoomEvent() {
|
||||
// under the correct session.
|
||||
if (userId) setActiveSessionId(userId);
|
||||
setPending({ roomId, eventId, targetSessionId: userId });
|
||||
|
||||
const incomingCall = resolveIncomingCallFromSearchParams(
|
||||
searchParams,
|
||||
roomId,
|
||||
eventId,
|
||||
mDirects.has(roomId)
|
||||
);
|
||||
if (incomingCall) {
|
||||
setIncomingCall(incomingCall);
|
||||
}
|
||||
|
||||
// Replace /to/… in history so the back button doesn't return to this route.
|
||||
window.history.replaceState({}, '', '/');
|
||||
}, [userId, roomId, eventId, setActiveSessionId, setPending]);
|
||||
}, [eventId, mDirects, roomId, searchParams, setActiveSessionId, setIncomingCall, setPending, userId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -481,6 +481,7 @@ async function handleMinimalPushPayload(
|
||||
room_id: roomId,
|
||||
event_id: eventId,
|
||||
user_id: session.userId,
|
||||
sender_id: sender,
|
||||
};
|
||||
|
||||
if (eventType === 'm.room.encrypted') {
|
||||
@@ -837,6 +838,15 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
|
||||
const pushRoomId: string | undefined = data?.room_id ?? undefined;
|
||||
const pushEventId: string | undefined = data?.event_id ?? undefined;
|
||||
const isInvite = data?.content?.membership === 'invite';
|
||||
const callNotificationType: string | undefined = data?.callNotificationType ?? undefined;
|
||||
const callIntentKind: string | undefined = data?.callIntentKind ?? undefined;
|
||||
const callIntentRaw: string | undefined = data?.callIntentRaw ?? undefined;
|
||||
const callRefEventId: string | undefined = data?.callRefEventId ?? undefined;
|
||||
const callSenderId: string | undefined = data?.sender_id ?? data?.callSenderId ?? undefined;
|
||||
const callSenderTs: number | undefined =
|
||||
typeof data?.callSenderTs === 'number' ? data.callSenderTs : undefined;
|
||||
const callExpiresAt: number | undefined =
|
||||
typeof data?.callExpiresAt === 'number' ? data.callExpiresAt : undefined;
|
||||
|
||||
console.debug('[SW notificationclick] notification data:', JSON.stringify(data, null, 2));
|
||||
console.debug('[SW notificationclick] resolved fields:', {
|
||||
@@ -864,11 +874,25 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
|
||||
if (pushUserId) u.searchParams.set('uid', pushUserId);
|
||||
targetUrl = u.href;
|
||||
} else if (pushUserId && pushRoomId) {
|
||||
const callParam = isCall ? '?joinCall=true' : '';
|
||||
const segments = pushEventId
|
||||
? `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}/${encodeURIComponent(pushEventId)}/${callParam}`
|
||||
: `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}/${callParam}`;
|
||||
targetUrl = new URL(segments, scope).href;
|
||||
? `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}/${encodeURIComponent(pushEventId)}`
|
||||
: `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}`;
|
||||
const target = new URL(segments, scope);
|
||||
if (isCall) {
|
||||
target.searchParams.set('call', '1');
|
||||
if (callNotificationType) target.searchParams.set('callType', callNotificationType);
|
||||
if (callIntentKind) target.searchParams.set('callIntentKind', callIntentKind);
|
||||
if (callIntentRaw) target.searchParams.set('callIntentRaw', callIntentRaw);
|
||||
if (callRefEventId) target.searchParams.set('callRefEventId', callRefEventId);
|
||||
if (callSenderId) target.searchParams.set('callSenderId', callSenderId);
|
||||
if (typeof callSenderTs === 'number') {
|
||||
target.searchParams.set('callSenderTs', String(callSenderTs));
|
||||
}
|
||||
if (typeof callExpiresAt === 'number') {
|
||||
target.searchParams.set('callExpiresAt', String(callExpiresAt));
|
||||
}
|
||||
}
|
||||
targetUrl = target.href;
|
||||
} else {
|
||||
// Fallback: no room ID or no user ID in payload.
|
||||
targetUrl = new URL('inbox/notifications/', scope).href;
|
||||
@@ -906,6 +930,13 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
|
||||
eventId: pushEventId,
|
||||
isInvite,
|
||||
isCall,
|
||||
callNotificationType,
|
||||
callIntentKind,
|
||||
callIntentRaw,
|
||||
callRefEventId,
|
||||
callSenderId,
|
||||
callSenderTs,
|
||||
callExpiresAt,
|
||||
});
|
||||
// oxlint-disable-next-line no-await-in-loop
|
||||
await wc.focus();
|
||||
|
||||
+158
-10
@@ -15,8 +15,16 @@ type NotificationSettings = {
|
||||
|
||||
interface MatrixPushData {
|
||||
type?: string;
|
||||
content?: { notification_type?: string; membership?: string };
|
||||
content?: {
|
||||
notification_type?: string;
|
||||
membership?: string;
|
||||
sender_ts?: number;
|
||||
lifetime?: number;
|
||||
'm.call.intent'?: string;
|
||||
'm.relates_to'?: { event_id?: string };
|
||||
};
|
||||
sender_display_name?: string;
|
||||
sender_id?: string;
|
||||
room_name?: string;
|
||||
room_id?: string;
|
||||
room_avatar_url?: string;
|
||||
@@ -27,6 +35,113 @@ interface MatrixPushData {
|
||||
}
|
||||
|
||||
const resolveSilent = (): boolean => false;
|
||||
const MAX_CALL_NOTIFICATION_LIFETIME_MS = 120_000;
|
||||
|
||||
const normalizeCallIntentKind = (intentRaw: string | undefined): 'audio' | 'video' => {
|
||||
if (!intentRaw) return 'audio';
|
||||
const normalized = intentRaw.toLowerCase();
|
||||
if (normalized.includes('video')) return 'video';
|
||||
return 'audio';
|
||||
};
|
||||
|
||||
const isCallNotificationType = (value: unknown): value is 'ring' | 'notification' =>
|
||||
value === 'ring' || value === 'notification';
|
||||
|
||||
const getCallTiming = (
|
||||
content: MatrixPushData['content'],
|
||||
originTs: number
|
||||
): { senderTs: number; expiresAt: number } => {
|
||||
const senderTsCandidate = content?.sender_ts;
|
||||
const lifetimeCandidate = content?.lifetime;
|
||||
|
||||
if (typeof senderTsCandidate !== 'number' || !Number.isFinite(senderTsCandidate)) {
|
||||
const senderTs = originTs;
|
||||
return {
|
||||
senderTs,
|
||||
expiresAt: senderTs + MAX_CALL_NOTIFICATION_LIFETIME_MS,
|
||||
};
|
||||
}
|
||||
|
||||
const senderTs = senderTsCandidate - originTs > 20_000 ? originTs : senderTsCandidate;
|
||||
const lifetime =
|
||||
typeof lifetimeCandidate === 'number' && Number.isFinite(lifetimeCandidate)
|
||||
? Math.min(Math.max(lifetimeCandidate, 0), MAX_CALL_NOTIFICATION_LIFETIME_MS)
|
||||
: MAX_CALL_NOTIFICATION_LIFETIME_MS;
|
||||
|
||||
return {
|
||||
senderTs,
|
||||
expiresAt: senderTs + lifetime,
|
||||
};
|
||||
};
|
||||
|
||||
const resolveCallNotificationCopy = (
|
||||
notificationType: 'ring' | 'notification',
|
||||
intentKind: 'audio' | 'video',
|
||||
senderDisplayName: string | undefined,
|
||||
roomName: string | undefined,
|
||||
showPreviewDetails: boolean
|
||||
): { title: string; body: string | undefined } => {
|
||||
if (notificationType === 'notification') {
|
||||
if (!showPreviewDetails) {
|
||||
return {
|
||||
title: 'Room call started',
|
||||
body: 'Open Sable to join.',
|
||||
};
|
||||
}
|
||||
if (roomName && senderDisplayName) {
|
||||
return {
|
||||
title: 'Room call started',
|
||||
body: `${senderDisplayName} started a call in ${roomName}`,
|
||||
};
|
||||
}
|
||||
if (roomName) {
|
||||
return {
|
||||
title: 'Room call started',
|
||||
body: `A call started in ${roomName}`,
|
||||
};
|
||||
}
|
||||
if (senderDisplayName) {
|
||||
return {
|
||||
title: 'Room call started',
|
||||
body: `${senderDisplayName} started a call`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: 'Room call started',
|
||||
body: 'A room call started.',
|
||||
};
|
||||
}
|
||||
|
||||
const title = intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call';
|
||||
if (!showPreviewDetails) {
|
||||
return {
|
||||
title,
|
||||
body: 'Open Sable to answer.',
|
||||
};
|
||||
}
|
||||
if (senderDisplayName && roomName) {
|
||||
return {
|
||||
title,
|
||||
body: `${senderDisplayName} is calling you in ${roomName}`,
|
||||
};
|
||||
}
|
||||
if (senderDisplayName) {
|
||||
return {
|
||||
title,
|
||||
body: `${senderDisplayName} is calling you`,
|
||||
};
|
||||
}
|
||||
if (roomName) {
|
||||
return {
|
||||
title,
|
||||
body: `Incoming call in ${roomName}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title,
|
||||
body: 'Incoming call',
|
||||
};
|
||||
};
|
||||
|
||||
export const createPushNotifications = (
|
||||
self: ServiceWorkerGlobalScope,
|
||||
@@ -38,13 +153,15 @@ export const createPushNotifications = (
|
||||
data: Record<string, unknown>,
|
||||
silent?: boolean,
|
||||
icon?: string,
|
||||
badge?: string
|
||||
badge?: string,
|
||||
tagOverride?: string
|
||||
) => {
|
||||
const roomId: string | undefined = data?.room_id as string | undefined;
|
||||
// Group by room so new messages in the same room replace the previous
|
||||
// notification rather than stacking individually. renotify: true ensures
|
||||
// the user is still alerted when the existing tag is replaced.
|
||||
const tag: string = roomId ? `room-${roomId}` : ((data?.event_id as string) ?? 'Cinny');
|
||||
const tag: string =
|
||||
tagOverride ?? (roomId ? `room-${roomId}` : ((data?.event_id as string) ?? 'Cinny'));
|
||||
const renotify = !!roomId;
|
||||
// `renotify` is a valid Web API property absent from TypeScript's NotificationOptions type.
|
||||
// Build the options object separately to avoid the excess-property check, then cast.
|
||||
@@ -62,26 +179,57 @@ export const createPushNotifications = (
|
||||
};
|
||||
|
||||
const handleCallNotification = async (pushData: MatrixPushData) => {
|
||||
const content = pushData?.content as { notification_type?: string } | undefined;
|
||||
if (content?.notification_type !== 'ring') return;
|
||||
if (pushData.type === EventType.RoomMessageEncrypted) return;
|
||||
|
||||
const notificationTypeRaw = pushData?.content?.notification_type;
|
||||
if (!isCallNotificationType(notificationTypeRaw)) return;
|
||||
|
||||
const intentRaw =
|
||||
typeof pushData?.content?.['m.call.intent'] === 'string'
|
||||
? pushData.content['m.call.intent']
|
||||
: undefined;
|
||||
const intentKind = normalizeCallIntentKind(intentRaw);
|
||||
const senderDisplayName = pushData?.sender_display_name;
|
||||
const roomName = pushData?.room_name;
|
||||
const title = 'Incoming Call';
|
||||
const body = senderDisplayName
|
||||
? `${senderDisplayName} is calling you ${roomName ? `in ${roomName}` : ''}`
|
||||
: 'Incoming voice chat';
|
||||
const showPreviewDetails = getNotificationSettings().showMessageContent;
|
||||
const copy = resolveCallNotificationCopy(
|
||||
notificationTypeRaw,
|
||||
intentKind,
|
||||
senderDisplayName,
|
||||
roomName,
|
||||
showPreviewDetails
|
||||
);
|
||||
const originTs = typeof pushData.timestamp === 'number' ? pushData.timestamp : Date.now();
|
||||
const { senderTs, expiresAt } = getCallTiming(pushData.content, originTs);
|
||||
|
||||
const data = {
|
||||
type: pushData?.type,
|
||||
room_id: pushData?.room_id,
|
||||
event_id: pushData?.event_id,
|
||||
user_id: pushData?.user_id,
|
||||
sender_id: pushData?.sender_id,
|
||||
timestamp: Date.now(),
|
||||
isCall: true,
|
||||
callNotificationType: notificationTypeRaw,
|
||||
callIntentKind: intentKind,
|
||||
callIntentRaw: intentRaw,
|
||||
callNotificationEventId: pushData?.event_id,
|
||||
callRefEventId: pushData?.content?.['m.relates_to']?.event_id,
|
||||
callSenderTs: senderTs,
|
||||
callExpiresAt: expiresAt,
|
||||
...pushData.data,
|
||||
};
|
||||
|
||||
await showNotificationWithData(title, body, data, resolveSilent(), pushData?.room_avatar_url);
|
||||
const callTag = pushData?.room_id ? `call-${pushData.room_id}` : undefined;
|
||||
await showNotificationWithData(
|
||||
copy.title,
|
||||
copy.body,
|
||||
data,
|
||||
resolveSilent(),
|
||||
pushData?.room_avatar_url,
|
||||
undefined,
|
||||
callTag
|
||||
);
|
||||
};
|
||||
|
||||
const handleRoomMessageNotification = async (pushData: MatrixPushData) => {
|
||||
|
||||
Reference in new issue
Block a user