/* Copyright 2023 - 2026 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { type Logger, logger as rootLogger } from "../logger.ts"; import { TypedEventEmitter } from "../models/typed-event-emitter.ts"; import { EventTimeline } from "../models/event-timeline.ts"; import { type Room } from "../models/room.ts"; import { type MatrixClient } from "../client.ts"; import { EventType, RelationType } from "../@types/event.ts"; import { KnownMembership } from "../@types/membership.ts"; import { type ISendEventResponse } from "../@types/requests.ts"; import { CallMembership } from "./CallMembership.ts"; import { toUnstableCallIntent } from "./CallIntent.ts"; import { RoomStateEvent } from "../models/room-state.ts"; import { MembershipManager, StickyEventMembershipManager } from "./MembershipManager.ts"; import { type CallMembershipIdentityParts, type IEncryptionManager } from "./EncryptionManager.ts"; import { deepCompare, logDurationSync } from "../utils.ts"; import type { Statistics, RTCNotificationType, Status, IRTCNotificationContent, RTCCallIntent, RTCCallCapability, Transport, SlotDescription, RtcSlotEventContent, RtcSlotEncryptionContent, } from "./types.ts"; import { RTC_NOTIFICATION_MAX_SENDER_TS_AHEAD_MS } from "./types.ts"; import { isLeftMembershipContent } from "./membershipData/index.ts"; import { UnsupportedStickyEventsEndpointError } from "../errors.ts"; import { MembershipManagerEvent, type MembershipManagerEventHandlerMap, type IMembershipManager, } from "./IMembershipManager.ts"; import { RTCEncryptionManager } from "./RTCEncryptionManager.ts"; import { ToDeviceKeyTransport } from "./ToDeviceKeyTransport.ts"; import { TypedReEmitter } from "../ReEmitter.ts"; import { type IContent, type MatrixEvent } from "../models/event.ts"; import { RoomStickyEventsEvent, type RoomStickyEventsMap } from "../models/room-sticky-events.ts"; import { computeSlotId, getSlotEventContent, isSlotClosed, isSlotOpen } from "./utils.ts"; /** * Events emitted by MatrixRTCSession */ export enum MatrixRTCSessionEvent { // A member joined, left, or updated a property of their membership. MembershipsChanged = "memberships_changed", // We joined or left the session: our own local idea of whether we are joined, // separate from MembershipsChanged, ie. independent of whether our member event // has successfully gone through. JoinStateChanged = "join_state_changed", // The key used to encrypt media has changed EncryptionKeyChanged = "encryption_key_changed", /** The membership manager had to shut down caused by an unrecoverable error */ MembershipManagerError = "membership_manager_error", /** The RTCSession did send a call notification caused by joining the call as the first member */ DidSendCallNotification = "did_send_call_notification", /** Whether the session is too large for the media key to be rotated has changed */ KeyRotationSuppressedChanged = "key_rotation_suppressed_changed", } export type MatrixRTCSessionEventHandlerMap = { [MatrixRTCSessionEvent.MembershipsChanged]: ( oldMemberships: CallMembership[], newMemberships: CallMembership[], ) => void; [MatrixRTCSessionEvent.JoinStateChanged]: (isJoined: boolean) => void; [MatrixRTCSessionEvent.EncryptionKeyChanged]: ( key: Uint8Array, encryptionKeyIndex: number, membership: CallMembershipIdentityParts, backendIdentity: string, ) => void; [MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void; [MatrixRTCSessionEvent.DidSendCallNotification]: ( notificationContentNew: { event_id: string } & IRTCNotificationContent, ) => void; [MatrixRTCSessionEvent.KeyRotationSuppressedChanged]: (isKeyRotationSuppressed: boolean) => void; }; export interface SessionConfig { /** * What kind of notification to send when starting the session. * @default `undefined` (no notification) */ notificationType?: RTCNotificationType; /** * Determines the kind of call this will be. */ callIntent?: RTCCallIntent; /** * What kinds of media this device is capable of handling for the call. */ callCapabilities?: RTCCallCapability[]; /** * Application-specific data to publish in our membership event (in the * `application` object of an `m.rtc.member` event, or at the top level of a * legacy `m.call.member` event). * * `type` is always written by the SDK from the slot's application and will be * dropped if given here. For `m.call` sessions, `intent`, `m.call.intent` and * `capabilities` are also written by the SDK from {@link SessionConfig.callIntent} * and {@link SessionConfig.callCapabilities} and will be dropped too. Other * application types may use those keys freely. * * Read back through {@link CallMembership.applicationData}. */ applicationData?: Record; /** * How long (in milliseconds) the callee's client should keep ringing/waiting for an * answer before the sender gives up and the call notification is considered timed out. */ notificationLifetimeMs?: number; } // The names follow these principles: // - we use the technical term delay if the option is related to delayed events. // - we use delayedLeaveEvent if the option is related to the delayed leave event. // - we use membershipEvent if the option is related to the rtc member state event. // - we use the technical term expiry if the option is related to the expiry field of the membership state event. // - we use a `Ms` postfix if the option is a duration to avoid using words like: // `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms. export interface MembershipConfig { /** * The timeout (in milliseconds) after we joined the call, that our membership should expire * unless we have explicitly updated it. * * This is what goes into the m.rtc.member event expiry field and is typically set to a number of hours. */ membershipEventExpiryMs?: number; /** * The time in (in milliseconds) which the manager will prematurely send the updated state event before the membership `expires` time to make sure it * sends the updated state event early enough. * * A headroom of 1000ms and a `membershipExpiryTimeout` of 10000ms would result in the first membership event update after 9s and * a membership event that would be considered expired after 10s. * * This value does not have an effect on the value of `SessionMembershipData.expires`. */ membershipEventExpiryHeadroomMs?: number; /** * The timeout (in milliseconds) with which the deleayed leave event on the server is configured. * After this time the server will set the event to the disconnected stat if it has not received a keep-alive from the client. */ delayedLeaveEventDelayMs?: number; /** * The interval (in milliseconds) in which the client will send membership keep-alives to the server. */ delayedLeaveEventRestartMs?: number; /** * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a server rate limit has been hit. */ maximumRateLimitRetryCount?: number; /** * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a network error occurs. */ maximumNetworkErrorRetryCount?: number; /** * The time (in milliseconds) after which we will retry a http request if it * failed to send due to a network error. (send membership event, send delayed event, restart delayed event...) */ networkErrorRetryMs?: number; /** * The time (in milliseconds) after which a we consider a delayed event restart http request to have failed. * Setting this to a lower value will result in more frequent retries but also a higher chance of failiour. * * In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs * helps by keeping more delayed event reset candidates in flight, * improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration, * but only applies to calls to the `_unstable_restartScheduledDelayedEvent` endpoint * or the `_unstable_updateDelayedEvent` endpoint with a body of `{action:"restart"}`.) */ delayedLeaveEventRestartLocalTimeoutMs?: number; /** * Send membership using sticky events rather than state events. * This also make the client use the new m.rtc.member MSC4354 event format. (instead of m.call.member) * * **WARNING**: This is an unstable feature and not all clients will support it. */ unstableSendStickyEvents?: boolean; } export interface EncryptionConfig { /** * If true, generate and share a media key for this participant, * and emit MatrixRTCSessionEvent.EncryptionKeyChanged when * media keys for other participants become available. */ manageMediaKeys?: boolean; /** * Sometimes it is necessary to rotate the encryption key after a membership update. * For performance reasons we might not want to rotate the key immediately but allow future memberships to use the same key. * If 5 people join in a row in less than 5 seconds, we don't want to rotate the key for each of them. * If 5 people leave in a row in less than 5 seconds, we don't want to rotate the key for each of them. * So we do share the key which was already used live for <5s to new joiners. * This does result in a potential leak up to the configured time of call media. * This has to be considered when choosing a value for this property. */ keyRotationGracePeriodMs?: number; /** * The number of participants in the session at which the media key will no longer be rotated. * * Rotating a key requires sending it to every participant device, so in large sessions the cost of rotating * on every join/leave becomes prohibitive. At this limit the current key is kept and * distributed to new joiners. No new keys are generated for joiners/leavers. * * Defaults to undefined. */ keyRotationParticipantLimit?: number; /** * The delay (in milliseconds) after a member leaves before we create and publish a new key, because people * tend to leave calls at the same time. * @deprecated - Not used by the new encryption manager. */ makeKeyDelay?: number; /** * The delay (in milliseconds) between sending a new key and starting to encrypt with it. This * gives others a chance to receive the new key to minimize the chance they get media they can't decrypt. * * The higher this value is, the better it is for existing members as they will have a smoother experience. * But it impacts new joiners: They will always have to wait `useKeyDelay` before being able to decrypt the media * (as it will be encrypted with the new key after the delay only), even if the key has already arrived before the delay. */ useKeyDelay?: number; } export type JoinSessionConfig = SessionConfig & MembershipConfig & EncryptionConfig; interface SessionMembershipsForSlotOpts { /** * Listen for incoming sticky member events. If disabled, this session will * ignore any incoming sticky events. */ listenForStickyEvents: boolean; /** * Listen for incoming member state events (legacy). If disabled, this session will * ignore any incoming state events. */ listenForMemberStateEvents: boolean; } const DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS: SessionMembershipsForSlotOpts = { listenForStickyEvents: true, listenForMemberStateEvents: true, }; /** * A MatrixRTCSession manages the membership & properties of a MatrixRTC session. * This class doesn't deal with media at all, just membership & properties of a session. */ export class MatrixRTCSession extends TypedEventEmitter< MatrixRTCSessionEvent | MembershipManagerEvent, MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap > { private membershipManager?: IMembershipManager; private encryptionManager?: IEncryptionManager; private joinConfig?: SessionConfig; private logger: Logger; private pendingNotificationToSend: undefined | RTCNotificationType; /** * This timeout is responsible to track any expiration. We need to know when we have to start * to ignore other call members. There is no callback for this. This timeout will always be configured to * emit when the next membership expires. */ private expiryTimeout?: ReturnType; public memberships: CallMembership[] = []; /** * Resolves when the session has calculated the initial membership of the session. */ public readonly initialMembershipCalculated: Promise; /** * Does membership need to be recalculated? This is set to false upon * recalculation. */ private membershipNeedsRecalculation = false; /** * The statistics for this session. */ public statistics: Statistics = { counters: { roomEventEncryptionKeysSent: 0, roomEventEncryptionKeysReceived: 0, }, totals: { roomEventEncryptionKeysReceivedTotalAge: 0, }, }; public get membershipStatus(): Status | undefined { return this.membershipManager?.status; } public get probablyLeft(): boolean | undefined { return this.membershipManager?.probablyLeft; } public get delayId(): string | undefined { return this.membershipManager?.delayId; } /** * Whether the key rotation is currently halted. * mirror of: EncryptionConfig.keyRotationParticipantLimit */ public get isKeyRotationSuppressed(): boolean { return this.encryptionManager?.isKeyRotationSuppressed ?? false; } /** * The slotId of the call. * `{application}#{appSpecificId}` * The slotId is the property that, per definition, groups memberships into one call. */ public get slotId(): string { return computeSlotId(this.slotDescription); } /** * Reads the current slot state event's content for this session. * * @returns The slot event's content, or `undefined` if no slot event exists for this session. */ public getRtcSlot(): RtcSlotEventContent | undefined { return getSlotEventContent(this.roomSubset, this.slotDescription); } /** * Whether this session's slot is closed. * * @returns `true` if the slot is closed, `false` if the slot is open or `undefined` * if no slot exists. */ public isSlotClosed(): boolean | undefined { return isSlotClosed(this.roomSubset, this.slotDescription); } /** * Whether this session's slot is open. * * @returns `true` if the slot is open, `false` if the slot is closed or `undefined` * if no slot exists. */ public isSlotOpen(): boolean | undefined { return isSlotOpen(this.roomSubset, this.slotDescription); } /** * Ensures this session's slot is open, sending a slot state event to open (or create) it if needed. * * The event's `application` is set from this session's slot description and its `encryption` from * `opts.encryption`, replacing whatever an existing slot event declares. Other content is preserved. * No-op if the slot is already open with matching `application` and `encryption`. * * @param opts.encryption - The encryption to declare on the slot, or `undefined` for none. * @throws if sending the state event fails. */ public async ensureRtcSlotOpen(opts: { encryption?: RtcSlotEncryptionContent } = {}): Promise { const application = { type: this.slotDescription.application }; const existingContent = this.getRtcSlot(); if ( existingContent?.status === "open" && deepCompare(existingContent.application, application) && deepCompare(existingContent.encryption, opts.encryption) ) { return; } await this.sendRtcSlot({ ...existingContent, status: "open", application, encryption: opts.encryption, }); } /** * Ensures this session's slot is closed, sending a slot state event to close it if needed. * The other content of the existing slot event is preserved. No-op if no slot event exists. * * @throws if sending the state event fails. */ public async ensureRtcSlotClosed(): Promise { const existingContent = this.getRtcSlot(); if (!existingContent || existingContent.status === "closed") return; await this.sendRtcSlot({ ...existingContent, status: "closed" }); } private async sendRtcSlot(content: RtcSlotEventContent): Promise { await this.client.sendStateEvent( this.roomSubset.roomId, EventType.RTCSlot, content, computeSlotId(this.slotDescription), ); } /** * Returns all the call memberships for a room that match the provided `sessionDescription`, * oldest first. * * By default, this will return *both* sticky and member state events. */ public static async sessionMembershipsForSlot( room: Pick, slotDescription: SlotDescription, // default both true this implied we combine sticky and state events for the final call state // (prefer sticky events in case of a duplicate) options: SessionMembershipsForSlotOpts = DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS, ): Promise { const logger = rootLogger.getChild( `[MatrixRTCSession ${room.roomId} ${slotDescription.application}#${slotDescription.id}]`, ); const callMemberEvents = collectMembersEvents(room, slotDescription, options, logger); const callMemberships = await computeBackendIdentityAndVerifyMemberEvents( room, callMemberEvents, slotDescription, logger, ); callMemberships.sort((a, b) => a.createdTs() - b.createdTs()); if (callMemberships.length > 1) { logger.debug( `Call memberships in room ${room.roomId}, in order: `, callMemberships.map((m) => [m.createdTs(), m.userId]), ); } return callMemberships; } /** * Return the MatrixRTC session for the room. * This returned session can be used to find out if there are active sessions * for the requested room and `slotDescription`. */ public static sessionForSlot( client: MatrixClient, room: Room, slotDescription: SlotDescription, opts?: SessionMembershipsForSlotOpts, ): MatrixRTCSession { return new MatrixRTCSession(client, room, slotDescription, opts); } /** * WARN: this can in theory only be a subset of the room with the properties required by * this class. * Outside of tests this most likely will be a full room, however. * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking * the room object in your own code and passing it in when needed. */ public get room(): Room { return this.roomSubset as Room; } /** * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected * to be used with the MatrixRTCSessionManager exclusively. * * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone * to manage a joined MatrixRTC session. * * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room. * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs. * @param slotDescription The slot description is a virtual address where participants are allowed to meet. * This session will only manage memberships that match this slot description.Sessions are distinct if any of * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`. * @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session. */ public constructor( private readonly client: Pick< MatrixClient, | "getUserId" | "getDeviceId" | "fetchCapabilities" | "getCachedCapabilities" | "sendEvent" | "sendStateEvent" | "_unstable_sendDelayedStateEvent" | "_unstable_updateDelayedEvent" | "_unstable_cancelScheduledDelayedEvent" | "_unstable_restartScheduledDelayedEvent" | "_unstable_sendScheduledDelayedEvent" | "_unstable_sendStickyEvent" | "_unstable_sendStickyDelayedEvent" | "cancelPendingEvent" | "encryptAndSendToDevice" | "off" | "on" | "decryptEventIfNeeded" >, private roomSubset: Pick< Room, | "getLiveTimeline" | "roomId" | "getVersion" | "hasMembershipState" | "on" | "off" | "_unstable_getStickyEvents" >, public readonly slotDescription: SlotDescription, private readonly calculateMembershipsOpts?: SessionMembershipsForSlotOpts, ) { super(); this.logger = rootLogger.getChild( `[MatrixRTCSession ${roomSubset.roomId} ${slotDescription.application}#${slotDescription.id}]`, ); this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate); this.roomSubset.on(RoomStateEvent.Events, this.onRoomStateEvent); this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate); this.initialMembershipCalculated = this.ensureRecalculateSessionMembers(); this.setExpiryTimer(); } /* * Returns true if we intend to be participating in the MatrixRTC session. */ public isJoined(): boolean { return this.membershipManager?.isActivated() ?? false; } /** * Performs cleanup & removes timers for client shutdown */ public async stop(): Promise { await this.membershipManager?.leave(1000); if (this.expiryTimeout) { clearTimeout(this.expiryTimeout); this.expiryTimeout = undefined; } this.roomSubset.off(RoomStateEvent.Members, this.onRoomMemberUpdate); this.roomSubset.off(RoomStateEvent.Events, this.onRoomStateEvent); this.roomSubset.off(RoomStickyEventsEvent.Update, this.onStickyEventUpdate); } private reEmitter = new TypedReEmitter< MatrixRTCSessionEvent | MembershipManagerEvent, MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap >(this); /** * Announces this user and device as joined to the MatrixRTC session, * and continues to update the membership event to keep it valid until * leaveRoomSession() is called * This method will return immediately and the session will be joined in the background. * @param ownMembershipIdentity the identity of the user and device joining the session. * This will be put into the content.member. * @param publishedTransports the list of transports on which the member is publishing. * @param joinConfig - Additional configuration for the joined session. */ public join( ownMembershipIdentity: CallMembershipIdentityParts, publishedTransports: Transport[], joinConfig?: JoinSessionConfig, ): void { if (this.isJoined()) { this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`); return; } else { // Create MembershipManager and pass the RTCSession logger (with room id info) this.membershipManager = joinConfig?.unstableSendStickyEvents ? new StickyEventMembershipManager( joinConfig, this.roomSubset, this.client, this.slotDescription, ownMembershipIdentity.memberId, this.logger, ) : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger); this.reEmitter.reEmit(this.membershipManager, [ MembershipManagerEvent.ProbablyLeft, MembershipManagerEvent.StatusChanged, MembershipManagerEvent.DelayIdChanged, ]); // Create Encryption manager const [room, client, statistics] = [this.roomSubset, this.client, this.statistics]; const transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, client, statistics); this.encryptionManager = new RTCEncryptionManager( ownMembershipIdentity, () => this.memberships, transport, ( keyBin: Uint8Array, encryptionKeyIndex: number, membership: CallMembershipIdentityParts, backendIdentity: string, ) => { this.emit( MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, membership, backendIdentity, ); }, this.logger, ); } this.joinConfig = joinConfig; this.pendingNotificationToSend = this.joinConfig?.notificationType; // Join! this.membershipManager.join(publishedTransports, (e) => { this.logger.error("MembershipManager encountered an unrecoverable error: ", e); this.emit(MatrixRTCSessionEvent.MembershipManagerError, e); this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined()); }); this.encryptionManager.join(joinConfig, publishedTransports); this.emit(MatrixRTCSessionEvent.JoinStateChanged, true); } /** * Announces this user and device as having left the MatrixRTC session * and stops scheduled updates. * The membership update required to leave the session will retry if it fails. * Without network connection the promise will never resolve. * A timeout can be provided so that there is a guarantee for the promise to resolve. * @returns Whether the membership update was attempted and did not time out. */ public async leave(timeout?: number): Promise { if (!this.isJoined()) { this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`); return false; } this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`); this.encryptionManager!.leave(); const leavePromise = this.membershipManager!.leave(timeout); this.emit(MatrixRTCSessionEvent.JoinStateChanged, false); return await leavePromise; } /** * Get the call intent for the current call, based on what members are advertising. If one or more * members disagree on the current call intent, or nobody specifies one then `undefined` is returned. * * If all members that specify a call intent agree, that value is returned. * * This method uses the stable intent identifiers (`m.audio`, `m.video`). * * @returns A call intent, or `undefined` if no consensus or not given. * * @experimental Part of [MSC4196](https://github.com/matrix-org/matrix-spec-proposals/pull/4196). */ public getConsensusIntent(): RTCCallIntent | undefined { const firstIntent = this.memberships.find((m) => !!m.intent)?.intent; if (!firstIntent) { return undefined; } if (this.memberships.every((m) => !m.intent || m.intent === firstIntent)) { return firstIntent; } return undefined; } /** * Update the intent we advertise for the call (see {@link SessionConfig.callIntent}), re-sending our * membership if it changed. */ public async updateCallIntent(callIntent: RTCCallIntent): Promise { const myMembership = this.membershipManager?.ownMembership; if (!myMembership) { throw Error("Not connected yet"); } await this.membershipManager?.updateCallIntent(callIntent); } /** * Replace the application-specific data in our membership (see * {@link SessionConfig.applicationData}), re-sending it if it changed. */ public async updateApplicationData(applicationData: Record): Promise { const myMembership = this.membershipManager?.ownMembership; if (!myMembership) { throw Error("Not connected yet"); } await this.membershipManager?.updateApplicationData(applicationData); } /** * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export * the keys. */ public reemitEncryptionKeys(): void { this.encryptionManager?.getEncryptionKeys().forEach((keyRing, key) => { keyRing.forEach((keyInfo) => { this.emit( MatrixRTCSessionEvent.EncryptionKeyChanged, keyInfo.key, keyInfo.keyIndex, keyInfo.membership, keyInfo.backendIdentity, ); }); }); } /** * Sets a timer for the soonest membership expiry */ private setExpiryTimer(): void { if (this.expiryTimeout) { clearTimeout(this.expiryTimeout); this.expiryTimeout = undefined; } let soonestExpiry; for (const membership of this.memberships) { const thisExpiry = membership.getMsUntilExpiry(); // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires // but will be reliably resent on disconnect. if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) { soonestExpiry = thisExpiry; } } if (soonestExpiry != undefined) { this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry); } } /** * Sends notification events to indiciate the call has started. * Note: This does not return a promise, instead scheduling the notification events to be sent. * @param parentEventId Event id linking to your RTC call membership event. * @param notificationType The type of notification to send * @param callIntent The type of call this is. */ private sendCallNotify(parentEventId: string, notificationType: RTCNotificationType, intent?: RTCCallIntent): void { const lifetime = this.joinConfig?.notificationLifetimeMs ?? 90_000; const slotId = computeSlotId(this.slotDescription); const sendNotificationEvent = async (): Promise<{ response: ISendEventResponse; content: IRTCNotificationContent; }> => { const content: IRTCNotificationContent = { "slot_id": slotId, "m.mentions": { user_ids: [], room: true }, "notification_type": notificationType, "m.relates_to": { event_id: parentEventId, rel_type: RelationType.Reference, }, "sender_ts": Date.now(), "lifetime": lifetime, "msc4354_sticky_key": slotId, }; if (intent) { // Only include the unstable intent property here. The notification event itself // is still unstable. const callIntent = toUnstableCallIntent(intent); content["m.call.intent"] = callIntent; } return { response: await this.sendNotificationEvent(content), content }; }; void sendNotificationEvent() .then((notification) => { // Join event_id and origin event content const newResult = { ...notification.response, ...notification.content }; this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult); }) .catch((error) => this.logger.error("Failed to send call notification", error)); } /** * Sends a notification event, as a sticky event (MSC4354) where the server supports it. */ private async sendNotificationEvent(content: IRTCNotificationContent): Promise { const roomId = this.roomSubset.roomId; try { // Stay sticky slightly longer than the lifetime, since the server measures the sticky duration // from `origin_server_ts` while receivers measure the lifetime from `sender_ts`. const stickyDurationMs = content.lifetime + RTC_NOTIFICATION_MAX_SENDER_TS_AHEAD_MS; return await this.client._unstable_sendStickyEvent( roomId, stickyDurationMs, null, EventType.RTCNotification, content, ); } catch (error) { if (!(error instanceof UnsupportedStickyEventsEndpointError)) throw error; this.logger.debug("Server does not support sticky events, sending notification as a regular event"); return await this.client.sendEvent(roomId, EventType.RTCNotification, content); } } /** * Call this when the Matrix room members have changed. */ private readonly onRoomMemberUpdate = (): void => { void this.ensureRecalculateSessionMembers(); }; /** * Call this when a room state event has been updated. */ private readonly onRoomStateEvent = (event: MatrixEvent): void => { if (event.getType() === EventType.GroupCallMemberPrefix) { // A (legacy) call membership state event: any of them can change our memberships. void this.ensureRecalculateSessionMembers(); } else if ( event.getType() === EventType.RTCSlot && event.getStateKey() === computeSlotId(this.slotDescription) ) { void this.ensureRecalculateSessionMembers(); } }; /** * Call this when a sticky event update has occured. */ private readonly onStickyEventUpdate: RoomStickyEventsMap[RoomStickyEventsEvent.Update] = ( added, updated, removed, ): void => { if ( [...added, ...removed, ...updated.flatMap((v) => [v.current, v.previous])].some( (e) => e.getType() === EventType.RTCMembership, ) ) { void this.ensureRecalculateSessionMembers(); } }; // Recalculations are chained onto this promise, so they never run in parallel. private recalculateSessionMembersPromise: Promise = Promise.resolve(); /** * Ensures that membership is recalculated when the state of the session may have changed. * Also ensures that only one recalculation is made at a time. * @returns A promise resolving when the state has been recalculated. */ public ensureRecalculateSessionMembers(): Promise { if (this.membershipNeedsRecalculation) { // We have already requested recalcuation, don't attempt a new one. return this.recalculateSessionMembersPromise; } this.membershipNeedsRecalculation = true; // Chain the recalculation. this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.then( () => this.recalculateSessionMembers(), () => this.recalculateSessionMembers(), ); return this.recalculateSessionMembersPromise; } /** * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members. * * Examines the latest call memberships and handles any encryption key sending or rotation that is needed. * * This function should be called when the room members or call memberships might have changed. */ private readonly recalculateSessionMembers = async (): Promise => { // Clear the flag. this.membershipNeedsRecalculation = false; const oldMemberships = this.memberships; // Needs to be computed before `this.memberships` is updated below, since it is derived from it. const wasKeyRotationSuppressed = this.isKeyRotationSuppressed; this.memberships = await MatrixRTCSession.sessionMembershipsForSlot( this.room, this.slotDescription, this.calculateMembershipsOpts, ); const changed = oldMemberships.length != this.memberships.length || oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i])); if (changed) { this.logger.info( `Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`, ); logDurationSync(this.logger, "emit MatrixRTCSessionEvent.MembershipsChanged", () => { this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships); }); void this.membershipManager?.onRTCSessionMemberUpdate(this.memberships); // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`. const ownMembership = this.membershipManager?.ownMembership; if (this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) { // If we're the first member in the call, we're responsible for // sending the notification event if (ownMembership.eventId && this.joinConfig?.notificationType) { this.sendCallNotify(ownMembership.eventId, this.joinConfig.notificationType, ownMembership.intent); } else { this.logger.warn("Own membership eventId is undefined, cannot send call notification"); } } // If anyone else joins the session it is no longer our responsibility to send the notification. // (If we were the joiner we already did sent the notification in the block above.) if (this.memberships.length > 0) this.pendingNotificationToSend = undefined; } else { this.logger.debug(`No membership changes detected for room ${this.roomSubset.roomId}`); } // This also needs to be done if `changed` = false // A member might have updated their fingerprint (created_ts) this.encryptionManager?.onMembershipsUpdate(oldMemberships); if (this.isKeyRotationSuppressed !== wasKeyRotationSuppressed) { this.logger.info( `Key rotation is now ${this.isKeyRotationSuppressed ? "suppressed" : "active again"} (${this.memberships.length} members)`, ); this.emit(MatrixRTCSessionEvent.KeyRotationSuppressedChanged, this.isKeyRotationSuppressed); } this.setExpiryTimer(); }; } /// Private helpers async function computeBackendIdentityAndVerifyMemberEvents( room: Pick, callMemberEvents: MatrixEvent[], slotDescription: SlotDescription, logger: Logger, ): Promise { const callMemberships: CallMembership[] = []; for (const memberEvent of callMemberEvents) { const content = memberEvent.getContent(); // Quick filter to avoid unneeded processing of invalid events or left events. if (!quickFilterNonRelevantContents(content)) { continue; } try { const membership = await CallMembership.parseFromEvent(memberEvent); if (isValidMembership(membership, room, slotDescription, logger)) { callMemberships.push(membership); } } catch (e) { logger.warn("Couldn't construct call membership: ", e); } } return callMemberships; } function quickFilterNonRelevantContents(content: IContent): boolean { // Don't even bother about left memberships (saves us from costly type/"key in" checks in bigger rooms) if (isLeftMembershipContent(content)) return false; // Ignore sticky keys for the count const eventKeysCount = Object.keys(content).filter((k) => k !== "msc4354_sticky_key").length; // We first decide if it's a MSC4143 event (per device state key) if (eventKeysCount > 1 && "application" in content) { // We have a MSC4143 event membership event with a proper joined content return true; } else if (eventKeysCount === 1 && "memberships" in content) { // Events used to have this format in the past, but are now deprecated. // Given that state events ~cannot be deleted, there can be some remaining events in the room, just ignore them. return false; } else { // Invalid or left content return false; } } function isValidMembership( membership: CallMembership, room: Pick, slotDescription: SlotDescription, logger: Logger, ): boolean { if (membership.slotDescription.id !== slotDescription.id) { logger.info( `Ignoring membership of user ${membership.userId} for a different slot. Theirs: ${JSON.stringify(membership.slotDescription)}, Expected: ${JSON.stringify(slotDescription)}`, ); return false; } if (membership.isExpired()) { logger.info(`Ignoring expired device membership ${membership.userId}/${membership.deviceId}`); return false; } if (!room.hasMembershipState(membership.userId ?? "", KnownMembership.Join)) { logger.info(`Ignoring membership of user ${membership.userId} who is not in the room.`); return false; } return true; } /** * Collects the raw member events from room state and sticky store. */ function collectMembersEvents( room: Pick, slotDescription: SlotDescription, options: SessionMembershipsForSlotOpts, logger: Logger, ): MatrixEvent[] { const { listenForStickyEvents, listenForMemberStateEvents } = options; let callMemberEvents: MatrixEvent[] = []; if (listenForStickyEvents && !isSlotClosed(room, slotDescription)) { // prefill with sticky events callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership); } if (listenForMemberStateEvents) { const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS); if (!roomState) { logger.warn("Couldn't get state for room " + room.roomId + "using empty membership array"); return []; } const callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix); callMemberEvents = callMemberEvents.concat( callMemberStateEvents.filter( (callMemberStateEvent) => !callMemberEvents.some( // only care about state events which have keys which we have not yet seen in the sticky events. // TODO: I believe this can discard a joined state event if there is a matching left sticky event. (stickyEvent) => stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey(), ), ), ); } return callMemberEvents; }