extract a bunch of things into their own files and some tests

This commit is contained in:
7w1 committed 2026-05-18 20:42:35 -05:00
1 parent 8cb0464760
commit e25ce4e5dd
33 files changed
+1215 -712

No files matched your search

+11 -40
View File
@@ -38,6 +38,7 @@ import {
} from '$state/callEmbed';
import { createDebugLogger } from '$utils/debugLogger';
import { dismissSystemCallNotifications } from '$features/call/callNotificationBridge';
import { getIncomingCallBlockers } from '$features/call/getIncomingCallBlockers';
import { RoomAvatar } from './room-avatar';
import { UserAvatar } from './user-avatar';
@@ -49,12 +50,6 @@ type IncomingCallInternalProps = {
onClose: () => void;
};
type CapabilityIssue = {
id: string;
message: string;
shortReason: string;
};
export function IncomingCallInternal({ room, incomingCall, onClose }: IncomingCallInternalProps) {
const mx = useMatrixClient();
const screenSize = useScreenSizeContext();
@@ -86,40 +81,16 @@ export function IncomingCallInternal({ room, incomingCall, onClose }: IncomingCa
const hasCallMemberPermission =
room.currentState?.maySendStateEvent('org.matrix.msc3401.call.member', myUserId) ?? false;
const capabilityIssues = useMemo<CapabilityIssue[]>(() => {
const issues: CapabilityIssue[] = [];
if (!canUseWebRTC) {
issues.push({
id: 'webrtc',
message: 'Your browser does not support WebRTC calling.',
shortReason: 'WebRTC is unavailable in this browser.',
});
}
if (!livekitSupported) {
issues.push({
id: 'livekit',
message: 'Your homeserver does not expose a LiveKit call focus.',
shortReason: 'Homeserver call focus is unavailable.',
});
}
if (!hasCallMemberPermission) {
issues.push({
id: 'permission',
message: "You don't have permission to join this room's call.",
shortReason: 'Missing permission to join this call.',
});
}
if (inAnotherCall) {
issues.push({
id: 'another_call',
message: 'You are already in another call.',
shortReason: 'Finish your current call first.',
});
}
return issues;
}, [canUseWebRTC, livekitSupported, hasCallMemberPermission, inAnotherCall]);
const capabilityIssues = useMemo(
() =>
getIncomingCallBlockers({
canUseWebRTC,
livekitSupported,
hasCallMemberPermission,
inAnotherCall,
}),
[canUseWebRTC, livekitSupported, hasCallMemberPermission, inAnotherCall]
);
const canAnswer = capabilityIssues.length === 0;
const primaryBlockedReason = capabilityIssues[0]?.shortReason;
+1 -1
View File
@@ -17,7 +17,7 @@ import { callEmbedAtom, callEmbedStartErrorAtom } from '$state/callEmbed';
function LivekitServerMissingMessage() {
return (
<Text style={{ margin: 'auto', color: color.Critical.Main }} size="L400" align="Center">
Your homeserver does not support calling.
Your homeserver does not support calling. You can still join calls started by others.
</Text>
);
}
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MatrixRTCSession } from '$types/matrix-sdk';
import {
getCallMembershipPresence,
isCallActive,
isIncomingCallActive,
isOutgoingCallPending,
type SessionDescription,
} from './callMembershipState';
const MY_USER_ID = '@self:example.org';
const SESSION_DESCRIPTION = {} as SessionDescription;
const room = { roomId: '!room:example.org' } as Parameters<
typeof MatrixRTCSession.sessionMembershipsForRoom
>[0];
describe('callMembershipState', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('detects incoming call when remote members exist without self', () => {
vi.spyOn(MatrixRTCSession, 'sessionMembershipsForRoom').mockReturnValue([
{ userId: '@remote:example.org' },
] as never);
expect(isIncomingCallActive(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(true);
expect(isCallActive(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(false);
expect(isOutgoingCallPending(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(false);
});
it('detects active call when self and remote members exist', () => {
vi.spyOn(MatrixRTCSession, 'sessionMembershipsForRoom').mockReturnValue([
{ userId: MY_USER_ID },
{ userId: '@remote:example.org' },
] as never);
expect(isIncomingCallActive(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(false);
expect(isCallActive(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(true);
expect(isOutgoingCallPending(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(false);
});
it('detects pending outgoing call when only self is present', () => {
vi.spyOn(MatrixRTCSession, 'sessionMembershipsForRoom').mockReturnValue([
{ userId: MY_USER_ID },
] as never);
expect(getCallMembershipPresence(MY_USER_ID, room, SESSION_DESCRIPTION)).toEqual({
hasSelfMember: true,
remoteMemberCount: 0,
});
expect(isOutgoingCallPending(MY_USER_ID, room, SESSION_DESCRIPTION)).toBe(true);
});
});
@@ -0,0 +1,72 @@
import { MatrixRTCSession } from '$types/matrix-sdk';
import type { Room } from '$types/matrix-sdk';
export type SessionDescription = Parameters<typeof MatrixRTCSession.sessionMembershipsForRoom>[1];
type RtcMembership = { userId?: string; sender?: string };
export type CallMembershipPresence = {
hasSelfMember: boolean;
remoteMemberCount: number;
};
const getRoomMemberships = (room: Room, sessionDescription: SessionDescription) =>
MatrixRTCSession.sessionMembershipsForRoom(room, sessionDescription) as RtcMembership[];
export const getCallMembershipPresence = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): CallMembershipPresence => {
const memberships = getRoomMemberships(room, sessionDescription);
const remoteMemberCount = memberships.filter(
(membership) => (membership.userId || membership.sender) !== mxUserId
).length;
const hasSelfMember = memberships.some(
(membership) => (membership.userId || membership.sender) === mxUserId
);
return { hasSelfMember, remoteMemberCount };
};
export const isIncomingCallActive = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return remoteMemberCount > 0 && !hasSelfMember;
};
export const isCallActive = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return hasSelfMember && remoteMemberCount > 0;
};
export const isOutgoingCallPending = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return hasSelfMember && remoteMemberCount === 0;
};
@@ -51,6 +51,28 @@ describe('callNotificationBridge', () => {
expect(incoming).toBeUndefined();
});
it('hydrates incoming call from legacy joinCall deep-link params', () => {
const now = 1_000_000;
const params = new URLSearchParams({
joinCall: 'true',
callType: 'ring',
});
const incoming = resolveIncomingCallFromSearchParams(
params,
'!room:test',
'$notif',
true,
now
);
expect(incoming).toMatchObject({
roomId: '!room:test',
notificationEventId: '$notif',
notificationType: 'ring',
});
});
it('hydrates incoming call from /to/ deep-link search params', () => {
const now = 1_000_000;
const params = new URLSearchParams({
@@ -82,11 +82,17 @@ export const resolveIncomingCallFromSearchParams = (
isDirect: boolean,
now = Date.now()
): IncomingCall | undefined => {
if (searchParams.get('call') !== '1') return undefined;
const isCallDeepLink =
searchParams.get('call') === '1' ||
searchParams.get('joinCall') === 'true' ||
searchParams.get('joinCall') === '1';
if (!isCallDeepLink) return undefined;
if (!notificationEventId) return undefined;
const senderTsRaw = Number(searchParams.get('callSenderTs'));
const expiresAtRaw = Number(searchParams.get('callExpiresAt'));
const senderTsParam = searchParams.get('callSenderTs');
const expiresAtParam = searchParams.get('callExpiresAt');
const senderTsRaw = senderTsParam ? Number(senderTsParam) : Number.NaN;
const expiresAtRaw = expiresAtParam ? Number(expiresAtParam) : Number.NaN;
return fromCandidate(
{
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
CALL_RINGBACK_OPTIONS,
callRingtoneVolumeToGain,
canPlayCallAudio,
clampCallRingtoneVolume,
@@ -115,4 +116,9 @@ describe('callRingtone', () => {
})
).toEqual({ valid: true });
});
it('excludes silent option from ringback choices', () => {
expect(CALL_RINGBACK_OPTIONS.some((option) => option.value === 'silent')).toBe(false);
expect(CALL_RINGBACK_OPTIONS.length).toBeGreaterThan(0);
});
});
+3 -2
View File
@@ -3,7 +3,6 @@ import NotificationSound from '$public/sound/notification.ogg';
import RingtoneSound from '$public/sound/ringtone.webm';
import {
CALL_TONE_IDS,
type CallRingbackTone,
type CallRingtoneId,
type Settings,
} from '$state/settings';
@@ -33,7 +32,9 @@ export const CALL_RINGTONE_OPTIONS: CallToneOption<CallRingtoneId>[] = CALL_TONE
})
);
export const CALL_RINGBACK_OPTIONS: CallToneOption<CallRingbackTone>[] = CALL_RINGTONE_OPTIONS;
export const CALL_RINGBACK_OPTIONS: CallToneOption<CallRingtoneId>[] = CALL_RINGTONE_OPTIONS.filter(
(option) => option.value !== 'silent'
);
type ToneSettings = Pick<Settings, 'isNotificationSounds' | 'callSoundOverrideGlobalNotifications'>;
@@ -0,0 +1,47 @@
import type { CryptoBackend, MatrixClient, MatrixEvent } from '$types/matrix-sdk';
import { createDebugLogger } from '$utils/debugLogger';
import { DECRYPT_TIMEOUT_MS } from './callSignalingPolicy';
const debugLog = createDebugLogger('CallSignaling');
export type DecryptedTimelineEvent = {
type?: string;
content?: unknown;
};
export const decryptRtcTimelineEvent = async (
event: MatrixEvent,
mx: MatrixClient
): Promise<DecryptedTimelineEvent | undefined> => {
const crypto = mx.getCrypto();
if (!crypto) return undefined;
try {
if (!event.isBeingDecrypted()) {
await event.attemptDecryption(crypto as CryptoBackend);
}
const decryptionPromise = event.getDecryptionPromise();
if (decryptionPromise) {
await Promise.race([
decryptionPromise,
new Promise<void>((resolve) => {
window.setTimeout(resolve, DECRYPT_TIMEOUT_MS);
}),
]);
}
} catch (error) {
debugLog.warn('call', 'RTC notification decryption failed', {
eventId: event.getId(),
roomId: event.getRoomId(),
error: error instanceof Error ? error.message : String(error),
});
return undefined;
}
const effectiveEvent = event.getEffectiveEvent();
return {
type: effectiveEvent.type,
content: effectiveEvent.content,
};
};
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import type { IncomingCall } from '$state/callEmbed';
import {
evaluateIncomingCallFallback,
evaluateOutgoingRingbackFallback,
type OutgoingRingbackState,
} from './callSignalingFallback';
import { INCOMING_MEMBERSHIP_GRACE_MS, OUTGOING_RING_TIMEOUT_MS } from './callSignalingPolicy';
const NOW = 1_700_000_000_000;
const incomingCall: IncomingCall = {
roomId: '!room:example.org',
notificationEventId: '$notif',
refEventId: '$ref',
senderId: '@caller:example.org',
senderTs: NOW - 1_000,
expiresAt: NOW + 60_000,
notificationType: 'ring',
intentKind: 'audio',
isDirect: true,
};
describe('evaluateIncomingCallFallback', () => {
it('clears expired incoming calls', () => {
expect(
evaluateIncomingCallFallback(
{ ...incomingCall, expiresAt: NOW - 1 },
NOW,
{ myUserId: '@self:example.org', getRoom: () => null, getSessionDescription: () => ({}) }
)
).toEqual({ kind: 'clear', reason: 'expired' });
});
it('keeps incoming call during membership grace window', () => {
expect(
evaluateIncomingCallFallback(incomingCall, NOW, {
myUserId: '@self:example.org',
getRoom: () => ({ roomId: incomingCall.roomId }) as never,
getSessionDescription: () => ({}),
isIncomingActive: () => false,
})
).toEqual({ kind: 'none' });
});
it('clears incoming call after grace when membership is inactive', () => {
const action = evaluateIncomingCallFallback(
{ ...incomingCall, senderTs: NOW - INCOMING_MEMBERSHIP_GRACE_MS - 1 },
NOW,
{
myUserId: '@self:example.org',
getRoom: () => ({ roomId: incomingCall.roomId }) as never,
getSessionDescription: () => ({}),
isIncomingActive: () => false,
}
);
expect(action).toEqual({ kind: 'clear', reason: 'membership_dropped' });
});
});
describe('evaluateOutgoingRingbackFallback', () => {
const baseContext = {
myUserId: '@self:example.org',
activeCallRoomId: '!room:example.org',
outgoingRingbackAllowed: true,
declinedRoomId: null,
getRoom: () => ({ roomId: '!room:example.org' }) as never,
getSessionDescription: () => ({}),
};
it('stops ringback when outgoing call is no longer pending', () => {
const state: OutgoingRingbackState = {
ringRoomId: '!room:example.org',
ringStartedAt: NOW,
};
const action = evaluateOutgoingRingbackFallback(state, NOW, {
...baseContext,
getRoom: () => undefined,
});
expect(action.kind).toBe('stop');
expect(action.nextState).toEqual({ ringRoomId: null, ringStartedAt: null });
});
it('plays ringback for pending outgoing calls and tracks start time', () => {
const action = evaluateOutgoingRingbackFallback(
{ ringRoomId: null, ringStartedAt: null },
NOW,
{
...baseContext,
isOutgoingPending: () => true,
isCallActive: () => false,
}
);
expect(action).toMatchObject({
kind: 'play',
roomId: '!room:example.org',
started: true,
});
});
it('stops ringback after timeout', () => {
const action = evaluateOutgoingRingbackFallback(
{
ringRoomId: '!room:example.org',
ringStartedAt: NOW - OUTGOING_RING_TIMEOUT_MS,
},
NOW,
{
...baseContext,
isOutgoingPending: () => true,
isCallActive: () => false,
}
);
expect(action.kind).toBe('stop');
});
});
@@ -0,0 +1,123 @@
import type { IncomingCall } from '$state/callEmbed';
import type { Room } from '$types/matrix-sdk';
import {
isCallActive,
isIncomingCallActive,
isOutgoingCallPending,
type SessionDescription,
} from './callMembershipState';
import { INCOMING_MEMBERSHIP_GRACE_MS, OUTGOING_RING_TIMEOUT_MS } from './callSignalingPolicy';
export type IncomingFallbackAction =
| { kind: 'none' }
| { kind: 'clear'; reason: 'expired' | 'missing_room' | 'membership_dropped' };
export type IncomingFallbackContext = {
myUserId: string;
getRoom: (roomId: string) => Room | null | undefined;
getSessionDescription: (room: Room) => SessionDescription;
isIncomingActive?: typeof isIncomingCallActive;
};
export const evaluateIncomingCallFallback = (
incoming: IncomingCall | null,
now: number,
context: IncomingFallbackContext
): IncomingFallbackAction => {
if (!incoming) return { kind: 'none' };
if (now >= incoming.expiresAt) return { kind: 'clear', reason: 'expired' };
const incomingRoom = context.getRoom(incoming.roomId);
if (!incomingRoom) return { kind: 'clear', reason: 'missing_room' };
const sessionDescription = context.getSessionDescription(incomingRoom);
const isIncomingActive = context.isIncomingActive ?? isIncomingCallActive;
if (isIncomingActive(context.myUserId, incomingRoom, sessionDescription)) {
return { kind: 'none' };
}
// Session membership can lag behind live RTC notification delivery.
if (now - incoming.senderTs < INCOMING_MEMBERSHIP_GRACE_MS) {
return { kind: 'none' };
}
return { kind: 'clear', reason: 'membership_dropped' };
};
export type OutgoingRingbackState = {
ringRoomId: string | null;
ringStartedAt: number | null;
};
export type OutgoingRingbackAction =
| { kind: 'stop'; nextState: OutgoingRingbackState }
| { kind: 'play'; roomId: string; nextState: OutgoingRingbackState; started: boolean };
export type OutgoingRingbackContext = {
myUserId: string;
activeCallRoomId: string | undefined;
outgoingRingbackAllowed: boolean;
declinedRoomId: string | null;
getRoom: (roomId: string) => Room | null | undefined;
getSessionDescription: (room: Room) => SessionDescription;
isOutgoingPending?: typeof isOutgoingCallPending;
isCallActive?: typeof isCallActive;
};
const clearedRingbackState = (): OutgoingRingbackState => ({
ringRoomId: null,
ringStartedAt: null,
});
export const evaluateOutgoingRingbackFallback = (
state: OutgoingRingbackState,
now: number,
context: OutgoingRingbackContext
): OutgoingRingbackAction => {
const stop = (): OutgoingRingbackAction => ({
kind: 'stop',
nextState: clearedRingbackState(),
});
if (!context.activeCallRoomId || !context.outgoingRingbackAllowed) {
return stop();
}
if (context.declinedRoomId === context.activeCallRoomId) {
return stop();
}
const outgoingRoom = context.getRoom(context.activeCallRoomId);
if (!outgoingRoom) {
return stop();
}
const sessionDescription = context.getSessionDescription(outgoingRoom);
const isOutgoingPending = context.isOutgoingPending ?? isOutgoingCallPending;
const isActive = context.isCallActive ?? isCallActive;
const pendingOutgoing = isOutgoingPending(
context.myUserId,
outgoingRoom,
sessionDescription
);
const activeCall = isActive(context.myUserId, outgoingRoom, sessionDescription);
if (!pendingOutgoing || activeCall) {
return stop();
}
const started = state.ringRoomId !== context.activeCallRoomId;
const nextState: OutgoingRingbackState = started
? { ringRoomId: context.activeCallRoomId, ringStartedAt: now }
: state;
if (nextState.ringStartedAt && now - nextState.ringStartedAt >= OUTGOING_RING_TIMEOUT_MS) {
return stop();
}
return {
kind: 'play',
roomId: context.activeCallRoomId,
nextState,
started,
};
};
@@ -0,0 +1,9 @@
/** Shared timing policy for call signaling, notifications, and membership fallback. */
export const MAX_NOTIFICATION_LIFETIME_MS = 120_000;
export const DECRYPT_TIMEOUT_MS = 8_000;
export const FALLBACK_INTERVAL_MS = 5_000;
export const OUTGOING_RING_TIMEOUT_MS = 30_000;
/** Grace window before clearing incoming call when membership lags behind RTC notification. */
export const INCOMING_MEMBERSHIP_GRACE_MS = 15_000;
/** Delay before clearing embed after outgoing decline hangup completes. */
export const OUTGOING_DECLINE_EMBED_CLEAR_MS = 2_000;
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest';
import { getIncomingCallBlockers } from './getIncomingCallBlockers';
describe('getIncomingCallBlockers', () => {
it('returns no blockers when all capabilities are available', () => {
expect(
getIncomingCallBlockers({
canUseWebRTC: true,
livekitSupported: true,
hasCallMemberPermission: true,
inAnotherCall: false,
})
).toEqual([]);
});
it('returns blockers in priority order', () => {
const issues = getIncomingCallBlockers({
canUseWebRTC: false,
livekitSupported: false,
hasCallMemberPermission: false,
inAnotherCall: true,
});
expect(issues.map((issue) => issue.id)).toEqual([
'webrtc',
'livekit',
'permission',
'another_call',
]);
});
});
@@ -0,0 +1,52 @@
export type IncomingCallBlocker = {
id: string;
message: string;
shortReason: string;
};
export type IncomingCallBlockerInput = {
canUseWebRTC: boolean;
livekitSupported: boolean;
hasCallMemberPermission: boolean;
inAnotherCall: boolean;
};
export const getIncomingCallBlockers = ({
canUseWebRTC,
livekitSupported,
hasCallMemberPermission,
inAnotherCall,
}: IncomingCallBlockerInput): IncomingCallBlocker[] => {
const issues: IncomingCallBlocker[] = [];
if (!canUseWebRTC) {
issues.push({
id: 'webrtc',
message: 'Your browser does not support WebRTC calling.',
shortReason: 'WebRTC is unavailable in this browser.',
});
}
if (!livekitSupported) {
issues.push({
id: 'livekit',
message: 'Your homeserver does not expose a LiveKit call focus.',
shortReason: 'Homeserver call focus is unavailable.',
});
}
if (!hasCallMemberPermission) {
issues.push({
id: 'permission',
message: "You don't have permission to join this room's call.",
shortReason: 'Missing permission to join this call.',
});
}
if (inAnotherCall) {
issues.push({
id: 'another_call',
message: 'You are already in another call.',
shortReason: 'Finish your current call first.',
});
}
return issues;
};
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest';
import { applyOutgoingDeclineToTracker, type OutgoingDeclineTracker } from './outgoingDeclineHandler';
const decline = {
roomId: '!room:example.org',
declineEventId: '$decline',
notificationEventId: '$notif',
senderId: '@alice:example.org',
};
describe('applyOutgoingDeclineToTracker', () => {
it('ends call immediately for direct rooms', () => {
const tracker: OutgoingDeclineTracker = new Map();
const decision = applyOutgoingDeclineToTracker(tracker, decline, {
remoteJoinedIds: new Set(['@alice:example.org']),
isDirectRoom: true,
});
expect(decision).toEqual({ kind: 'end_call', declinedCount: 1, targetCount: 1 });
});
it('ignores partial declines in group calls until all remotes decline', () => {
const tracker: OutgoingDeclineTracker = new Map();
const remoteJoinedIds = new Set(['@alice:example.org', '@bob:example.org']);
const partial = applyOutgoingDeclineToTracker(tracker, decline, {
remoteJoinedIds,
isDirectRoom: false,
});
expect(partial).toEqual({ kind: 'ignore_partial', declinedCount: 1, targetCount: 2 });
const end = applyOutgoingDeclineToTracker(
tracker,
{ ...decline, senderId: '@bob:example.org' },
{ remoteJoinedIds, isDirectRoom: false }
);
expect(end).toEqual({ kind: 'end_call', declinedCount: 2, targetCount: 2 });
});
});
@@ -0,0 +1,49 @@
export type OutgoingDeclineEvent = {
roomId: string;
declineEventId: string;
notificationEventId: string;
senderId: string;
};
export type OutgoingDeclineTrackerState = {
notificationEventId: string;
declinerIds: Set<string>;
};
export type OutgoingDeclineTracker = Map<string, OutgoingDeclineTrackerState>;
export type OutgoingDeclineDecision =
| { kind: 'ignore_partial'; declinedCount: number; targetCount: number }
| { kind: 'end_call'; declinedCount: number; targetCount: number };
export const applyOutgoingDeclineToTracker = (
tracker: OutgoingDeclineTracker,
decline: OutgoingDeclineEvent,
options: {
remoteJoinedIds: Set<string>;
isDirectRoom: boolean;
}
): OutgoingDeclineDecision => {
const trackedDecline = tracker.get(decline.roomId);
const declineState =
trackedDecline && trackedDecline.notificationEventId === decline.notificationEventId
? trackedDecline
: {
notificationEventId: decline.notificationEventId,
declinerIds: new Set<string>(),
};
declineState.declinerIds.add(decline.senderId);
tracker.set(decline.roomId, declineState);
const targetCount = options.remoteJoinedIds.size;
const declinedCount = declineState.declinerIds.size;
const allRemoteDeclined =
targetCount > 0 && [...options.remoteJoinedIds].every((userId) => declineState.declinerIds.has(userId));
const treatAsOneToOne = options.isDirectRoom || targetCount <= 1;
if (!treatAsOneToOne && targetCount > 0 && !allRemoteDeclined) {
return { kind: 'ignore_partial', declinedCount, targetCount };
}
return { kind: 'end_call', declinedCount, targetCount };
};
@@ -0,0 +1,58 @@
import * as Sentry from '@sentry/react';
import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import { decryptRtcTimelineEvent } from './callSignalingDecrypt';
import { parseRtcDecline, type ParsedRtcDecline } from './rtcNotificationParser';
const relationFromContent = (content: unknown) => {
if (!content || typeof content !== 'object') return undefined;
const maybeRelates = (content as { 'm.relates_to'?: unknown })['m.relates_to'];
if (!maybeRelates || typeof maybeRelates !== 'object') return undefined;
const relation = maybeRelates as { rel_type?: unknown; event_id?: unknown };
return {
rel_type: typeof relation.rel_type === 'string' ? relation.rel_type : undefined,
event_id: typeof relation.event_id === 'string' ? relation.event_id : undefined,
};
};
export const parseRtcDeclineFromTimelineEvent = async (
event: MatrixEvent,
room: Room,
liveEvent: boolean,
myUserId: string,
mx: MatrixClient
): Promise<ParsedRtcDecline | undefined> => {
let eventType = event.getType();
let content = event.getContent();
if (event.isEncrypted()) {
const decrypted = await decryptRtcTimelineEvent(event, mx);
if (!decrypted?.content || !decrypted.type) {
Sentry.metrics.count('sable.call.signal.decrypt_timeout', 1);
return undefined;
}
eventType = decrypted.type;
content = decrypted.content;
}
const relation = event.getRelation() ?? relationFromContent(content);
return parseRtcDecline(
{
type: eventType,
sender: event.getSender() ?? '',
roomId: room.roomId,
eventId: event.getId() ?? '',
originServerTs: event.getTs(),
content,
relation: relation
? {
rel_type: relation.rel_type,
event_id: relation.event_id,
}
: undefined,
isLiveEvent: liveEvent,
isEncrypted: false,
},
{ myUserId }
);
};
@@ -186,7 +186,7 @@ export function PermissionGroups({
return (
<SequenceCard
key={item.name}
key={getPermissionLocationKey(item.location)}
variant="SurfaceVariant"
className={SequenceCardStyle}
direction="Column"
@@ -6,7 +6,7 @@ import { Box, Button, Chip, Text, PopOut, Menu, Scroll, toRem, config, color } f
import { SequenceCard } from '$components/sequence-card';
import { getPowers, usePowerLevelTags } from '$hooks/usePowerLevelTags';
import { SettingTile } from '$components/setting-tile';
import type { IPowerLevels } from '$hooks/usePowerLevels';
import type { IPowerLevels, PermissionLocation } from '$hooks/usePowerLevels';
import { getPermissionPower } from '$hooks/usePowerLevels';
import { useRoom } from '$hooks/useRoom';
import { PowerColorBadge, PowerIcon } from '$components/power';
@@ -19,6 +19,8 @@ import { useRoomCreators } from '$hooks/useRoomCreators';
import { SequenceCardStyle } from '$features/common-settings/styles.css';
import type { PermissionGroup } from './types';
const getPermissionLocationKey = (location: PermissionLocation): string => JSON.stringify(location);
type PeekPermissionsProps = {
powerLevels: IPowerLevels;
power: number;
@@ -67,7 +69,7 @@ function PeekPermissions({ powerLevels, power, permissionGroups, children }: Pee
return (
<Text
key={item.name}
key={getPermissionLocationKey(item.location)}
size="T200"
style={{
color: hasPower ? undefined : color.Critical.Main,
@@ -1,7 +1,7 @@
import { useMemo } from 'react';
import type { PermissionGroup } from '$features/common-settings/permissions';
import { CALL_PERMISSIONS_GROUP } from '$features/common-settings/permissions/callPermissions';
import { CALL_PERMISSIONS_GROUP } from '$features/common-settings/permissions';
import { EventType } from '$types/matrix-sdk';
import { CustomStateEvent } from '$types/matrix/room';
@@ -1,5 +1,6 @@
import { render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useSetting } from '$state/hooks/settings';
import { CallSoundSettings } from './CallSoundSettings';
vi.mock('$state/settings', () => ({
@@ -8,23 +9,7 @@ vi.mock('$state/settings', () => ({
}));
vi.mock('$state/hooks/settings', () => ({
useSetting: (_atom: unknown, key: string) => {
const values: Record<string, unknown> = {
incomingCallSoundEnabled: true,
outgoingRingbackEnabled: true,
callRingtoneId: 'sable-default',
callRingbackTone: 'sable-default',
callRingtoneVolume: 80,
callSoundOverrideGlobalNotifications: false,
callCustomRingtoneName: undefined,
callCustomRingtoneSizeBytes: undefined,
callCustomRingtoneDurationMs: undefined,
callCustomRingbackName: undefined,
callCustomRingbackSizeBytes: undefined,
callCustomRingbackDurationMs: undefined,
};
return [values[key], vi.fn<(value: unknown) => void>()] as const;
},
useSetting: vi.fn(),
}));
vi.mock('$features/call/callRingtoneStorage', () => ({
@@ -36,7 +21,38 @@ vi.mock('$features/call/callRingtoneStorage', () => ({
clearCustomCallRingback: vi.fn<() => Promise<void>>(),
}));
const defaultSettingValues: Record<string, unknown> = {
incomingCallSoundEnabled: true,
outgoingRingbackEnabled: true,
callRingtoneId: 'sable-default',
callRingbackTone: 'sable-default',
callRingtoneVolume: 80,
callSoundOverrideGlobalNotifications: false,
};
describe('CallSoundSettings', () => {
beforeEach(() => {
vi.mocked(useSetting).mockImplementation((_atom: unknown, key: string) => {
return [defaultSettingValues[key], vi.fn<(value: unknown) => void>()] as const;
});
});
it('falls back to default ringtone when custom ringtone is unavailable', async () => {
const setCallRingtoneId = vi.fn<(value: unknown) => void>();
vi.mocked(useSetting).mockImplementation((_atom: unknown, key: string) => {
if (key === 'callRingtoneId') {
return ['custom', setCallRingtoneId] as const;
}
return [defaultSettingValues[key], vi.fn<(value: unknown) => void>()] as const;
});
render(<CallSoundSettings />);
await waitFor(() => {
expect(setCallRingtoneId).toHaveBeenCalledWith('sable-default');
});
});
it('renders expected call sound setting controls', async () => {
render(<CallSoundSettings />);
@@ -1,15 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Button, Icon, Icons, Input, Spinner, Switch, Text, toRem } from 'folds';
import { Box, Icons, Input, Switch, Text, toRem } from 'folds';
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { SettingMenuSelector } from '$components/setting-menu-selector';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom, type CallRingbackTone, type CallRingtoneId } from '$state/settings';
import { settingsAtom, type CallRingtoneId } from '$state/settings';
import {
CALL_RINGBACK_OPTIONS,
CALL_RINGTONE_OPTIONS,
CUSTOM_CALL_RINGTONE_MAX_BYTES,
CUSTOM_CALL_RINGTONE_MAX_DURATION_MS,
callRingtoneVolumeToGain,
clampCallRingtoneVolume,
readAudioDurationMs,
@@ -23,158 +21,21 @@ import {
getCustomCallRingtone,
putCustomCallRingback,
putCustomCallRingtone,
type StoredCallRingtone,
} from '$features/call/callRingtoneStorage';
import { SequenceCardStyle } from '$features/settings/styles.css';
import { bytesToSize, millisecondsToMinutesAndSeconds } from '$utils/common';
import {
CustomToneSettingsCard,
customToneValidationError,
type CustomToneMetadata,
type PreviewTone,
} from './CallSoundSettingsCards';
type PreviewTone = 'incoming' | 'outgoing';
function CustomToneMeta({
fileName,
sizeBytes,
durationMs,
emptyLabel,
}: {
fileName?: string;
sizeBytes?: number;
durationMs?: number;
emptyLabel: string;
}) {
if (!fileName) {
return (
<Text size="T200" priority="300">
{emptyLabel}
</Text>
);
}
return (
<Text size="T200" priority="300">
{[
fileName,
typeof sizeBytes === 'number' ? bytesToSize(sizeBytes) : undefined,
typeof durationMs === 'number' ? millisecondsToMinutesAndSeconds(durationMs) : undefined,
]
.filter(Boolean)
.join(' - ')}
</Text>
);
}
function CustomToneSettingsCard({
title,
focusId,
description,
fileName,
sizeBytes,
durationMs,
emptyLabel,
hasCustomTone,
previewing,
previewActions,
onImport,
onPreview,
onReset,
}: {
title: string;
focusId: string;
description: string;
fileName?: string;
sizeBytes?: number;
durationMs?: number;
emptyLabel: string;
hasCustomTone: boolean;
previewing: boolean;
previewActions: {
label: string;
tone: PreviewTone;
icon: (typeof Icons)[keyof typeof Icons];
}[];
onImport: () => void;
onPreview: (tone: PreviewTone) => void;
onReset: () => void;
}) {
return (
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile title={title} focusId={focusId} description={description}>
<Box direction="Column" gap="200">
<CustomToneMeta
fileName={fileName}
sizeBytes={sizeBytes}
durationMs={durationMs}
emptyLabel={emptyLabel}
/>
<Box gap="200" wrap="Wrap">
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.ArrowTop} size="100" />}
onClick={onImport}
>
<Text size="B300">Import</Text>
</Button>
{previewActions.map(({ label, tone, icon }) => (
<Button
key={label}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={
previewing ? (
<Spinner variant="Secondary" size="100" />
) : (
<Icon src={icon} size="100" />
)
}
onClick={() => onPreview(tone)}
disabled={previewing}
>
<Text size="B300">{label}</Text>
</Button>
))}
<Button
variant="Critical"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.Cross} size="100" />}
onClick={onReset}
disabled={!hasCustomTone}
>
<Text size="B300">Reset</Text>
</Button>
</Box>
<Text size="T200" priority="300">
Max file size: {bytesToSize(CUSTOM_CALL_RINGTONE_MAX_BYTES)}. Max duration:{' '}
{millisecondsToMinutesAndSeconds(CUSTOM_CALL_RINGTONE_MAX_DURATION_MS)}.
</Text>
</Box>
</SettingTile>
</SequenceCard>
);
}
const customToneValidationError = (
reason: 'type' | 'size' | 'duration',
label: 'Ringtone' | 'Ringback'
): string => {
if (reason === 'type') return 'Only audio files are supported.';
if (reason === 'size') {
return `File is too large. Max ${bytesToSize(CUSTOM_CALL_RINGTONE_MAX_BYTES)} allowed.`;
}
return `${label} must be between 1s and ${millisecondsToMinutesAndSeconds(
CUSTOM_CALL_RINGTONE_MAX_DURATION_MS
)}.`;
};
const toCustomToneMetadata = (stored: StoredCallRingtone): CustomToneMetadata => ({
fileName: stored.fileName,
sizeBytes: stored.sizeBytes,
durationMs: stored.durationMs,
});
export function CallSoundSettings() {
const [incomingCallSoundEnabled, setIncomingCallSoundEnabled] = useSetting(
@@ -193,35 +54,13 @@ export function CallSoundSettings() {
);
const [callSoundOverrideGlobalNotifications, setCallSoundOverrideGlobalNotifications] =
useSetting(settingsAtom, 'callSoundOverrideGlobalNotifications');
const [callCustomRingtoneName, setCallCustomRingtoneName] = useSetting(
settingsAtom,
'callCustomRingtoneName'
);
const [callCustomRingtoneSizeBytes, setCallCustomRingtoneSizeBytes] = useSetting(
settingsAtom,
'callCustomRingtoneSizeBytes'
);
const [callCustomRingtoneDurationMs, setCallCustomRingtoneDurationMs] = useSetting(
settingsAtom,
'callCustomRingtoneDurationMs'
);
const [callCustomRingbackName, setCallCustomRingbackName] = useSetting(
settingsAtom,
'callCustomRingbackName'
);
const [callCustomRingbackSizeBytes, setCallCustomRingbackSizeBytes] = useSetting(
settingsAtom,
'callCustomRingbackSizeBytes'
);
const [callCustomRingbackDurationMs, setCallCustomRingbackDurationMs] = useSetting(
settingsAtom,
'callCustomRingbackDurationMs'
);
const [previewing, setPreviewing] = useState(false);
const [loadingCustomState, setLoadingCustomState] = useState(true);
const [hasCustomRingtone, setHasCustomRingtone] = useState(false);
const [hasCustomRingback, setHasCustomRingback] = useState(false);
const [customRingtoneMeta, setCustomRingtoneMeta] = useState<CustomToneMetadata | null>(null);
const [customRingbackMeta, setCustomRingbackMeta] = useState<CustomToneMetadata | null>(null);
const [customError, setCustomError] = useState<string | null>(null);
const previewAudioRef = useRef<HTMLAudioElement | null>(null);
@@ -232,6 +71,8 @@ export function CallSoundSettings() {
if (!mounted) return;
setHasCustomRingtone(Boolean(ringtone));
setHasCustomRingback(Boolean(ringback));
setCustomRingtoneMeta(ringtone ? toCustomToneMetadata(ringtone) : null);
setCustomRingbackMeta(ringback ? toCustomToneMetadata(ringback) : null);
})
.finally(() => {
if (!mounted) return;
@@ -270,12 +111,12 @@ export function CallSoundSettings() {
option.value === 'custom'
? {
...option,
label: callCustomRingtoneName ? 'Custom File (Imported)' : 'Custom File',
label: customRingtoneMeta ? 'Custom File (Imported)' : 'Custom File',
disabled: loadingCustomState,
}
: option
),
[callCustomRingtoneName, loadingCustomState]
[customRingtoneMeta, loadingCustomState]
);
const ringbackOptions = useMemo(
() =>
@@ -283,12 +124,12 @@ export function CallSoundSettings() {
option.value === 'custom'
? {
...option,
label: callCustomRingbackName ? 'Custom File (Imported)' : 'Custom File',
label: customRingbackMeta ? 'Custom File (Imported)' : 'Custom File',
disabled: loadingCustomState,
}
: option
),
[callCustomRingbackName, loadingCustomState]
[customRingbackMeta, loadingCustomState]
);
const resolveToneForPreview = useCallback(
@@ -335,8 +176,8 @@ export function CallSoundSettings() {
const importCustomTone = useCallback(
(
label: 'Ringtone' | 'Ringback',
putTone: (file: File, durationMs: number) => Promise<unknown>,
onImported: (file: File, durationMs: number) => void
putTone: (file: File, durationMs: number) => Promise<StoredCallRingtone>,
onImported: (stored: StoredCallRingtone) => void
) => {
setCustomError(null);
const input = document.createElement('input');
@@ -359,8 +200,8 @@ export function CallSoundSettings() {
return;
}
await putTone(file, durationMs);
onImported(file, durationMs);
const stored = await putTone(file, durationMs);
onImported(stored);
} catch {
setCustomError('Could not import this file. Try a different audio format.');
}
@@ -372,72 +213,40 @@ export function CallSoundSettings() {
);
const handleImportCustomRingtone = useCallback(() => {
importCustomTone('Ringtone', putCustomCallRingtone, (file, durationMs) => {
importCustomTone('Ringtone', putCustomCallRingtone, (stored) => {
setHasCustomRingtone(true);
setCallRingtoneId('custom');
setCallCustomRingtoneName(file.name);
setCallCustomRingtoneSizeBytes(file.size);
setCallCustomRingtoneDurationMs(durationMs);
setCustomRingtoneMeta(toCustomToneMetadata(stored));
});
}, [
importCustomTone,
setCallCustomRingtoneDurationMs,
setCallCustomRingtoneName,
setCallCustomRingtoneSizeBytes,
setCallRingtoneId,
]);
}, [importCustomTone, setCallRingtoneId]);
const handleResetCustomRingtone = useCallback(async () => {
setCustomError(null);
await clearCustomCallRingtone();
setHasCustomRingtone(false);
setCallCustomRingtoneName(undefined);
setCallCustomRingtoneSizeBytes(undefined);
setCallCustomRingtoneDurationMs(undefined);
setCustomRingtoneMeta(null);
if (callRingtoneId === 'custom') {
setCallRingtoneId('sable-default');
}
}, [
callRingtoneId,
setCallCustomRingtoneDurationMs,
setCallCustomRingtoneName,
setCallCustomRingtoneSizeBytes,
setCallRingtoneId,
]);
}, [callRingtoneId, setCallRingtoneId]);
const handleImportCustomRingback = useCallback(() => {
importCustomTone('Ringback', putCustomCallRingback, (file, durationMs) => {
importCustomTone('Ringback', putCustomCallRingback, (stored) => {
setHasCustomRingback(true);
setCallRingbackTone('custom');
setCallCustomRingbackName(file.name);
setCallCustomRingbackSizeBytes(file.size);
setCallCustomRingbackDurationMs(durationMs);
setCustomRingbackMeta(toCustomToneMetadata(stored));
});
}, [
importCustomTone,
setCallCustomRingbackDurationMs,
setCallCustomRingbackName,
setCallCustomRingbackSizeBytes,
setCallRingbackTone,
]);
}, [importCustomTone, setCallRingbackTone]);
const handleResetCustomRingback = useCallback(async () => {
setCustomError(null);
await clearCustomCallRingback();
setHasCustomRingback(false);
setCallCustomRingbackName(undefined);
setCallCustomRingbackSizeBytes(undefined);
setCallCustomRingbackDurationMs(undefined);
setCustomRingbackMeta(null);
if (callRingbackTone === 'custom') {
setCallRingbackTone('sable-default');
}
}, [
callRingbackTone,
setCallCustomRingbackDurationMs,
setCallCustomRingbackName,
setCallCustomRingbackSizeBytes,
setCallRingbackTone,
]);
}, [callRingbackTone, setCallRingbackTone]);
const handleRingtoneSelection = (next: CallRingtoneId) => {
if (next === 'custom' && !hasCustomRingtone) {
@@ -448,7 +257,7 @@ export function CallSoundSettings() {
setCallRingtoneId(next);
};
const handleRingbackSelection = (next: CallRingbackTone) => {
const handleRingbackSelection = (next: CallRingtoneId) => {
if (next === 'custom' && !hasCustomRingback) {
setCustomError('Import a custom ringback file first.');
return;
@@ -562,9 +371,7 @@ export function CallSoundSettings() {
title="Custom Ringtone"
focusId="custom-call-ringtone"
description="Import an audio file for your ringtone."
fileName={callCustomRingtoneName}
sizeBytes={callCustomRingtoneSizeBytes}
durationMs={callCustomRingtoneDurationMs}
metadata={customRingtoneMeta}
emptyLabel="No custom ringtone imported."
hasCustomTone={hasCustomRingtone}
previewing={previewing}
@@ -580,9 +387,7 @@ export function CallSoundSettings() {
title="Custom Ringback"
focusId="custom-call-ringback"
description="Import an audio file for outgoing ringback."
fileName={callCustomRingbackName}
sizeBytes={callCustomRingbackSizeBytes}
durationMs={callCustomRingbackDurationMs}
metadata={customRingbackMeta}
emptyLabel="No custom ringback imported."
hasCustomTone={hasCustomRingback}
previewing={previewing}
@@ -0,0 +1,149 @@
import { Box, Button, Icon, Icons, Spinner, Text } from 'folds';
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { SequenceCardStyle } from '$features/settings/styles.css';
import {
CUSTOM_CALL_RINGTONE_MAX_BYTES,
CUSTOM_CALL_RINGTONE_MAX_DURATION_MS,
} from '$features/call/callRingtone';
import { bytesToSize, millisecondsToMinutesAndSeconds } from '$utils/common';
export type PreviewTone = 'incoming' | 'outgoing';
export type CustomToneMetadata = {
fileName: string;
sizeBytes: number;
durationMs: number;
};
export function CustomToneMeta({
metadata,
emptyLabel,
}: {
metadata: CustomToneMetadata | null;
emptyLabel: string;
}) {
if (!metadata) {
return (
<Text size="T200" priority="300">
{emptyLabel}
</Text>
);
}
return (
<Text size="T200" priority="300">
{[
metadata.fileName,
bytesToSize(metadata.sizeBytes),
millisecondsToMinutesAndSeconds(metadata.durationMs),
].join(' - ')}
</Text>
);
}
export function CustomToneSettingsCard({
title,
focusId,
description,
metadata,
emptyLabel,
hasCustomTone,
previewing,
previewActions,
onImport,
onPreview,
onReset,
}: {
title: string;
focusId: string;
description: string;
metadata: CustomToneMetadata | null;
emptyLabel: string;
hasCustomTone: boolean;
previewing: boolean;
previewActions: {
label: string;
tone: PreviewTone;
icon: (typeof Icons)[keyof typeof Icons];
}[];
onImport: () => void;
onPreview: (tone: PreviewTone) => void;
onReset: () => void;
}) {
return (
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile title={title} focusId={focusId} description={description}>
<Box direction="Column" gap="200">
<CustomToneMeta metadata={metadata} emptyLabel={emptyLabel} />
<Box gap="200" wrap="Wrap">
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.ArrowTop} size="100" />}
onClick={onImport}
>
<Text size="B300">Import</Text>
</Button>
{previewActions.map(({ label, tone, icon }) => (
<Button
key={label}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={
previewing ? (
<Spinner variant="Secondary" size="100" />
) : (
<Icon src={icon} size="100" />
)
}
onClick={() => onPreview(tone)}
disabled={previewing}
>
<Text size="B300">{label}</Text>
</Button>
))}
<Button
variant="Critical"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.Cross} size="100" />}
onClick={onReset}
disabled={!hasCustomTone}
>
<Text size="B300">Reset</Text>
</Button>
</Box>
<Text size="T200" priority="300">
Max file size: {bytesToSize(CUSTOM_CALL_RINGTONE_MAX_BYTES)}. Max duration:{' '}
{millisecondsToMinutesAndSeconds(CUSTOM_CALL_RINGTONE_MAX_DURATION_MS)}.
</Text>
</Box>
</SettingTile>
</SequenceCard>
);
}
export const customToneValidationError = (
reason: 'type' | 'size' | 'duration',
label: 'Ringtone' | 'Ringback'
): string => {
if (reason === 'type') return 'Only audio files are supported.';
if (reason === 'size') {
return `File is too large. Max ${bytesToSize(CUSTOM_CALL_RINGTONE_MAX_BYTES)} allowed.`;
}
return `${label} must be between 1s and ${millisecondsToMinutesAndSeconds(
CUSTOM_CALL_RINGTONE_MAX_DURATION_MS
)}.`;
};
@@ -1,7 +1,7 @@
import { useMemo } from 'react';
import type { PermissionGroup } from '$features/common-settings/permissions';
import { CALL_PERMISSIONS_GROUP } from '$features/common-settings/permissions/callPermissions';
import { CALL_PERMISSIONS_GROUP } from '$features/common-settings/permissions';
import { EventType } from '$types/matrix-sdk';
import { CustomStateEvent } from '$types/matrix/room';
+110 -269
View File
@@ -1,13 +1,8 @@
import { useCallback, useEffect, useRef } from 'react';
import * as Sentry from '@sentry/react';
import { useAtomValue, useSetAtom, useStore } from 'jotai';
import type { RoomEventHandlerMap, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import {
type CryptoBackend,
MatrixRTCSession,
MatrixRTCSessionManagerEvents,
RoomEvent,
} from '$types/matrix-sdk';
import type { RoomEventHandlerMap, MatrixEvent, Room } from '$types/matrix-sdk';
import { MatrixRTCSessionManagerEvents, RoomEvent } from '$types/matrix-sdk';
import { mDirectAtom } from '$state/mDirectList';
import {
callEmbedAtom,
@@ -18,12 +13,26 @@ import {
} from '$state/callEmbed';
import { settingsAtom } from '$state/settings';
import {
parseRtcDecline,
parseIncomingRtcNotification,
RTC_DECLINE_EVENT_TYPE,
REFERENCE_REL_TYPE,
RTC_NOTIFICATION_EVENT_TYPE,
} from '$features/call/rtcNotificationParser';
import { decryptRtcTimelineEvent } from '$features/call/callSignalingDecrypt';
import {
FALLBACK_INTERVAL_MS,
MAX_NOTIFICATION_LIFETIME_MS,
OUTGOING_DECLINE_EMBED_CLEAR_MS,
} from '$features/call/callSignalingPolicy';
import {
applyOutgoingDeclineToTracker,
type OutgoingDeclineEvent,
} from '$features/call/outgoingDeclineHandler';
import { parseRtcDeclineFromTimelineEvent } from '$features/call/rtcTimelineDecline';
import {
evaluateIncomingCallFallback,
evaluateOutgoingRingbackFallback,
} from '$features/call/callSignalingFallback';
import { callRingtoneVolumeToGain, canPlayCallAudio } from '$features/call/callRingtone';
import { dismissSystemCallNotifications } from '$features/call/callNotificationBridge';
import { resolveCallToneSources } from '$features/call/callToneSources';
@@ -32,112 +41,6 @@ import { createDebugLogger } from '../utils/debugLogger';
const debugLog = createDebugLogger('CallSignaling');
const MAX_NOTIFICATION_LIFETIME_MS = 120_000;
const DECRYPT_TIMEOUT_MS = 8_000;
const FALLBACK_INTERVAL_MS = 5_000;
const OUTGOING_RING_TIMEOUT_MS = 30_000;
type SessionDescription = Parameters<typeof MatrixRTCSession.sessionMembershipsForRoom>[1];
type RtcMembership = { userId?: string; sender?: string };
const getRoomMemberships = (room: Room, sessionDescription: SessionDescription) =>
MatrixRTCSession.sessionMembershipsForRoom(room, sessionDescription);
const getCallMembershipPresence = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
) => {
const memberships = getRoomMemberships(room, sessionDescription) as RtcMembership[];
const remoteMemberCount = memberships.filter(
(membership) => (membership.userId || membership.sender) !== mxUserId
).length;
const hasSelfMember = memberships.some(
(membership) => (membership.userId || membership.sender) === mxUserId
);
return { hasSelfMember, remoteMemberCount };
};
const isIncomingCallActive = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return remoteMemberCount > 0 && !hasSelfMember;
};
const isCallActive = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return hasSelfMember && remoteMemberCount > 0;
};
const isOutgoingCallPending = (
mxUserId: string,
room: Room,
sessionDescription: SessionDescription
): boolean => {
const { hasSelfMember, remoteMemberCount } = getCallMembershipPresence(
mxUserId,
room,
sessionDescription
);
return hasSelfMember && remoteMemberCount === 0;
};
const decryptWithTimeout = async (
event: MatrixEvent,
mx: MatrixClient
): Promise<{ type?: string; content?: unknown } | undefined> => {
const crypto = mx.getCrypto();
if (!crypto) return undefined;
try {
if (!event.isBeingDecrypted()) {
await event.attemptDecryption(crypto as CryptoBackend);
}
const decryptionPromise = event.getDecryptionPromise();
if (decryptionPromise) {
await Promise.race([
decryptionPromise,
new Promise<void>((resolve) => {
window.setTimeout(resolve, DECRYPT_TIMEOUT_MS);
}),
]);
}
} catch (error) {
debugLog.warn('call', 'RTC notification decryption failed', {
eventId: event.getId(),
roomId: event.getRoomId(),
error: error instanceof Error ? error.message : String(error),
});
return undefined;
}
const effectiveEvent = event.getEffectiveEvent();
return {
type: effectiveEvent.type,
content: effectiveEvent.content,
};
};
const canSenderStartCalls = (room: Room, senderId: string): boolean =>
room.currentState?.maySendStateEvent('org.matrix.msc3401.call.member', senderId) ?? false;
@@ -159,6 +62,19 @@ export function useIncomingCallSignaling() {
const incomingCallRef = useRef<IncomingCall | null>(incomingCall);
const mutedRoomIdRef = useRef<string | null>(mutedRoomId);
const seenNotificationIdsRef = useRef<Set<string>>(new Set());
const MAX_SEEN_NOTIFICATION_IDS = 256;
const rememberNotificationId = (notificationEventId: string) => {
const seen = seenNotificationIdsRef.current;
if (seen.has(notificationEventId)) return false;
seen.add(notificationEventId);
while (seen.size > MAX_SEEN_NOTIFICATION_IDS) {
const oldest = seen.values().next().value;
if (!oldest) break;
seen.delete(oldest);
}
return true;
};
const outgoingRingRoomIdRef = useRef<string | null>(null);
const declinedOutgoingRoomIdRef = useRef<string | null>(null);
const outgoingDeclinesRef = useRef<
@@ -283,12 +199,7 @@ export function useIncomingCallSignaling() {
}, [setIncomingCall, stopIncomingRing]);
const handleOutgoingDecline = useCallback(
(decline: {
roomId: string;
declineEventId: string;
notificationEventId: string;
senderId: string;
}) => {
(decline: OutgoingDeclineEvent) => {
if (!callEmbed || callEmbed.roomId !== decline.roomId) {
return;
}
@@ -298,7 +209,6 @@ export function useIncomingCallSignaling() {
return;
}
const isDirectRoom = mDirects.has(decline.roomId);
const remoteJoinedIds = new Set(
outgoingRoom
.getJoinedMembers()
@@ -306,29 +216,18 @@ export function useIncomingCallSignaling() {
.filter((userId) => userId !== mx.getSafeUserId())
);
const trackedDecline = outgoingDeclinesRef.current.get(decline.roomId);
const declineState =
trackedDecline && trackedDecline.notificationEventId === decline.notificationEventId
? trackedDecline
: {
notificationEventId: decline.notificationEventId,
declinerIds: new Set<string>(),
};
declineState.declinerIds.add(decline.senderId);
outgoingDeclinesRef.current.set(decline.roomId, declineState);
const decision = applyOutgoingDeclineToTracker(outgoingDeclinesRef.current, decline, {
remoteJoinedIds,
isDirectRoom: mDirects.has(decline.roomId),
});
const allRemoteDeclined =
remoteJoinedIds.size > 0 &&
[...remoteJoinedIds].every((userId) => declineState.declinerIds.has(userId));
const treatAsOneToOne = isDirectRoom || remoteJoinedIds.size <= 1;
if (!treatAsOneToOne && remoteJoinedIds.size > 0 && !allRemoteDeclined) {
if (decision.kind === 'ignore_partial') {
debugLog.info('call', 'Ignoring partial outgoing decline for group call', {
roomId: decline.roomId,
declineEventId: decline.declineEventId,
notificationEventId: decline.notificationEventId,
declinedCount: declineState.declinerIds.size,
targetCount: remoteJoinedIds.size,
declinedCount: decision.declinedCount,
targetCount: decision.targetCount,
});
Sentry.metrics.count('sable.call.outgoing.declined.partial', 1);
return;
@@ -339,8 +238,8 @@ export function useIncomingCallSignaling() {
roomId: decline.roomId,
declineEventId: decline.declineEventId,
notificationEventId: decline.notificationEventId,
declinedCount: declineState.declinerIds.size,
targetCount: remoteJoinedIds.size,
declinedCount: decision.declinedCount,
targetCount: decision.targetCount,
});
Sentry.metrics.count('sable.call.outgoing.declined', 1);
stopOutgoingRing();
@@ -359,7 +258,7 @@ export function useIncomingCallSignaling() {
const activeEmbed = store.get(callEmbedAtom);
if (activeEmbed !== callEmbed) return;
setCallEmbed(undefined);
}, 2_000);
}, OUTGOING_DECLINE_EMBED_CLEAR_MS);
});
},
[callEmbed, mDirects, mx, setCallEmbed, stopOutgoingRing, store]
@@ -402,9 +301,7 @@ export function useIncomingCallSignaling() {
const handleIncomingCall = useCallback(
(nextIncomingCall: IncomingCall) => {
if (mutedRoomIdRef.current === nextIncomingCall.roomId) return;
if (seenNotificationIdsRef.current.has(nextIncomingCall.notificationEventId)) return;
seenNotificationIdsRef.current.add(nextIncomingCall.notificationEventId);
if (!rememberNotificationId(nextIncomingCall.notificationEventId)) return;
setIncomingCall(nextIncomingCall);
debugLog.info('call', 'Incoming RTC notification accepted', {
@@ -464,7 +361,7 @@ export function useIncomingCallSignaling() {
let content = event.getContent();
if (event.isEncrypted()) {
const decrypted = await decryptWithTimeout(event, mx);
const decrypted = await decryptRtcTimelineEvent(event, mx);
if (!decrypted?.content || !decrypted.type) {
Sentry.metrics.count('sable.call.signal.decrypt_timeout', 1);
return undefined;
@@ -510,57 +407,7 @@ export function useIncomingCallSignaling() {
};
};
const parseDeclineEvent = async (
event: MatrixEvent,
room: Room,
liveEvent: boolean
): Promise<ReturnType<typeof parseRtcDecline>> => {
let eventType = event.getType();
let content = event.getContent();
if (event.isEncrypted()) {
const decrypted = await decryptWithTimeout(event, mx);
if (!decrypted?.content || !decrypted.type) {
Sentry.metrics.count('sable.call.signal.decrypt_timeout', 1);
} else {
eventType = decrypted.type;
content = decrypted.content;
}
}
const relationFromContent = (() => {
if (!content || typeof content !== 'object') return undefined;
const maybeRelates = (content as { 'm.relates_to'?: unknown })['m.relates_to'];
if (!maybeRelates || typeof maybeRelates !== 'object') return undefined;
const relation = maybeRelates as { rel_type?: unknown; event_id?: unknown };
return {
rel_type: typeof relation.rel_type === 'string' ? relation.rel_type : undefined,
event_id: typeof relation.event_id === 'string' ? relation.event_id : undefined,
};
})();
const relation = event.getRelation() ?? relationFromContent;
const parsed = parseRtcDecline(
{
type: eventType,
sender: event.getSender() ?? '',
roomId: room.roomId,
eventId: event.getId() ?? '',
originServerTs: event.getTs(),
content,
relation: relation
? {
rel_type: relation.rel_type,
event_id: relation.event_id,
}
: undefined,
isLiveEvent: liveEvent,
isEncrypted: false,
},
{ myUserId }
);
return parsed;
};
let timelineHandlerEpoch = 0;
const handleTimelineEvent: RoomEventHandlerMap[RoomEvent.Timeline] = async (
event,
@@ -571,6 +418,9 @@ export function useIncomingCallSignaling() {
) => {
if (!room || !data.liveEvent) return;
const epochAtStart = timelineHandlerEpoch;
const isStale = () => epochAtStart !== timelineHandlerEpoch;
const relation = event.getRelation();
if (relation?.rel_type !== REFERENCE_REL_TYPE && !event.isEncrypted()) return;
@@ -586,6 +436,7 @@ export function useIncomingCallSignaling() {
if (!event.getId()) return;
const incoming = await parseEvent(event, room, data.liveEvent);
if (isStale()) return;
if (incoming) {
handlers().handleIncomingCall(incoming);
return;
@@ -602,87 +453,74 @@ export function useIncomingCallSignaling() {
return;
}
const decline = await parseDeclineEvent(event, room, data.liveEvent);
const decline = await parseRtcDeclineFromTimelineEvent(
event,
room,
data.liveEvent,
myUserId,
mx
);
if (isStale()) return;
if (decline) {
handlers().handleOutgoingDecline(decline);
return;
}
};
const evaluateFallbackState = () => {
const now = Date.now();
const fallbackContext = {
myUserId,
getRoom: (roomId: string) => mx.getRoom(roomId),
getSessionDescription: (room: Room) => mx.matrixRTC.getRoomSession(room).sessionDescription,
};
const currentIncoming = incomingCallRef.current;
if (currentIncoming) {
if (Date.now() >= currentIncoming.expiresAt) {
debugLog.info('call', 'Incoming call timed out', {
roomId: currentIncoming.roomId,
notificationEventId: currentIncoming.notificationEventId,
});
Sentry.metrics.count('sable.call.timeout', 1);
handlers().clearIncomingCall();
return;
}
const incomingRoom = mx.getRoom(currentIncoming.roomId);
if (!incomingRoom) {
handlers().clearIncomingCall();
return;
}
const session = mx.matrixRTC.getRoomSession(incomingRoom);
if (!isIncomingCallActive(myUserId, incomingRoom, session.sessionDescription)) {
// Session membership can lag behind live RTC notification delivery.
// Keep ringing for a short grace window before treating the call as ended.
if (now - currentIncoming.senderTs < 15_000) {
return;
}
debugLog.info('call', 'Incoming call cleared after membership drop', {
roomId: currentIncoming.roomId,
});
handlers().clearIncomingCall();
return;
}
}
const activeCallRoomId = handlers().callEmbed?.roomId;
if (!activeCallRoomId || !handlers().outgoingRingbackAllowed) {
handlers().stopOutgoingRing();
return;
}
if (declinedOutgoingRoomIdRef.current === activeCallRoomId) {
handlers().stopOutgoingRing();
return;
}
const outgoingRoom = mx.getRoom(activeCallRoomId);
if (!outgoingRoom) {
handlers().stopOutgoingRing();
return;
}
const session = mx.matrixRTC.getRoomSession(outgoingRoom);
const pendingOutgoing = isOutgoingCallPending(
myUserId,
outgoingRoom,
session.sessionDescription
const evaluateIncomingFallback = () => {
const action = evaluateIncomingCallFallback(
incomingCallRef.current,
Date.now(),
fallbackContext
);
const activeCall = isCallActive(myUserId, outgoingRoom, session.sessionDescription);
if (action.kind !== 'clear') return;
if (!pendingOutgoing || activeCall) {
if (action.reason === 'expired') {
const currentIncoming = incomingCallRef.current;
debugLog.info('call', 'Incoming call timed out', {
roomId: currentIncoming?.roomId,
notificationEventId: currentIncoming?.notificationEventId,
});
Sentry.metrics.count('sable.call.timeout', 1);
} else if (action.reason === 'membership_dropped') {
debugLog.info('call', 'Incoming call cleared after membership drop', {
roomId: incomingCallRef.current?.roomId,
});
}
handlers().clearIncomingCall();
};
const evaluateOutgoingFallback = () => {
const ringAction = evaluateOutgoingRingbackFallback(
{
ringRoomId: outgoingRingRoomIdRef.current,
ringStartedAt: outgoingStartRef.current,
},
Date.now(),
{
...fallbackContext,
activeCallRoomId: handlers().callEmbed?.roomId,
outgoingRingbackAllowed: handlers().outgoingRingbackAllowed,
declinedRoomId: declinedOutgoingRoomIdRef.current,
}
);
outgoingRingRoomIdRef.current = ringAction.nextState.ringRoomId;
outgoingStartRef.current = ringAction.nextState.ringStartedAt;
if (ringAction.kind === 'stop') {
handlers().stopOutgoingRing();
return;
}
if (outgoingRingRoomIdRef.current !== activeCallRoomId) {
outgoingRingRoomIdRef.current = activeCallRoomId;
outgoingStartRef.current = now;
debugLog.info('call', 'Outgoing ringing fallback started', { roomId: activeCallRoomId });
}
if (outgoingStartRef.current && now - outgoingStartRef.current >= OUTGOING_RING_TIMEOUT_MS) {
handlers().stopOutgoingRing();
return;
if (ringAction.started) {
debugLog.info('call', 'Outgoing ringing fallback started', { roomId: ringAction.roomId });
}
outgoingAudioRef.current?.play().catch(() => {
@@ -690,6 +528,11 @@ export function useIncomingCallSignaling() {
});
};
const evaluateFallbackState = () => {
evaluateIncomingFallback();
evaluateOutgoingFallback();
};
const handleSessionEnded = (roomId: string) => {
if (mutedRoomIdRef.current === roomId) handlers().setMutedRoomId(null);
evaluateFallbackState();
@@ -703,6 +546,7 @@ export function useIncomingCallSignaling() {
evaluateFallbackState();
return () => {
timelineHandlerEpoch += 1;
mx.off(RoomEvent.Timeline, handleTimelineEvent);
mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionStarted, evaluateFallbackState);
mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionEnded, handleSessionEnded);
@@ -715,6 +559,3 @@ export function useIncomingCallSignaling() {
return null;
}
export function useCallSignaling() {
return useIncomingCallSignaling();
}
-8
View File
@@ -63,14 +63,6 @@ export class CallWidgetDriver extends WidgetDriver {
});
}
const requestedSableCapabilities = ['moe.sable.thumbnails', 'moe.sable.media_proxy'].filter(
(cap) => requested.has(cap)
);
debugLog.info('call', 'Sable-only capability request status', {
roomId: this.inRoomId,
requestedSableCapabilities,
});
return new Set(allow);
}
+3 -7
View File
@@ -63,7 +63,7 @@ describe('mergePersistedSettings', () => {
expect(mergedDefault.callRingbackTone).toBe('classic-soft');
});
it('drops invalid custom ringtone metadata during migration', () => {
it('ignores legacy custom tone metadata keys during migration', () => {
localStorage.setItem(
'settings',
JSON.stringify({
@@ -76,12 +76,8 @@ describe('mergePersistedSettings', () => {
})
);
const merged = mergePersistedSettings(localStorage.getItem('settings'), {});
expect(merged.callCustomRingtoneName).toBe('tone.ogg');
expect(merged.callCustomRingtoneSizeBytes).toBeUndefined();
expect(merged.callCustomRingtoneDurationMs).toBeNull();
expect(merged.callCustomRingbackName).toBe('ringback.ogg');
expect(merged.callCustomRingbackSizeBytes).toBeUndefined();
expect(merged.callCustomRingbackDurationMs).toBeNull();
expect(merged).not.toHaveProperty('callCustomRingtoneName');
expect(merged).not.toHaveProperty('callCustomRingbackName');
});
});
+12 -32
View File
@@ -37,7 +37,6 @@ export const CALL_TONE_IDS = [
'custom',
] as const;
export type CallRingtoneId = (typeof CALL_TONE_IDS)[number];
export type CallRingbackTone = CallRingtoneId;
export type ThemeRemoteFavorite = {
fullUrl: string;
@@ -166,14 +165,8 @@ export interface Settings {
outgoingRingbackEnabled: boolean;
callRingtoneVolume: number;
callRingtoneId: CallRingtoneId;
callRingbackTone: CallRingbackTone;
callRingbackTone: CallRingtoneId;
callSoundOverrideGlobalNotifications: boolean;
callCustomRingtoneName?: string;
callCustomRingtoneSizeBytes?: number;
callCustomRingtoneDurationMs?: number;
callCustomRingbackName?: string;
callCustomRingbackSizeBytes?: number;
callCustomRingbackDurationMs?: number;
faviconForMentionsOnly: boolean;
highlightMentions: boolean;
pkCompat: boolean;
@@ -312,12 +305,6 @@ export const defaultSettings: Settings = {
callRingtoneId: 'sable-default',
callRingbackTone: 'sable-default',
callSoundOverrideGlobalNotifications: false,
callCustomRingtoneName: undefined,
callCustomRingtoneSizeBytes: undefined,
callCustomRingtoneDurationMs: undefined,
callCustomRingbackName: undefined,
callCustomRingbackSizeBytes: undefined,
callCustomRingbackDurationMs: undefined,
faviconForMentionsOnly: false,
highlightMentions: true,
pkCompat: false,
@@ -367,12 +354,6 @@ function cloneDefaultSettings(): Settings {
}
const CALL_TONE_ID_SET = new Set<unknown>(CALL_TONE_IDS);
const CALL_AUDIO_METADATA_NUMBER_KEYS = [
'callCustomRingtoneSizeBytes',
'callCustomRingtoneDurationMs',
'callCustomRingbackSizeBytes',
'callCustomRingbackDurationMs',
] as const;
const isCallToneId = (value: unknown): value is CallRingtoneId => CALL_TONE_ID_SET.has(value);
@@ -424,11 +405,17 @@ function migrateParsedLocalStorage(parsed: Record<string, unknown>): void {
delete parsed.callRingbackTone;
}
for (const key of CALL_AUDIO_METADATA_NUMBER_KEYS) {
const value = parsed[key];
if (typeof value === 'number' && (!Number.isFinite(value) || value < 0)) {
delete parsed[key];
}
const legacyCallCustomMetadataKeys = [
'callCustomRingtoneName',
'callCustomRingtoneSizeBytes',
'callCustomRingtoneDurationMs',
'callCustomRingbackName',
'callCustomRingbackSizeBytes',
'callCustomRingbackDurationMs',
] as const;
for (const key of legacyCallCustomMetadataKeys) {
delete parsed[key];
}
}
@@ -547,13 +534,6 @@ function sanitizeSettingsKey(key: keyof Settings, val: unknown): unknown {
case 'callRingtoneVolume':
if (typeof val !== 'number' || !Number.isFinite(val)) return undefined;
return clampPercent(val);
case 'callCustomRingtoneSizeBytes':
case 'callCustomRingtoneDurationMs':
case 'callCustomRingbackSizeBytes':
case 'callCustomRingbackDurationMs':
return typeof val === 'number' && Number.isFinite(val) && val >= 0
? Math.round(val)
: undefined;
case 'renderUserCards':
return val === 'both' || val === 'light' || val === 'dark' || val === 'none'
? val
-6
View File
@@ -37,12 +37,6 @@ describe('NON_SYNCABLE_KEYS', () => {
'callRingtoneId',
'callRingbackTone',
'callSoundOverrideGlobalNotifications',
'callCustomRingtoneName',
'callCustomRingtoneSizeBytes',
'callCustomRingtoneDurationMs',
'callCustomRingbackName',
'callCustomRingbackSizeBytes',
'callCustomRingbackDurationMs',
'developerTools',
'settingsSyncEnabled',
] as const;
-6
View File
@@ -21,12 +21,6 @@ export const NON_SYNCABLE_KEYS = new Set<keyof Settings>([
'callRingtoneId',
'callRingbackTone',
'callSoundOverrideGlobalNotifications',
'callCustomRingtoneName',
'callCustomRingtoneSizeBytes',
'callCustomRingtoneDurationMs',
'callCustomRingbackName',
'callCustomRingbackSizeBytes',
'callCustomRingbackDurationMs',
// Developer / diagnostic
'developerTools',
// Sync toggle itself must never be uploaded (it's device-local)
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest';
import { resolveCallNotificationCopy } from './pushCallNotificationCopy';
describe('resolveCallNotificationCopy', () => {
it('uses generic room-call copy when previews are hidden', () => {
expect(
resolveCallNotificationCopy({
notificationType: 'notification',
intentKind: 'audio',
showPreviewDetails: false,
})
).toEqual({
title: 'Room call started',
body: 'Open Sable to join.',
});
});
it('uses sender and room details for ring notifications', () => {
expect(
resolveCallNotificationCopy({
notificationType: 'ring',
intentKind: 'video',
senderDisplayName: 'Alice',
roomName: 'General',
showPreviewDetails: true,
})
).toEqual({
title: 'Incoming video call',
body: 'Alice is calling you in General',
});
});
});
+120
View File
@@ -0,0 +1,120 @@
type CallNotificationType = 'ring' | 'notification';
type CallIntentKind = 'audio' | 'video';
export type CallNotificationCopyContext = {
notificationType: CallNotificationType;
intentKind: CallIntentKind;
senderDisplayName?: string;
roomName?: string;
showPreviewDetails: boolean;
};
type CopyTemplate = {
title: string | ((ctx: CallNotificationCopyContext) => string);
body: string | ((ctx: CallNotificationCopyContext) => string | undefined);
};
type CopyRule = {
when: (ctx: CallNotificationCopyContext) => boolean;
template: CopyTemplate;
};
const firstMatchingTemplate = (
ctx: CallNotificationCopyContext,
rules: CopyRule[]
): CopyTemplate | undefined => {
for (const rule of rules) {
if (rule.when(ctx)) return rule.template;
}
return undefined;
};
const resolveTemplate = (
ctx: CallNotificationCopyContext,
template: CopyTemplate
): { title: string; body: string | undefined } => ({
title: template.title,
body: typeof template.body === 'function' ? template.body(ctx) : template.body,
});
const ROOM_CALL_RULES: CopyRule[] = [
{
when: (ctx) => !ctx.showPreviewDetails,
template: { title: 'Room call started', body: 'Open Sable to join.' },
},
{
when: (ctx) => Boolean(ctx.senderDisplayName && ctx.roomName),
template: {
title: 'Room call started',
body: (ctx) => `${ctx.senderDisplayName} started a call in ${ctx.roomName}`,
},
},
{
when: (ctx) => Boolean(ctx.roomName),
template: { title: 'Room call started', body: (ctx) => `A call started in ${ctx.roomName}` },
},
{
when: (ctx) => Boolean(ctx.senderDisplayName),
template: {
title: 'Room call started',
body: (ctx) => `${ctx.senderDisplayName} started a call`,
},
},
{
when: () => true,
template: { title: 'Room call started', body: 'A room call started.' },
},
];
const RING_CALL_RULES: CopyRule[] = [
{
when: (ctx) => !ctx.showPreviewDetails,
template: {
title: (ctx) => (ctx.intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call'),
body: 'Open Sable to answer.',
},
},
{
when: (ctx) => Boolean(ctx.senderDisplayName && ctx.roomName),
template: {
title: (ctx) => (ctx.intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call'),
body: (ctx) => `${ctx.senderDisplayName} is calling you in ${ctx.roomName}`,
},
},
{
when: (ctx) => Boolean(ctx.senderDisplayName),
template: {
title: (ctx) => (ctx.intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call'),
body: (ctx) => `${ctx.senderDisplayName} is calling you`,
},
},
{
when: (ctx) => Boolean(ctx.roomName),
template: {
title: (ctx) => (ctx.intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call'),
body: (ctx) => `Incoming call in ${ctx.roomName}`,
},
},
{
when: () => true,
template: {
title: (ctx) => (ctx.intentKind === 'video' ? 'Incoming video call' : 'Incoming voice call'),
body: 'Incoming call',
},
},
];
export const resolveCallNotificationCopy = (
ctx: CallNotificationCopyContext
): { title: string; body: string | undefined } => {
const rules = ctx.notificationType === 'notification' ? ROOM_CALL_RULES : RING_CALL_RULES;
const template = firstMatchingTemplate(ctx, rules);
if (!template) {
return { title: 'Incoming call', body: undefined };
}
return {
title: typeof template.title === 'function' ? template.title(ctx) : template.title,
body: typeof template.body === 'function' ? template.body(ctx) : template.body,
};
};
+7 -81
View File
@@ -1,12 +1,14 @@
/* oxlint-disable no-console */
// Keep the service worker import graph narrow, the app barrel pulls in runtime Matrix SDK modules that break SW script evaluation
import { EventType } from 'matrix-js-sdk/lib/@types/event';
import { normalizeCallIntent } from '../app/features/call/callIntent';
import {
buildRoomMessageNotification,
DEFAULT_NOTIFICATION_ICON,
DEFAULT_NOTIFICATION_BADGE,
resolveNotificationPreviewText,
} from '../app/utils/notificationStyle';
import { resolveCallNotificationCopy } from './pushCallNotificationCopy';
type NotificationSettings = {
showMessageContent: boolean;
@@ -37,13 +39,6 @@ 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';
@@ -74,75 +69,6 @@ const getCallTiming = (
};
};
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,
getNotificationSettings: () => NotificationSettings
@@ -188,17 +114,17 @@ export const createPushNotifications = (
typeof pushData?.content?.['m.call.intent'] === 'string'
? pushData.content['m.call.intent']
: undefined;
const intentKind = normalizeCallIntentKind(intentRaw);
const intentKind = normalizeCallIntent(undefined, intentRaw);
const senderDisplayName = pushData?.sender_display_name;
const roomName = pushData?.room_name;
const showPreviewDetails = getNotificationSettings().showMessageContent;
const copy = resolveCallNotificationCopy(
notificationTypeRaw,
const copy = resolveCallNotificationCopy({
notificationType: notificationTypeRaw,
intentKind,
senderDisplayName,
roomName,
showPreviewDetails
);
showPreviewDetails,
});
const originTs = typeof pushData.timestamp === 'number' ? pushData.timestamp : Date.now();
const { senderTs, expiresAt } = getCallTiming(pushData.content, originTs);