/* Copyright 2025 Element Creations Ltd. SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial Please see LICENSE in the repository root for full details. */ import { type IRTCNotificationContent, type MatrixRTCSession, MatrixRTCSessionEvent, RTC_CALL_INTENT_AUDIO, type RTCCallIntent, toStableCallIntent, } from "matrix-js-sdk/lib/matrixrtc"; import { defer, filter, from, fromEvent, map, merge, NEVER, type Observable, of, pairwise, switchMap, timer, EMPTY, race, take, mergeMap, } from "rxjs"; import { type EventTimelineSetHandlerMap, EventType, type MatrixEvent, type Room as MatrixRoom, RoomEvent, RoomStickyEventsEvent, } from "matrix-js-sdk"; import { type RoomStickyEventsMap } from "matrix-js-sdk/lib/models/room-sticky-events"; import { logger as rootLogger } from "matrix-js-sdk/lib/logger"; import { type Behavior, type ObservableScope } from "@element-hq/matrixrtc-sdk"; export type AutoLeaveReason = "allOthersLeft" | "timeout" | "decline"; export interface RingAttempt { intent: RTCCallIntent; /** * The user ID of the recipient being rung. */ recipient: string; /** * The eventual outcome of the ringing attempt. (Emits a single value.) */ // TODO: Include a callback for attempting ringing again in case of a timeout outcome$: Observable<"accept" | "decline" | "timeout">; } export type CallNotificationWrapper = { event_id: string; } & IRTCNotificationContent; export function createSentCallNotification$( scope: ObservableScope, matrixRTCSession: MatrixRTCSession, ): Behavior { const sentCallNotification$ = scope.behavior( fromEvent(matrixRTCSession, MatrixRTCSessionEvent.DidSendCallNotification), null, ) as Behavior; return sentCallNotification$; } export function createReceivedDecline$( matrixRoom: MatrixRoom, ): Observable { // A decline is sticky, so after a gappy sync it arrives only in the sticky // section, which never reaches the timeline. Racing for the first outcome // makes a decline seen in both places harmless. const timeline$ = ( fromEvent(matrixRoom, RoomEvent.Timeline) as Observable< Parameters > ).pipe(map(([event]) => event)); // The decline can arrive via sync before the send of our notification // resolves, which is when we start listening. To guard against this, we // include what is already in the sticky section. const currentSticky$ = defer(() => from(matrixRoom._unstable_getStickyEvents()), ); const sticky$ = ( fromEvent(matrixRoom, RoomStickyEventsEvent.Update) as Observable< Parameters > ).pipe( mergeMap(([added, updated]) => [ ...added, ...updated.map(({ current }) => current), ]), ); return merge(currentSticky$, sticky$, timeline$).pipe( filter((event) => event.getType() === EventType.RTCDecline), ); } export interface Props { scope: ObservableScope; /** The user ids of the session's members, ours included. */ memberUserIds$: Behavior; /** The user ids of the room's members, ours included. */ roomMemberUserIds$: Behavior; sentCallNotification$: Observable; receivedDecline$: Observable; options: { waitForCallPickup?: boolean; autoLeaveWhenOthersLeft?: boolean }; localUser: { deviceId: string; userId: string }; } export function createCallNotificationLifecycle$({ scope, memberUserIds$, roomMemberUserIds$, sentCallNotification$, receivedDecline$, options, localUser, }: Props): { /** * An observable of attempts to ring the remote participant's devices. */ ringAttempts$: Observable; /** * An observable that emits when the call should be automatically left. * - if options.autoLeaveWhenOthersLeft is set to true it emits when all others left. * - if options.waitForCallPickup is set to true it emits if noone picked up the ring or if the ring got declined. * - if options.autoLeaveWhenOthersLeft && options.waitForCallPickup is false it will never emit. */ autoLeave$: Observable; } { const logger = rootLogger.getChild("[CallNotificationLifecycle]"); let ringAttempts$: Observable = NEVER; if (options.waitForCallPickup) ringAttempts$ = sentCallNotification$.pipe( filter( ( notificationEvent: CallNotificationWrapper | null, ): notificationEvent is CallNotificationWrapper => // only care about new events (legacy do not have decline pattern) notificationEvent?.notification_type === "ring" && notificationEvent.lifetime > 0, ), switchMap((notificationEvent) => { // We assume that there is only one other user in the room when ringing // TODO: Respect io.element.functional_members const recipient = roomMemberUserIds$.value.find( (userId) => userId !== localUser.userId, ); if (recipient === undefined) { logger.warn("No recipient for notification event; not ringing."); return EMPTY; } // Ringing times out after lifetime ms have passed const timeout$ = timer(notificationEvent.lifetime).pipe( map(() => "timeout" as const), ); // Call is accepted when the recipient joins const accept$ = memberUserIds$.pipe( filter((userIds) => userIds.includes(recipient)), map(() => "accept" as const), ); // Call is declined when we receive a decline event const decline$ = receivedDecline$.pipe( filter( (event) => event.getRelation()?.rel_type === "m.reference" && event.getRelation()?.event_id === notificationEvent.event_id && event.getSender() === recipient, ), map(() => "decline" as const), ); return of({ // The notification still carries the legacy intent values intent: toStableCallIntent(notificationEvent["m.call.intent"]) ?? RTC_CALL_INTENT_AUDIO, recipient, outcome$: race(timeout$, accept$, decline$).pipe( take(1), // Make this observable 'hot' to avoid running multiple timers. This // is not actually a resource leak since there will be at most one // active ring attempt at any given time. // eslint-disable-next-line element-call/no-observablescope-leak scope.share, ), }); }), scope.share, ); const allOthersLeft$ = memberUserIds$.pipe( pairwise(), filter( ([prev, current]) => current.every((userId) => userId === localUser.userId) && prev.some((userId) => userId !== localUser.userId), ), map(() => {}), ); const autoLeave$ = merge( options.autoLeaveWhenOthersLeft === true ? allOthersLeft$.pipe(map(() => "allOthersLeft" as const)) : NEVER, ringAttempts$.pipe( switchMap(({ outcome$ }) => outcome$.pipe( filter((outcome) => outcome === "timeout" || outcome === "decline"), ), ), ), ); return { ringAttempts$, autoLeave$ }; }