matrix-js-sdk 42.3.0 → 42.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/lib/@types/json.d.ts.map +1 -1
  3. package/lib/@types/json.js.map +1 -1
  4. package/lib/client.d.ts +74 -5
  5. package/lib/client.d.ts.map +1 -1
  6. package/lib/client.js +83 -7
  7. package/lib/client.js.map +1 -1
  8. package/lib/common-crypto/CryptoBackend.d.ts +42 -23
  9. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +7 -0
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/embedded.d.ts +35 -1
  13. package/lib/embedded.d.ts.map +1 -1
  14. package/lib/embedded.js +49 -1
  15. package/lib/embedded.js.map +1 -1
  16. package/lib/http-api/fetch.d.ts +0 -1
  17. package/lib/http-api/fetch.d.ts.map +1 -1
  18. package/lib/http-api/fetch.js +3 -22
  19. package/lib/http-api/fetch.js.map +1 -1
  20. package/lib/http-api/logging.d.ts +10 -0
  21. package/lib/http-api/logging.d.ts.map +1 -0
  22. package/lib/http-api/logging.js +46 -0
  23. package/lib/http-api/logging.js.map +1 -0
  24. package/lib/matrixrtc/EncryptionManager.d.ts +5 -0
  25. package/lib/matrixrtc/EncryptionManager.d.ts.map +1 -1
  26. package/lib/matrixrtc/EncryptionManager.js.map +1 -1
  27. package/lib/matrixrtc/LivekitTransport.d.ts +82 -0
  28. package/lib/matrixrtc/LivekitTransport.d.ts.map +1 -1
  29. package/lib/matrixrtc/LivekitTransport.js +25 -0
  30. package/lib/matrixrtc/LivekitTransport.js.map +1 -1
  31. package/lib/matrixrtc/MatrixRTCSession.d.ts +41 -2
  32. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  33. package/lib/matrixrtc/MatrixRTCSession.js +59 -1
  34. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  35. package/lib/matrixrtc/MembershipManager.js +7 -4
  36. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  37. package/lib/matrixrtc/RTCEncryptionManager.d.ts +17 -0
  38. package/lib/matrixrtc/RTCEncryptionManager.d.ts.map +1 -1
  39. package/lib/matrixrtc/RTCEncryptionManager.js +68 -29
  40. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  41. package/lib/models/room-receipts.d.ts +9 -3
  42. package/lib/models/room-receipts.d.ts.map +1 -1
  43. package/lib/models/room-receipts.js +51 -11
  44. package/lib/models/room-receipts.js.map +1 -1
  45. package/lib/oauth/authorize.d.ts +7 -2
  46. package/lib/oauth/authorize.d.ts.map +1 -1
  47. package/lib/oauth/authorize.js +10 -4
  48. package/lib/oauth/authorize.js.map +1 -1
  49. package/lib/oauth/fetch.d.ts +17 -0
  50. package/lib/oauth/fetch.d.ts.map +1 -0
  51. package/lib/oauth/fetch.js +47 -0
  52. package/lib/oauth/fetch.js.map +1 -0
  53. package/lib/oauth/index.d.ts +15 -2
  54. package/lib/oauth/index.d.ts.map +1 -1
  55. package/lib/oauth/index.js +33 -12
  56. package/lib/oauth/index.js.map +1 -1
  57. package/lib/rust-crypto/index.d.ts +17 -0
  58. package/lib/rust-crypto/index.d.ts.map +1 -1
  59. package/lib/rust-crypto/index.js +4 -2
  60. package/lib/rust-crypto/index.js.map +1 -1
  61. package/lib/rust-crypto/rust-crypto.d.ts +6 -26
  62. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  63. package/lib/rust-crypto/rust-crypto.js +19 -54
  64. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  65. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  66. package/lib/sliding-sync-sdk.js +65 -27
  67. package/lib/sliding-sync-sdk.js.map +1 -1
  68. package/lib/sliding-sync.d.ts +17 -0
  69. package/lib/sliding-sync.d.ts.map +1 -1
  70. package/lib/sliding-sync.js +21 -9
  71. package/lib/sliding-sync.js.map +1 -1
  72. package/lib/sync.d.ts +9 -1
  73. package/lib/sync.d.ts.map +1 -1
  74. package/lib/sync.js +54 -29
  75. package/lib/sync.js.map +1 -1
  76. package/package.json +5 -5
  77. package/src/@types/json.ts +11 -2
  78. package/src/client.ts +126 -11
  79. package/src/common-crypto/CryptoBackend.ts +45 -23
  80. package/src/embedded.ts +67 -4
  81. package/src/http-api/fetch.ts +2 -23
  82. package/src/http-api/logging.ts +46 -0
  83. package/src/matrixrtc/EncryptionManager.ts +6 -0
  84. package/src/matrixrtc/LivekitTransport.ts +86 -0
  85. package/src/matrixrtc/MatrixRTCSession.ts +81 -1
  86. package/src/matrixrtc/MembershipManager.ts +7 -7
  87. package/src/matrixrtc/RTCEncryptionManager.ts +80 -31
  88. package/src/models/room-receipts.ts +54 -10
  89. package/src/oauth/authorize.ts +10 -2
  90. package/src/oauth/fetch.ts +54 -0
  91. package/src/oauth/index.ts +29 -10
  92. package/src/rust-crypto/index.ts +23 -0
  93. package/src/rust-crypto/rust-crypto.ts +25 -67
  94. package/src/sliding-sync-sdk.ts +73 -33
  95. package/src/sliding-sync.ts +31 -14
  96. package/src/sync.ts +58 -35
@@ -1 +1 @@
1
- {"version":3,"file":"MatrixRTCSession.js","names":[],"sources":["../../src/matrixrtc/MatrixRTCSession.ts"],"sourcesContent":["/*\nCopyright 2023 - 2026 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger, logger as rootLogger } from \"../logger.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { EventTimeline } from \"../models/event-timeline.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { EventType, RelationType } from \"../@types/event.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\nimport { type ISendEventResponse } from \"../@types/requests.ts\";\nimport { CallMembership } from \"./CallMembership.ts\";\nimport { RoomStateEvent } from \"../models/room-state.ts\";\nimport { MembershipManager, StickyEventMembershipManager } from \"./MembershipManager.ts\";\nimport { type CallMembershipIdentityParts, type IEncryptionManager } from \"./EncryptionManager.ts\";\nimport { logDurationSync } from \"../utils.ts\";\nimport type {\n Statistics,\n RTCNotificationType,\n Status,\n IRTCNotificationContent,\n RTCCallIntent,\n Transport,\n SlotDescription,\n RtcSlotEventContent,\n} from \"./types.ts\";\nimport {\n MembershipManagerEvent,\n type MembershipManagerEventHandlerMap,\n type IMembershipManager,\n} from \"./IMembershipManager.ts\";\nimport { RTCEncryptionManager } from \"./RTCEncryptionManager.ts\";\nimport { ToDeviceKeyTransport } from \"./ToDeviceKeyTransport.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { type IContent, type MatrixEvent } from \"../models/event.ts\";\nimport { RoomStickyEventsEvent, type RoomStickyEventsMap } from \"../models/room-sticky-events.ts\";\nimport { computeSlotId } from \"./utils.ts\";\n\n/**\n * Events emitted by MatrixRTCSession\n */\nexport enum MatrixRTCSessionEvent {\n // A member joined, left, or updated a property of their membership.\n MembershipsChanged = \"memberships_changed\",\n // We joined or left the session: our own local idea of whether we are joined,\n // separate from MembershipsChanged, ie. independent of whether our member event\n // has successfully gone through.\n JoinStateChanged = \"join_state_changed\",\n // The key used to encrypt media has changed\n EncryptionKeyChanged = \"encryption_key_changed\",\n /** The membership manager had to shut down caused by an unrecoverable error */\n MembershipManagerError = \"membership_manager_error\",\n /** The RTCSession did send a call notification caused by joining the call as the first member */\n DidSendCallNotification = \"did_send_call_notification\",\n}\n\nexport type MatrixRTCSessionEventHandlerMap = {\n [MatrixRTCSessionEvent.MembershipsChanged]: (\n oldMemberships: CallMembership[],\n newMemberships: CallMembership[],\n ) => void;\n [MatrixRTCSessionEvent.JoinStateChanged]: (isJoined: boolean) => void;\n [MatrixRTCSessionEvent.EncryptionKeyChanged]: (\n key: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => void;\n [MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void;\n [MatrixRTCSessionEvent.DidSendCallNotification]: (\n notificationContentNew: { event_id: string } & IRTCNotificationContent,\n ) => void;\n};\n\nexport interface SessionConfig {\n /**\n * What kind of notification to send when starting the session.\n * @default `undefined` (no notification)\n */\n notificationType?: RTCNotificationType;\n\n /**\n * Determines the kind of call this will be.\n */\n callIntent?: RTCCallIntent;\n\n /**\n * How long (in milliseconds) the callee's client should keep ringing/waiting for an\n * answer before the sender gives up and the call notification is considered timed out.\n */\n notificationLifetimeMs?: number;\n}\n\n// The names follow these principles:\n// - we use the technical term delay if the option is related to delayed events.\n// - we use delayedLeaveEvent if the option is related to the delayed leave event.\n// - we use membershipEvent if the option is related to the rtc member state event.\n// - we use the technical term expiry if the option is related to the expiry field of the membership state event.\n// - we use a `Ms` postfix if the option is a duration to avoid using words like:\n// `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms.\nexport interface MembershipConfig {\n /**\n * The timeout (in milliseconds) after we joined the call, that our membership should expire\n * unless we have explicitly updated it.\n *\n * This is what goes into the m.rtc.member event expiry field and is typically set to a number of hours.\n */\n membershipEventExpiryMs?: number;\n\n /**\n * The time in (in milliseconds) which the manager will prematurely send the updated state event before the membership `expires` time to make sure it\n * sends the updated state event early enough.\n *\n * A headroom of 1000ms and a `membershipExpiryTimeout` of 10000ms would result in the first membership event update after 9s and\n * a membership event that would be considered expired after 10s.\n *\n * This value does not have an effect on the value of `SessionMembershipData.expires`.\n */\n membershipEventExpiryHeadroomMs?: number;\n\n /**\n * The timeout (in milliseconds) with which the deleayed leave event on the server is configured.\n * After this time the server will set the event to the disconnected stat if it has not received a keep-alive from the client.\n */\n delayedLeaveEventDelayMs?: number;\n\n /**\n * The interval (in milliseconds) in which the client will send membership keep-alives to the server.\n */\n delayedLeaveEventRestartMs?: number;\n\n /**\n * 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.\n */\n maximumRateLimitRetryCount?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a network error occurs.\n */\n maximumNetworkErrorRetryCount?: number;\n\n /**\n * The time (in milliseconds) after which we will retry a http request if it\n * failed to send due to a network error. (send membership event, send delayed event, restart delayed event...)\n */\n networkErrorRetryMs?: number;\n\n /**\n * The time (in milliseconds) after which a we consider a delayed event restart http request to have failed.\n * Setting this to a lower value will result in more frequent retries but also a higher chance of failiour.\n *\n * In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs\n * helps by keeping more delayed event reset candidates in flight,\n * improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,\n * but only applies to calls to the `_unstable_restartScheduledDelayedEvent` endpoint\n * or the `_unstable_updateDelayedEvent` endpoint with a body of `{action:\"restart\"}`.)\n */\n delayedLeaveEventRestartLocalTimeoutMs?: number;\n\n /**\n * Send membership using sticky events rather than state events.\n * This also make the client use the new m.rtc.member MSC4354 event format. (instead of m.call.member)\n *\n * **WARNING**: This is an unstable feature and not all clients will support it.\n */\n unstableSendStickyEvents?: boolean;\n}\n\nexport interface EncryptionConfig {\n /**\n * If true, generate and share a media key for this participant,\n * and emit MatrixRTCSessionEvent.EncryptionKeyChanged when\n * media keys for other participants become available.\n */\n manageMediaKeys?: boolean;\n /**\n * The minimum time (in milliseconds) between each attempt to send encryption key(s).\n * e.g. if this is set to 1000, then we will send at most one key event every second.\n * @deprecated - Not used by the new encryption manager.\n */\n updateEncryptionKeyThrottle?: number;\n\n /**\n * Sometimes it is necessary to rotate the encryption key after a membership update.\n * For performance reasons we might not want to rotate the key immediately but allow future memberships to use the same key.\n * If 5 people join in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * If 5 people leave in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * So we do share the key which was already used live for <5s to new joiners.\n * This does result in a potential leak up to the configured time of call media.\n * This has to be considered when choosing a value for this property.\n */\n keyRotationGracePeriodMs?: number;\n\n /**\n * The delay (in milliseconds) after a member leaves before we create and publish a new key, because people\n * tend to leave calls at the same time.\n * @deprecated - Not used by the new encryption manager.\n */\n makeKeyDelay?: number;\n /**\n * The delay (in milliseconds) between sending a new key and starting to encrypt with it. This\n * gives others a chance to receive the new key to minimize the chance they get media they can't decrypt.\n *\n * The higher this value is, the better it is for existing members as they will have a smoother experience.\n * But it impacts new joiners: They will always have to wait `useKeyDelay` before being able to decrypt the media\n * (as it will be encrypted with the new key after the delay only), even if the key has already arrived before the delay.\n */\n useKeyDelay?: number;\n}\nexport type JoinSessionConfig = SessionConfig & MembershipConfig & EncryptionConfig;\n\ninterface SessionMembershipsForSlotOpts {\n /**\n * Listen for incoming sticky member events. If disabled, this session will\n * ignore any incoming sticky events.\n */\n listenForStickyEvents: boolean;\n /**\n * Listen for incoming member state events (legacy). If disabled, this session will\n * ignore any incoming state events.\n */\n listenForMemberStateEvents: boolean;\n}\n\nconst DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS: SessionMembershipsForSlotOpts = {\n listenForStickyEvents: true,\n listenForMemberStateEvents: true,\n};\n\n/**\n * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.\n * This class doesn't deal with media at all, just membership & properties of a session.\n */\nexport class MatrixRTCSession extends TypedEventEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n> {\n private membershipManager?: IMembershipManager;\n private encryptionManager?: IEncryptionManager;\n private joinConfig?: SessionConfig;\n private logger: Logger;\n\n private pendingNotificationToSend: undefined | RTCNotificationType;\n /**\n * This timeout is responsible to track any expiration. We need to know when we have to start\n * to ignore other call members. There is no callback for this. This timeout will always be configured to\n * emit when the next membership expires.\n */\n private expiryTimeout?: ReturnType<typeof setTimeout>;\n\n public memberships: CallMembership[] = [];\n\n /**\n * Resolves when the session has calculated the initial membership of the session.\n */\n public readonly initialMembershipCalculated: Promise<void>;\n /**\n * Does membership need to be recalculated? This is set to false upon\n * recalculation.\n */\n private membershipNeedsRecalculation = false;\n\n /**\n * The statistics for this session.\n */\n public statistics: Statistics = {\n counters: {\n roomEventEncryptionKeysSent: 0,\n roomEventEncryptionKeysReceived: 0,\n },\n totals: {\n roomEventEncryptionKeysReceivedTotalAge: 0,\n },\n };\n\n public get membershipStatus(): Status | undefined {\n return this.membershipManager?.status;\n }\n public get probablyLeft(): boolean | undefined {\n return this.membershipManager?.probablyLeft;\n }\n public get delayId(): string | undefined {\n return this.membershipManager?.delayId;\n }\n\n /**\n * The callId (sessionId) of the call.\n *\n * It can be undefined since the callId is only known once the first membership joins.\n * The callId is the property that, per definition, groups memberships into one call.\n * @deprecated use `slotId` instead.\n */\n public get callId(): string | undefined {\n return this.slotDescription?.id;\n }\n /**\n * The slotId of the call.\n * `{application}#{appSpecificId}`\n * It can be undefined since the slotId is only known once the first membership joins.\n * The slotId is the property that, per definition, groups memberships into one call.\n */\n public get slotId(): string | undefined {\n return computeSlotId(this.slotDescription);\n }\n\n /**\n * Reads the current slot state event's content for this session.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for this session.\n */\n public getRtcSlot(): RtcSlotEventContent | undefined {\n return getSlotEventContent(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Whether this session's slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\n public isSlotClosed(): boolean | undefined {\n return isSlotClosed(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Returns all the call memberships for a room that match the provided `sessionDescription`,\n * oldest first.\n *\n * By default, this will return *both* sticky and member state events.\n */\n public static async sessionMembershipsForSlot(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"hasMembershipState\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n // default both true this implied we combine sticky and state events for the final call state\n // (prefer sticky events in case of a duplicate)\n options: SessionMembershipsForSlotOpts = DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS,\n ): Promise<CallMembership[]> {\n const logger = rootLogger.getChild(\n `[MatrixRTCSession ${room.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n const callMemberEvents = collectMembersEvents(room, slotDescription, options, logger);\n\n const callMemberships = await computeBackendIdentityAndVerifyMemberEvents(\n room,\n callMemberEvents,\n slotDescription,\n logger,\n );\n\n callMemberships.sort((a, b) => a.createdTs() - b.createdTs());\n if (callMemberships.length > 1) {\n logger.debug(\n `Call memberships in room ${room.roomId}, in order: `,\n callMemberships.map((m) => [m.createdTs(), m.userId]),\n );\n }\n\n return callMemberships;\n }\n\n /**\n * Return the MatrixRTC session for the room.\n * This returned session can be used to find out if there are active sessions\n * for the requested room and `slotDescription`.\n */\n public static sessionForSlot(\n client: MatrixClient,\n room: Room,\n slotDescription: SlotDescription,\n opts?: SessionMembershipsForSlotOpts,\n ): MatrixRTCSession {\n return new MatrixRTCSession(client, room, slotDescription, opts);\n }\n\n /**\n * WARN: this can in theory only be a subset of the room with the properties required by\n * this class.\n * Outside of tests this most likely will be a full room, however.\n * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking\n * the room object in your own code and passing it in when needed.\n */\n public get room(): Room {\n return this.roomSubset as Room;\n }\n\n /**\n * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected\n * to be used with the MatrixRTCSessionManager exclusively.\n *\n * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone\n * to manage a joined MatrixRTC session.\n *\n * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.\n * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.\n * @param slotDescription The slot description is a virtual address where participants are allowed to meet.\n * This session will only manage memberships that match this slot description.Sessions are distinct if any of\n * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.\n * @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session.\n */\n public constructor(\n private readonly client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendEvent\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n | \"_unstable_cancelScheduledDelayedEvent\"\n | \"_unstable_restartScheduledDelayedEvent\"\n | \"_unstable_sendScheduledDelayedEvent\"\n | \"_unstable_sendStickyEvent\"\n | \"_unstable_sendStickyDelayedEvent\"\n | \"cancelPendingEvent\"\n | \"encryptAndSendToDevice\"\n | \"off\"\n | \"on\"\n | \"decryptEventIfNeeded\"\n >,\n private roomSubset: Pick<\n Room,\n | \"getLiveTimeline\"\n | \"roomId\"\n | \"getVersion\"\n | \"hasMembershipState\"\n | \"on\"\n | \"off\"\n | \"_unstable_getStickyEvents\"\n >,\n\n public readonly slotDescription: SlotDescription,\n private readonly calculateMembershipsOpts?: SessionMembershipsForSlotOpts,\n ) {\n super();\n this.logger = rootLogger.getChild(\n `[MatrixRTCSession ${roomSubset.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n\n this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.on(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n\n this.initialMembershipCalculated = this.ensureRecalculateSessionMembers();\n this.setExpiryTimer();\n }\n /*\n * Returns true if we intend to be participating in the MatrixRTC session.\n * This is determined by checking if the relativeExpiry has been set.\n */\n public isJoined(): boolean {\n return this.membershipManager?.isJoined() ?? false;\n }\n\n /**\n * Performs cleanup & removes timers for client shutdown\n */\n public async stop(): Promise<void> {\n await this.membershipManager?.leave(1000);\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n this.roomSubset.off(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.off(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.off(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n }\n\n private reEmitter = new TypedReEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n >(this);\n\n /**\n * Announces this user and device as joined to the MatrixRTC session,\n * and continues to update the membership event to keep it valid until\n * leaveRoomSession() is called\n * This will not subscribe to updates: remember to call subscribe() separately if\n * desired.\n * This method will return immediately and the session will be joined in the background.\n * @param ownMembershipIdentity the identity of the user and device joining the session.\n * This will be put into the content.member.\n * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n * transport selection will be used instead.\n * @param joinConfig - Additional configuration for the joined session.\n */\n public joinRTCSession(\n ownMembershipIdentity: CallMembershipIdentityParts,\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n if (this.isJoined()) {\n this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);\n return;\n } else {\n // Create MembershipManager and pass the RTCSession logger (with room id info)\n this.membershipManager = joinConfig?.unstableSendStickyEvents\n ? new StickyEventMembershipManager(\n joinConfig,\n this.roomSubset,\n this.client,\n this.slotDescription,\n ownMembershipIdentity.memberId,\n this.logger,\n )\n : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);\n\n this.reEmitter.reEmit(this.membershipManager, [\n MembershipManagerEvent.ProbablyLeft,\n MembershipManagerEvent.StatusChanged,\n MembershipManagerEvent.DelayIdChanged,\n ]);\n // Create Encryption manager\n const [room, client, statistics] = [this.roomSubset, this.client, this.statistics];\n const transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, client, statistics);\n this.encryptionManager = new RTCEncryptionManager(\n ownMembershipIdentity,\n () => this.memberships,\n transport,\n (\n keyBin: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyBin,\n encryptionKeyIndex,\n membership,\n rtcBackendIdentity,\n );\n },\n this.logger,\n );\n }\n\n this.joinConfig = joinConfig;\n this.pendingNotificationToSend = this.joinConfig?.notificationType;\n\n // Join!\n this.membershipManager.join(fociPreferred, multiSfuFocus, (e) => {\n this.logger.error(\"MembershipManager encountered an unrecoverable error: \", e);\n this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());\n });\n this.encryptionManager.join(joinConfig);\n\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);\n }\n\n /**\n *\n * @param fociPreferred\n * @param multiSfuFocus\n * @param joinConfig\n * @deprecated use the joinRTCSession method instead\n */\n public joinRoomSession(\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n const [userId, deviceId] = [this.client.getUserId()!, this.client.getDeviceId()!];\n // TODO this wants to become a UUID\n const memberId = `${userId}:${deviceId}`;\n this.joinRTCSession({ userId, deviceId, memberId }, fociPreferred, multiSfuFocus, joinConfig);\n }\n\n /**\n * Announces this user and device as having left the MatrixRTC session\n * and stops scheduled updates.\n * This will not unsubscribe from updates: remember to call unsubscribe() separately if\n * desired.\n * The membership update required to leave the session will retry if it fails.\n * Without network connection the promise will never resolve.\n * A timeout can be provided so that there is a guarantee for the promise to resolve.\n * @returns Whether the membership update was attempted and did not time out.\n */\n public async leaveRoomSession(timeout: number | undefined = undefined): Promise<boolean> {\n if (!this.isJoined()) {\n this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`);\n return false;\n }\n\n this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`);\n\n this.encryptionManager!.leave();\n\n const leavePromise = this.membershipManager!.leave(timeout);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, false);\n\n return await leavePromise;\n }\n /**\n * This returns the focus in use by the oldest membership.\n * Do not use since this might be just the focus for the oldest membership. others might use a different focus.\n * @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.\n */\n public getFocusInUse(): Transport | undefined {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getTransport(oldestMembership);\n }\n\n public getOldestMembership(): CallMembership | undefined {\n return this.memberships[0];\n }\n\n /**\n * Get the call intent for the current call, based on what members are advertising. If one or more\n * members disagree on the current call intent, or nobody specifies one then `undefined` is returned.\n *\n * If all members that specify a call intent agree, that value is returned.\n * @returns A call intent, or `undefined` if no consensus or not given.\n */\n public getConsensusCallIntent(): RTCCallIntent | undefined {\n const getFirstCallIntent = this.memberships.find((m) => !!m.callIntent)?.callIntent;\n if (!getFirstCallIntent) {\n return undefined;\n }\n if (this.memberships.every((m) => !m.callIntent || m.callIntent === getFirstCallIntent)) {\n return getFirstCallIntent;\n }\n return undefined;\n }\n\n public async updateCallIntent(callIntent: RTCCallIntent): Promise<void> {\n const myMembership = this.membershipManager?.ownMembership;\n if (!myMembership) {\n throw Error(\"Not connected yet\");\n }\n await this.membershipManager?.updateCallIntent(callIntent);\n }\n\n /**\n * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export\n * the keys.\n */\n public reemitEncryptionKeys(): void {\n this.encryptionManager?.getEncryptionKeys().forEach((keyRing, key) => {\n keyRing.forEach((keyInfo) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyInfo.key,\n keyInfo.keyIndex,\n keyInfo.membership,\n keyInfo.rtcBackendIdentity,\n );\n });\n });\n }\n\n /**\n * Sets a timer for the soonest membership expiry\n */\n private setExpiryTimer(): void {\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n let soonestExpiry;\n for (const membership of this.memberships) {\n const thisExpiry = membership.getMsUntilExpiry();\n // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires\n // but will be reliably resent on disconnect.\n if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {\n soonestExpiry = thisExpiry;\n }\n }\n\n if (soonestExpiry != undefined) {\n this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry);\n }\n }\n\n /**\n * Sends notification events to indiciate the call has started.\n * Note: This does not return a promise, instead scheduling the notification events to be sent.\n * @param parentEventId Event id linking to your RTC call membership event.\n * @param notificationType The type of notification to send\n * @param callIntent The type of call this is (e.g. \"audio\").\n */\n private sendCallNotify(\n parentEventId: string,\n notificationType: RTCNotificationType,\n callIntent?: RTCCallIntent,\n ): void {\n const lifetime = this.joinConfig?.notificationLifetimeMs ?? 90_000;\n const sendNotificationEvent = async (): Promise<{\n response: ISendEventResponse;\n content: IRTCNotificationContent;\n }> => {\n const content: IRTCNotificationContent = {\n \"m.mentions\": { user_ids: [], room: true },\n \"notification_type\": notificationType,\n \"m.relates_to\": {\n event_id: parentEventId,\n rel_type: RelationType.Reference,\n },\n \"sender_ts\": Date.now(),\n \"lifetime\": lifetime,\n };\n if (callIntent) {\n content[\"m.call.intent\"] = callIntent;\n }\n const response = await this.client.sendEvent(this.roomSubset.roomId, EventType.RTCNotification, content);\n return { response, content };\n };\n\n void sendNotificationEvent()\n .then((notification) => {\n // Join event_id and origin event content\n const newResult = { ...notification.response, ...notification.content };\n this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);\n })\n .catch(([errorLegacy, errorNew]) =>\n this.logger.error(\"Failed to send call notification\", errorLegacy, errorNew),\n );\n }\n\n /**\n * Call this when the Matrix room members have changed.\n */\n private readonly onRoomMemberUpdate = (): void => {\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a room state event has been updated.\n */\n private readonly onRoomStateEvent = (event: MatrixEvent): void => {\n if (event.getType() !== EventType.RTCSlot) return;\n if (event.getStateKey() !== computeSlotId(this.slotDescription)) return;\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a sticky event update has occured.\n */\n private readonly onStickyEventUpdate: RoomStickyEventsMap[RoomStickyEventsEvent.Update] = (\n added,\n updated,\n removed,\n ): void => {\n if (\n [...added, ...removed, ...updated.flatMap((v) => [v.current, v.previous])].some(\n (e) => e.getType() === EventType.RTCMembership,\n )\n ) {\n void this.ensureRecalculateSessionMembers();\n }\n };\n\n /**\n * Call this when something changed that may impacts the current MatrixRTC members in this session.\n */\n // We allow this name schema since this function should only be used for testing purposes.\n public _onRTCSessionMemberUpdate = async (): Promise<void> => {\n await this.recalculateSessionMembers();\n };\n\n // helper variables to make sure we do not have parallel running recalculations.\n private recalculateSessionMembersPromise: Promise<void> = Promise.resolve();\n\n /**\n * Ensures that membership is recalculated when the state of the session may have changed.\n * Also ensures that only one recalculation is made at a time.\n * @returns A promise resolving when the state has been recalculated.\n */\n private ensureRecalculateSessionMembers(): Promise<void> {\n if (this.membershipNeedsRecalculation) {\n // We have already requested recalcuation, don't attempt a new one.\n return this.recalculateSessionMembersPromise;\n }\n this.membershipNeedsRecalculation = true;\n // Chain the recalculation.\n this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.then(\n () => this.recalculateSessionMembers(),\n () => this.recalculateSessionMembers(),\n );\n return this.recalculateSessionMembersPromise;\n }\n\n /**\n * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.\n *\n * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.\n *\n * This function should be called when the room members or call memberships might have changed.\n */\n private readonly recalculateSessionMembers = async (): Promise<void> => {\n // Clear the flag.\n this.membershipNeedsRecalculation = false;\n const oldMemberships = this.memberships;\n\n this.memberships = await MatrixRTCSession.sessionMembershipsForSlot(\n this.room,\n this.slotDescription,\n this.calculateMembershipsOpts,\n );\n\n const changed =\n oldMemberships.length != this.memberships.length ||\n oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i]));\n\n if (changed) {\n this.logger.info(\n `Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`,\n );\n logDurationSync(this.logger, \"emit MatrixRTCSessionEvent.MembershipsChanged\", () => {\n this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships);\n });\n\n void this.membershipManager?.onRTCSessionMemberUpdate(this.memberships);\n // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`.\n const ownMembership = this.membershipManager?.ownMembership;\n if (this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {\n // If we're the first member in the call, we're responsible for\n // sending the notification event\n if (ownMembership.eventId && this.joinConfig?.notificationType) {\n this.sendCallNotify(\n ownMembership.eventId,\n this.joinConfig.notificationType,\n ownMembership.callIntent,\n );\n } else {\n this.logger.warn(\"Own membership eventId is undefined, cannot send call notification\");\n }\n }\n // If anyone else joins the session it is no longer our responsibility to send the notification.\n // (If we were the joiner we already did sent the notification in the block above.)\n if (this.memberships.length > 0) this.pendingNotificationToSend = undefined;\n } else {\n this.logger.debug(`No membership changes detected for room ${this.roomSubset.roomId}`);\n }\n // This also needs to be done if `changed` = false\n // A member might have updated their fingerprint (created_ts)\n this.encryptionManager?.onMembershipsUpdate(oldMemberships);\n\n this.setExpiryTimer();\n };\n}\n\n/// Private helpers\nasync function computeBackendIdentityAndVerifyMemberEvents(\n room: Pick<Room, \"hasMembershipState\">,\n callMemberEvents: MatrixEvent[],\n slotDescription: SlotDescription,\n logger: Logger,\n): Promise<CallMembership[]> {\n const callMemberships: CallMembership[] = [];\n\n for (const memberEvent of callMemberEvents) {\n const content = memberEvent.getContent();\n\n // Quick filter to avoid unneeded processing of invalid events or left events.\n if (!quickFilterNonRelevantContents(content, logger)) {\n continue;\n }\n\n try {\n const membership = await CallMembership.parseFromEvent(memberEvent);\n\n if (isValidMembership(membership, room, slotDescription, logger)) {\n callMemberships.push(membership);\n }\n } catch (e) {\n logger.warn(\"Couldn't construct call membership: \", e);\n }\n }\n\n return callMemberships;\n}\n\nfunction quickFilterNonRelevantContents(content: IContent, logger: Logger): boolean {\n // Ignore sticky keys for the count\n const eventKeysCount = Object.keys(content).filter((k) => k !== \"msc4354_sticky_key\").length;\n // Don't even bother about empty events (saves us from costly type/\"key in\" checks in bigger rooms)\n if (eventKeysCount === 0) return false;\n\n // We first decide if it's a MSC4143 event (per device state key)\n if (eventKeysCount > 1 && \"application\" in content) {\n // We have a MSC4143 event membership event with a proper joined content\n return true;\n } else if (eventKeysCount === 1 && \"memberships\" in content) {\n // Events used to have this format in the past, but are now deprecated.\n // Given that state events ~cannot be deleted, there can be some remaining events in the room, just ignore them.\n return false;\n } else {\n // Invalid or left content\n return false;\n }\n}\n\nfunction isValidMembership(\n membership: CallMembership,\n room: Pick<Room, \"hasMembershipState\">,\n slotDescription: SlotDescription,\n logger: Logger,\n): boolean {\n if (membership.slotDescription.id !== slotDescription.id) {\n logger.info(\n `Ignoring membership of user ${membership.userId} for a different slot. Theirs: ${JSON.stringify(membership.slotDescription)}, Expected: ${JSON.stringify(slotDescription)}`,\n );\n return false;\n }\n\n if (membership.isExpired()) {\n logger.info(`Ignoring expired device membership ${membership.userId}/${membership.deviceId}`);\n return false;\n }\n\n if (!room.hasMembershipState(membership.userId ?? \"\", KnownMembership.Join)) {\n logger.info(`Ignoring membership of user ${membership.userId} who is not in the room.`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Reads the slot state event's content for the given slot description.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for the given description.\n */\nfunction getSlotEventContent(\n room: Pick<Room, \"getLiveTimeline\">,\n slotDescription: SlotDescription,\n): RtcSlotEventContent | undefined {\n const slotId = computeSlotId(slotDescription);\n const slotEvent = room\n .getLiveTimeline()\n .getState(EventTimeline.FORWARDS)\n ?.getStateEvents(EventType.RTCSlot, slotId);\n if (!slotEvent) return undefined;\n\n return slotEvent.getContent<RtcSlotEventContent>();\n}\n\n/**\n * Whether the given slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\nfunction isSlotClosed(room: Pick<Room, \"getLiveTimeline\">, slotDescription: SlotDescription): boolean | undefined {\n const content = getSlotEventContent(room, slotDescription) as Partial<RtcSlotEventContent> | undefined;\n if (content === undefined) return undefined;\n\n return (\n content.status !== \"open\" ||\n typeof content.application !== \"object\" ||\n content.application?.type !== slotDescription.application\n );\n}\n\n/**\n * Collects the raw member events from room state and sticky store.\n */\nfunction collectMembersEvents(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n options: SessionMembershipsForSlotOpts,\n logger: Logger,\n): MatrixEvent[] {\n const { listenForStickyEvents, listenForMemberStateEvents } = options;\n let callMemberEvents: MatrixEvent[] = [];\n if (listenForStickyEvents && !isSlotClosed(room, slotDescription)) {\n // prefill with sticky events\n callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership);\n }\n if (listenForMemberStateEvents) {\n const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!roomState) {\n logger.warn(\"Couldn't get state for room \" + room.roomId + \"using empty membership array\");\n return [];\n }\n const callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);\n callMemberEvents = callMemberEvents.concat(\n callMemberStateEvents.filter(\n (callMemberStateEvent) =>\n !callMemberEvents.some(\n // only care about state events which have keys which we have not yet seen in the sticky events.\n // TODO: I believe this can discard a joined state event if there is a matching left sticky event.\n (stickyEvent) =>\n stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey(),\n ),\n ),\n );\n }\n return callMemberEvents;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsB,MAAM,IAAI,UAAU,QAAQ,cAAc;AAChE,SA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/*\nCopyright 2023 - 2026 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger, logger as rootLogger } from \"../logger.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { EventTimeline } from \"../models/event-timeline.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { EventType, RelationType } from \"../@types/event.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\nimport { type ISendEventResponse } from \"../@types/requests.ts\";\nimport { CallMembership } from \"./CallMembership.ts\";\nimport { RoomStateEvent } from \"../models/room-state.ts\";\nimport { MembershipManager, StickyEventMembershipManager } from \"./MembershipManager.ts\";\nimport { type CallMembershipIdentityParts, type IEncryptionManager } from \"./EncryptionManager.ts\";\nimport { deepCompare, logDurationSync } from \"../utils.ts\";\nimport type {\n Statistics,\n RTCNotificationType,\n Status,\n IRTCNotificationContent,\n RTCCallIntent,\n Transport,\n SlotDescription,\n RtcSlotEventContent,\n RtcSlotEncryptionContent,\n} from \"./types.ts\";\nimport {\n MembershipManagerEvent,\n type MembershipManagerEventHandlerMap,\n type IMembershipManager,\n} from \"./IMembershipManager.ts\";\nimport { RTCEncryptionManager } from \"./RTCEncryptionManager.ts\";\nimport { ToDeviceKeyTransport } from \"./ToDeviceKeyTransport.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { type IContent, type MatrixEvent } from \"../models/event.ts\";\nimport { RoomStickyEventsEvent, type RoomStickyEventsMap } from \"../models/room-sticky-events.ts\";\nimport { computeSlotId } from \"./utils.ts\";\n\n/**\n * Events emitted by MatrixRTCSession\n */\nexport enum MatrixRTCSessionEvent {\n // A member joined, left, or updated a property of their membership.\n MembershipsChanged = \"memberships_changed\",\n // We joined or left the session: our own local idea of whether we are joined,\n // separate from MembershipsChanged, ie. independent of whether our member event\n // has successfully gone through.\n JoinStateChanged = \"join_state_changed\",\n // The key used to encrypt media has changed\n EncryptionKeyChanged = \"encryption_key_changed\",\n /** The membership manager had to shut down caused by an unrecoverable error */\n MembershipManagerError = \"membership_manager_error\",\n /** The RTCSession did send a call notification caused by joining the call as the first member */\n DidSendCallNotification = \"did_send_call_notification\",\n /** Whether the session is too large for the media key to be rotated has changed */\n KeyRotationSuppressedChanged = \"key_rotation_suppressed_changed\",\n}\n\nexport type MatrixRTCSessionEventHandlerMap = {\n [MatrixRTCSessionEvent.MembershipsChanged]: (\n oldMemberships: CallMembership[],\n newMemberships: CallMembership[],\n ) => void;\n [MatrixRTCSessionEvent.JoinStateChanged]: (isJoined: boolean) => void;\n [MatrixRTCSessionEvent.EncryptionKeyChanged]: (\n key: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => void;\n [MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void;\n [MatrixRTCSessionEvent.DidSendCallNotification]: (\n notificationContentNew: { event_id: string } & IRTCNotificationContent,\n ) => void;\n [MatrixRTCSessionEvent.KeyRotationSuppressedChanged]: (isKeyRotationSuppressed: boolean) => void;\n};\n\nexport interface SessionConfig {\n /**\n * What kind of notification to send when starting the session.\n * @default `undefined` (no notification)\n */\n notificationType?: RTCNotificationType;\n\n /**\n * Determines the kind of call this will be.\n */\n callIntent?: RTCCallIntent;\n\n /**\n * How long (in milliseconds) the callee's client should keep ringing/waiting for an\n * answer before the sender gives up and the call notification is considered timed out.\n */\n notificationLifetimeMs?: number;\n}\n\n// The names follow these principles:\n// - we use the technical term delay if the option is related to delayed events.\n// - we use delayedLeaveEvent if the option is related to the delayed leave event.\n// - we use membershipEvent if the option is related to the rtc member state event.\n// - we use the technical term expiry if the option is related to the expiry field of the membership state event.\n// - we use a `Ms` postfix if the option is a duration to avoid using words like:\n// `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms.\nexport interface MembershipConfig {\n /**\n * The timeout (in milliseconds) after we joined the call, that our membership should expire\n * unless we have explicitly updated it.\n *\n * This is what goes into the m.rtc.member event expiry field and is typically set to a number of hours.\n */\n membershipEventExpiryMs?: number;\n\n /**\n * The time in (in milliseconds) which the manager will prematurely send the updated state event before the membership `expires` time to make sure it\n * sends the updated state event early enough.\n *\n * A headroom of 1000ms and a `membershipExpiryTimeout` of 10000ms would result in the first membership event update after 9s and\n * a membership event that would be considered expired after 10s.\n *\n * This value does not have an effect on the value of `SessionMembershipData.expires`.\n */\n membershipEventExpiryHeadroomMs?: number;\n\n /**\n * The timeout (in milliseconds) with which the deleayed leave event on the server is configured.\n * After this time the server will set the event to the disconnected stat if it has not received a keep-alive from the client.\n */\n delayedLeaveEventDelayMs?: number;\n\n /**\n * The interval (in milliseconds) in which the client will send membership keep-alives to the server.\n */\n delayedLeaveEventRestartMs?: number;\n\n /**\n * 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.\n */\n maximumRateLimitRetryCount?: number;\n\n /**\n * The maximum number of retries that the manager will do for delayed event sending/updating and state event sending when a network error occurs.\n */\n maximumNetworkErrorRetryCount?: number;\n\n /**\n * The time (in milliseconds) after which we will retry a http request if it\n * failed to send due to a network error. (send membership event, send delayed event, restart delayed event...)\n */\n networkErrorRetryMs?: number;\n\n /**\n * The time (in milliseconds) after which a we consider a delayed event restart http request to have failed.\n * Setting this to a lower value will result in more frequent retries but also a higher chance of failiour.\n *\n * In the presence of network packet loss (hurting TCP connections), the custom delayedEventRestartLocalTimeoutMs\n * helps by keeping more delayed event reset candidates in flight,\n * improving the chances of a successful reset. (its is equivalent to the js-sdk `localTimeout` configuration,\n * but only applies to calls to the `_unstable_restartScheduledDelayedEvent` endpoint\n * or the `_unstable_updateDelayedEvent` endpoint with a body of `{action:\"restart\"}`.)\n */\n delayedLeaveEventRestartLocalTimeoutMs?: number;\n\n /**\n * Send membership using sticky events rather than state events.\n * This also make the client use the new m.rtc.member MSC4354 event format. (instead of m.call.member)\n *\n * **WARNING**: This is an unstable feature and not all clients will support it.\n */\n unstableSendStickyEvents?: boolean;\n}\n\nexport interface EncryptionConfig {\n /**\n * If true, generate and share a media key for this participant,\n * and emit MatrixRTCSessionEvent.EncryptionKeyChanged when\n * media keys for other participants become available.\n */\n manageMediaKeys?: boolean;\n /**\n * The minimum time (in milliseconds) between each attempt to send encryption key(s).\n * e.g. if this is set to 1000, then we will send at most one key event every second.\n * @deprecated - Not used by the new encryption manager.\n */\n updateEncryptionKeyThrottle?: number;\n\n /**\n * Sometimes it is necessary to rotate the encryption key after a membership update.\n * For performance reasons we might not want to rotate the key immediately but allow future memberships to use the same key.\n * If 5 people join in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * If 5 people leave in a row in less than 5 seconds, we don't want to rotate the key for each of them.\n * So we do share the key which was already used live for <5s to new joiners.\n * This does result in a potential leak up to the configured time of call media.\n * This has to be considered when choosing a value for this property.\n */\n keyRotationGracePeriodMs?: number;\n\n /**\n * The number of participants in the session at which the media key will no longer be rotated.\n *\n * Rotating a key requires sending it to every participant device, so in large sessions the cost of rotating\n * on every join/leave becomes prohibitive. At this limit the current key is kept and\n * distributed to new joiners. No new keys are generated for joiners/leavers.\n *\n * Defaults to undefined.\n */\n keyRotationParticipantLimit?: number;\n\n /**\n * The delay (in milliseconds) after a member leaves before we create and publish a new key, because people\n * tend to leave calls at the same time.\n * @deprecated - Not used by the new encryption manager.\n */\n makeKeyDelay?: number;\n /**\n * The delay (in milliseconds) between sending a new key and starting to encrypt with it. This\n * gives others a chance to receive the new key to minimize the chance they get media they can't decrypt.\n *\n * The higher this value is, the better it is for existing members as they will have a smoother experience.\n * But it impacts new joiners: They will always have to wait `useKeyDelay` before being able to decrypt the media\n * (as it will be encrypted with the new key after the delay only), even if the key has already arrived before the delay.\n */\n useKeyDelay?: number;\n}\nexport type JoinSessionConfig = SessionConfig & MembershipConfig & EncryptionConfig;\n\ninterface SessionMembershipsForSlotOpts {\n /**\n * Listen for incoming sticky member events. If disabled, this session will\n * ignore any incoming sticky events.\n */\n listenForStickyEvents: boolean;\n /**\n * Listen for incoming member state events (legacy). If disabled, this session will\n * ignore any incoming state events.\n */\n listenForMemberStateEvents: boolean;\n}\n\nconst DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS: SessionMembershipsForSlotOpts = {\n listenForStickyEvents: true,\n listenForMemberStateEvents: true,\n};\n\n/**\n * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.\n * This class doesn't deal with media at all, just membership & properties of a session.\n */\nexport class MatrixRTCSession extends TypedEventEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n> {\n private membershipManager?: IMembershipManager;\n private encryptionManager?: IEncryptionManager;\n private joinConfig?: SessionConfig;\n private logger: Logger;\n\n private pendingNotificationToSend: undefined | RTCNotificationType;\n /**\n * This timeout is responsible to track any expiration. We need to know when we have to start\n * to ignore other call members. There is no callback for this. This timeout will always be configured to\n * emit when the next membership expires.\n */\n private expiryTimeout?: ReturnType<typeof setTimeout>;\n\n public memberships: CallMembership[] = [];\n\n /**\n * Resolves when the session has calculated the initial membership of the session.\n */\n public readonly initialMembershipCalculated: Promise<void>;\n /**\n * Does membership need to be recalculated? This is set to false upon\n * recalculation.\n */\n private membershipNeedsRecalculation = false;\n\n /**\n * The statistics for this session.\n */\n public statistics: Statistics = {\n counters: {\n roomEventEncryptionKeysSent: 0,\n roomEventEncryptionKeysReceived: 0,\n },\n totals: {\n roomEventEncryptionKeysReceivedTotalAge: 0,\n },\n };\n\n public get membershipStatus(): Status | undefined {\n return this.membershipManager?.status;\n }\n public get probablyLeft(): boolean | undefined {\n return this.membershipManager?.probablyLeft;\n }\n public get delayId(): string | undefined {\n return this.membershipManager?.delayId;\n }\n\n /**\n * Whether the key rotation is currently halted.\n * mirror of: EncryptionConfig.keyRotationParticipantLimit\n */\n public get isKeyRotationSuppressed(): boolean {\n return this.encryptionManager?.isKeyRotationSuppressed ?? false;\n }\n\n /**\n * The callId (sessionId) of the call.\n *\n * It can be undefined since the callId is only known once the first membership joins.\n * The callId is the property that, per definition, groups memberships into one call.\n * @deprecated use `slotId` instead.\n */\n public get callId(): string | undefined {\n return this.slotDescription?.id;\n }\n /**\n * The slotId of the call.\n * `{application}#{appSpecificId}`\n * It can be undefined since the slotId is only known once the first membership joins.\n * The slotId is the property that, per definition, groups memberships into one call.\n */\n public get slotId(): string | undefined {\n return computeSlotId(this.slotDescription);\n }\n\n /**\n * Reads the current slot state event's content for this session.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for this session.\n */\n public getRtcSlot(): RtcSlotEventContent | undefined {\n return getSlotEventContent(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Whether this session's slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\n public isSlotClosed(): boolean | undefined {\n return isSlotClosed(this.roomSubset, this.slotDescription);\n }\n\n /**\n * Ensures this session's slot is open, sending a slot state event to open (or create) it if needed.\n *\n * The event's `application` is set from this session's slot description and its `encryption` from\n * `opts.encryption`, replacing whatever an existing slot event declares. Other content is preserved.\n * No-op if the slot is already open with matching `application` and `encryption`.\n *\n * @param opts.encryption - The encryption to declare on the slot, or `undefined` for none.\n * @throws if sending the state event fails.\n */\n public async ensureRtcSlotOpen(opts: { encryption?: RtcSlotEncryptionContent } = {}): Promise<void> {\n const application = { type: this.slotDescription.application };\n const existingContent = this.getRtcSlot();\n if (\n existingContent?.status === \"open\" &&\n deepCompare(existingContent.application, application) &&\n deepCompare(existingContent.encryption, opts.encryption)\n ) {\n return;\n }\n await this.sendRtcSlot({\n ...existingContent,\n status: \"open\",\n application,\n encryption: opts.encryption,\n });\n }\n\n /**\n * Ensures this session's slot is closed, sending a slot state event to close it if needed.\n * The other content of the existing slot event is preserved. No-op if no slot event exists.\n *\n * @throws if sending the state event fails.\n */\n public async ensureRtcSlotClosed(): Promise<void> {\n const existingContent = this.getRtcSlot();\n if (!existingContent || existingContent.status === \"closed\") return;\n await this.sendRtcSlot({ ...existingContent, status: \"closed\" });\n }\n\n private async sendRtcSlot(content: RtcSlotEventContent): Promise<void> {\n await this.client.sendStateEvent(\n this.roomSubset.roomId,\n EventType.RTCSlot,\n content,\n computeSlotId(this.slotDescription),\n );\n }\n\n /**\n * Returns all the call memberships for a room that match the provided `sessionDescription`,\n * oldest first.\n *\n * By default, this will return *both* sticky and member state events.\n */\n public static async sessionMembershipsForSlot(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"hasMembershipState\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n // default both true this implied we combine sticky and state events for the final call state\n // (prefer sticky events in case of a duplicate)\n options: SessionMembershipsForSlotOpts = DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS,\n ): Promise<CallMembership[]> {\n const logger = rootLogger.getChild(\n `[MatrixRTCSession ${room.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n const callMemberEvents = collectMembersEvents(room, slotDescription, options, logger);\n\n const callMemberships = await computeBackendIdentityAndVerifyMemberEvents(\n room,\n callMemberEvents,\n slotDescription,\n logger,\n );\n\n callMemberships.sort((a, b) => a.createdTs() - b.createdTs());\n if (callMemberships.length > 1) {\n logger.debug(\n `Call memberships in room ${room.roomId}, in order: `,\n callMemberships.map((m) => [m.createdTs(), m.userId]),\n );\n }\n\n return callMemberships;\n }\n\n /**\n * Return the MatrixRTC session for the room.\n * This returned session can be used to find out if there are active sessions\n * for the requested room and `slotDescription`.\n */\n public static sessionForSlot(\n client: MatrixClient,\n room: Room,\n slotDescription: SlotDescription,\n opts?: SessionMembershipsForSlotOpts,\n ): MatrixRTCSession {\n return new MatrixRTCSession(client, room, slotDescription, opts);\n }\n\n /**\n * WARN: this can in theory only be a subset of the room with the properties required by\n * this class.\n * Outside of tests this most likely will be a full room, however.\n * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking\n * the room object in your own code and passing it in when needed.\n */\n public get room(): Room {\n return this.roomSubset as Room;\n }\n\n /**\n * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected\n * to be used with the MatrixRTCSessionManager exclusively.\n *\n * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone\n * to manage a joined MatrixRTC session.\n *\n * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.\n * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.\n * @param slotDescription The slot description is a virtual address where participants are allowed to meet.\n * This session will only manage memberships that match this slot description.Sessions are distinct if any of\n * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.\n * @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session.\n */\n public constructor(\n private readonly client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendEvent\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n | \"_unstable_cancelScheduledDelayedEvent\"\n | \"_unstable_restartScheduledDelayedEvent\"\n | \"_unstable_sendScheduledDelayedEvent\"\n | \"_unstable_sendStickyEvent\"\n | \"_unstable_sendStickyDelayedEvent\"\n | \"cancelPendingEvent\"\n | \"encryptAndSendToDevice\"\n | \"off\"\n | \"on\"\n | \"decryptEventIfNeeded\"\n >,\n private roomSubset: Pick<\n Room,\n | \"getLiveTimeline\"\n | \"roomId\"\n | \"getVersion\"\n | \"hasMembershipState\"\n | \"on\"\n | \"off\"\n | \"_unstable_getStickyEvents\"\n >,\n\n public readonly slotDescription: SlotDescription,\n private readonly calculateMembershipsOpts?: SessionMembershipsForSlotOpts,\n ) {\n super();\n this.logger = rootLogger.getChild(\n `[MatrixRTCSession ${roomSubset.roomId} ${slotDescription.application}#${slotDescription.id}]`,\n );\n\n this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.on(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n\n this.initialMembershipCalculated = this.ensureRecalculateSessionMembers();\n this.setExpiryTimer();\n }\n /*\n * Returns true if we intend to be participating in the MatrixRTC session.\n * This is determined by checking if the relativeExpiry has been set.\n */\n public isJoined(): boolean {\n return this.membershipManager?.isJoined() ?? false;\n }\n\n /**\n * Performs cleanup & removes timers for client shutdown\n */\n public async stop(): Promise<void> {\n await this.membershipManager?.leave(1000);\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n this.roomSubset.off(RoomStateEvent.Members, this.onRoomMemberUpdate);\n this.roomSubset.off(RoomStateEvent.Events, this.onRoomStateEvent);\n this.roomSubset.off(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n }\n\n private reEmitter = new TypedReEmitter<\n MatrixRTCSessionEvent | MembershipManagerEvent,\n MatrixRTCSessionEventHandlerMap & MembershipManagerEventHandlerMap\n >(this);\n\n /**\n * Announces this user and device as joined to the MatrixRTC session,\n * and continues to update the membership event to keep it valid until\n * leaveRoomSession() is called\n * This will not subscribe to updates: remember to call subscribe() separately if\n * desired.\n * This method will return immediately and the session will be joined in the background.\n * @param ownMembershipIdentity the identity of the user and device joining the session.\n * This will be put into the content.member.\n * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n * transport selection will be used instead.\n * @param joinConfig - Additional configuration for the joined session.\n */\n public joinRTCSession(\n ownMembershipIdentity: CallMembershipIdentityParts,\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n if (this.isJoined()) {\n this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);\n return;\n } else {\n // Create MembershipManager and pass the RTCSession logger (with room id info)\n this.membershipManager = joinConfig?.unstableSendStickyEvents\n ? new StickyEventMembershipManager(\n joinConfig,\n this.roomSubset,\n this.client,\n this.slotDescription,\n ownMembershipIdentity.memberId,\n this.logger,\n )\n : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);\n\n this.reEmitter.reEmit(this.membershipManager, [\n MembershipManagerEvent.ProbablyLeft,\n MembershipManagerEvent.StatusChanged,\n MembershipManagerEvent.DelayIdChanged,\n ]);\n // Create Encryption manager\n const [room, client, statistics] = [this.roomSubset, this.client, this.statistics];\n const transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, client, statistics);\n this.encryptionManager = new RTCEncryptionManager(\n ownMembershipIdentity,\n () => this.memberships,\n transport,\n (\n keyBin: Uint8Array<ArrayBuffer>,\n encryptionKeyIndex: number,\n membership: CallMembershipIdentityParts,\n rtcBackendIdentity: string,\n ) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyBin,\n encryptionKeyIndex,\n membership,\n rtcBackendIdentity,\n );\n },\n this.logger,\n );\n }\n\n this.joinConfig = joinConfig;\n this.pendingNotificationToSend = this.joinConfig?.notificationType;\n\n // Join!\n this.membershipManager.join(fociPreferred, multiSfuFocus, (e) => {\n this.logger.error(\"MembershipManager encountered an unrecoverable error: \", e);\n this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());\n });\n this.encryptionManager.join(joinConfig);\n\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);\n }\n\n /**\n *\n * @param fociPreferred\n * @param multiSfuFocus\n * @param joinConfig\n * @deprecated use the joinRTCSession method instead\n */\n public joinRoomSession(\n fociPreferred: Transport[],\n multiSfuFocus?: Transport,\n joinConfig?: JoinSessionConfig,\n ): void {\n const [userId, deviceId] = [this.client.getUserId()!, this.client.getDeviceId()!];\n // TODO this wants to become a UUID\n const memberId = `${userId}:${deviceId}`;\n this.joinRTCSession({ userId, deviceId, memberId }, fociPreferred, multiSfuFocus, joinConfig);\n }\n\n /**\n * Announces this user and device as having left the MatrixRTC session\n * and stops scheduled updates.\n * This will not unsubscribe from updates: remember to call unsubscribe() separately if\n * desired.\n * The membership update required to leave the session will retry if it fails.\n * Without network connection the promise will never resolve.\n * A timeout can be provided so that there is a guarantee for the promise to resolve.\n * @returns Whether the membership update was attempted and did not time out.\n */\n public async leaveRoomSession(timeout: number | undefined = undefined): Promise<boolean> {\n if (!this.isJoined()) {\n this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`);\n return false;\n }\n\n this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`);\n\n this.encryptionManager!.leave();\n\n const leavePromise = this.membershipManager!.leave(timeout);\n this.emit(MatrixRTCSessionEvent.JoinStateChanged, false);\n\n return await leavePromise;\n }\n /**\n * This returns the focus in use by the oldest membership.\n * Do not use since this might be just the focus for the oldest membership. others might use a different focus.\n * @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.\n */\n public getFocusInUse(): Transport | undefined {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getTransport(oldestMembership);\n }\n\n public getOldestMembership(): CallMembership | undefined {\n return this.memberships[0];\n }\n\n /**\n * Get the call intent for the current call, based on what members are advertising. If one or more\n * members disagree on the current call intent, or nobody specifies one then `undefined` is returned.\n *\n * If all members that specify a call intent agree, that value is returned.\n * @returns A call intent, or `undefined` if no consensus or not given.\n */\n public getConsensusCallIntent(): RTCCallIntent | undefined {\n const getFirstCallIntent = this.memberships.find((m) => !!m.callIntent)?.callIntent;\n if (!getFirstCallIntent) {\n return undefined;\n }\n if (this.memberships.every((m) => !m.callIntent || m.callIntent === getFirstCallIntent)) {\n return getFirstCallIntent;\n }\n return undefined;\n }\n\n public async updateCallIntent(callIntent: RTCCallIntent): Promise<void> {\n const myMembership = this.membershipManager?.ownMembership;\n if (!myMembership) {\n throw Error(\"Not connected yet\");\n }\n await this.membershipManager?.updateCallIntent(callIntent);\n }\n\n /**\n * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export\n * the keys.\n */\n public reemitEncryptionKeys(): void {\n this.encryptionManager?.getEncryptionKeys().forEach((keyRing, key) => {\n keyRing.forEach((keyInfo) => {\n this.emit(\n MatrixRTCSessionEvent.EncryptionKeyChanged,\n keyInfo.key,\n keyInfo.keyIndex,\n keyInfo.membership,\n keyInfo.rtcBackendIdentity,\n );\n });\n });\n }\n\n /**\n * Sets a timer for the soonest membership expiry\n */\n private setExpiryTimer(): void {\n if (this.expiryTimeout) {\n clearTimeout(this.expiryTimeout);\n this.expiryTimeout = undefined;\n }\n\n let soonestExpiry;\n for (const membership of this.memberships) {\n const thisExpiry = membership.getMsUntilExpiry();\n // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires\n // but will be reliably resent on disconnect.\n if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {\n soonestExpiry = thisExpiry;\n }\n }\n\n if (soonestExpiry != undefined) {\n this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry);\n }\n }\n\n /**\n * Sends notification events to indiciate the call has started.\n * Note: This does not return a promise, instead scheduling the notification events to be sent.\n * @param parentEventId Event id linking to your RTC call membership event.\n * @param notificationType The type of notification to send\n * @param callIntent The type of call this is (e.g. \"audio\").\n */\n private sendCallNotify(\n parentEventId: string,\n notificationType: RTCNotificationType,\n callIntent?: RTCCallIntent,\n ): void {\n const lifetime = this.joinConfig?.notificationLifetimeMs ?? 90_000;\n const sendNotificationEvent = async (): Promise<{\n response: ISendEventResponse;\n content: IRTCNotificationContent;\n }> => {\n const content: IRTCNotificationContent = {\n \"m.mentions\": { user_ids: [], room: true },\n \"notification_type\": notificationType,\n \"m.relates_to\": {\n event_id: parentEventId,\n rel_type: RelationType.Reference,\n },\n \"sender_ts\": Date.now(),\n \"lifetime\": lifetime,\n };\n if (callIntent) {\n content[\"m.call.intent\"] = callIntent;\n }\n const response = await this.client.sendEvent(this.roomSubset.roomId, EventType.RTCNotification, content);\n return { response, content };\n };\n\n void sendNotificationEvent()\n .then((notification) => {\n // Join event_id and origin event content\n const newResult = { ...notification.response, ...notification.content };\n this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);\n })\n .catch(([errorLegacy, errorNew]) =>\n this.logger.error(\"Failed to send call notification\", errorLegacy, errorNew),\n );\n }\n\n /**\n * Call this when the Matrix room members have changed.\n */\n private readonly onRoomMemberUpdate = (): void => {\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a room state event has been updated.\n */\n private readonly onRoomStateEvent = (event: MatrixEvent): void => {\n if (event.getType() !== EventType.RTCSlot) return;\n if (event.getStateKey() !== computeSlotId(this.slotDescription)) return;\n void this.ensureRecalculateSessionMembers();\n };\n\n /**\n * Call this when a sticky event update has occured.\n */\n private readonly onStickyEventUpdate: RoomStickyEventsMap[RoomStickyEventsEvent.Update] = (\n added,\n updated,\n removed,\n ): void => {\n if (\n [...added, ...removed, ...updated.flatMap((v) => [v.current, v.previous])].some(\n (e) => e.getType() === EventType.RTCMembership,\n )\n ) {\n void this.ensureRecalculateSessionMembers();\n }\n };\n\n /**\n * Call this when something changed that may impacts the current MatrixRTC members in this session.\n */\n // We allow this name schema since this function should only be used for testing purposes.\n public _onRTCSessionMemberUpdate = async (): Promise<void> => {\n await this.recalculateSessionMembers();\n };\n\n // helper variables to make sure we do not have parallel running recalculations.\n private recalculateSessionMembersPromise: Promise<void> = Promise.resolve();\n\n /**\n * Ensures that membership is recalculated when the state of the session may have changed.\n * Also ensures that only one recalculation is made at a time.\n * @returns A promise resolving when the state has been recalculated.\n */\n private ensureRecalculateSessionMembers(): Promise<void> {\n if (this.membershipNeedsRecalculation) {\n // We have already requested recalcuation, don't attempt a new one.\n return this.recalculateSessionMembersPromise;\n }\n this.membershipNeedsRecalculation = true;\n // Chain the recalculation.\n this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.then(\n () => this.recalculateSessionMembers(),\n () => this.recalculateSessionMembers(),\n );\n return this.recalculateSessionMembersPromise;\n }\n\n /**\n * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.\n *\n * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.\n *\n * This function should be called when the room members or call memberships might have changed.\n */\n private readonly recalculateSessionMembers = async (): Promise<void> => {\n // Clear the flag.\n this.membershipNeedsRecalculation = false;\n const oldMemberships = this.memberships;\n // Needs to be computed before `this.memberships` is updated below, since it is derived from it.\n const wasKeyRotationSuppressed = this.isKeyRotationSuppressed;\n\n this.memberships = await MatrixRTCSession.sessionMembershipsForSlot(\n this.room,\n this.slotDescription,\n this.calculateMembershipsOpts,\n );\n\n const changed =\n oldMemberships.length != this.memberships.length ||\n oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i]));\n\n if (changed) {\n this.logger.info(\n `Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`,\n );\n logDurationSync(this.logger, \"emit MatrixRTCSessionEvent.MembershipsChanged\", () => {\n this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships);\n });\n\n void this.membershipManager?.onRTCSessionMemberUpdate(this.memberships);\n // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`.\n const ownMembership = this.membershipManager?.ownMembership;\n if (this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {\n // If we're the first member in the call, we're responsible for\n // sending the notification event\n if (ownMembership.eventId && this.joinConfig?.notificationType) {\n this.sendCallNotify(\n ownMembership.eventId,\n this.joinConfig.notificationType,\n ownMembership.callIntent,\n );\n } else {\n this.logger.warn(\"Own membership eventId is undefined, cannot send call notification\");\n }\n }\n // If anyone else joins the session it is no longer our responsibility to send the notification.\n // (If we were the joiner we already did sent the notification in the block above.)\n if (this.memberships.length > 0) this.pendingNotificationToSend = undefined;\n } else {\n this.logger.debug(`No membership changes detected for room ${this.roomSubset.roomId}`);\n }\n // This also needs to be done if `changed` = false\n // A member might have updated their fingerprint (created_ts)\n this.encryptionManager?.onMembershipsUpdate(oldMemberships);\n if (this.isKeyRotationSuppressed !== wasKeyRotationSuppressed) {\n this.logger.info(\n `Key rotation is now ${this.isKeyRotationSuppressed ? \"suppressed\" : \"active again\"} (${this.memberships.length} members)`,\n );\n this.emit(MatrixRTCSessionEvent.KeyRotationSuppressedChanged, this.isKeyRotationSuppressed);\n }\n\n this.setExpiryTimer();\n };\n}\n\n/// Private helpers\nasync function computeBackendIdentityAndVerifyMemberEvents(\n room: Pick<Room, \"hasMembershipState\">,\n callMemberEvents: MatrixEvent[],\n slotDescription: SlotDescription,\n logger: Logger,\n): Promise<CallMembership[]> {\n const callMemberships: CallMembership[] = [];\n\n for (const memberEvent of callMemberEvents) {\n const content = memberEvent.getContent();\n\n // Quick filter to avoid unneeded processing of invalid events or left events.\n if (!quickFilterNonRelevantContents(content, logger)) {\n continue;\n }\n\n try {\n const membership = await CallMembership.parseFromEvent(memberEvent);\n\n if (isValidMembership(membership, room, slotDescription, logger)) {\n callMemberships.push(membership);\n }\n } catch (e) {\n logger.warn(\"Couldn't construct call membership: \", e);\n }\n }\n\n return callMemberships;\n}\n\nfunction quickFilterNonRelevantContents(content: IContent, logger: Logger): boolean {\n // Ignore sticky keys for the count\n const eventKeysCount = Object.keys(content).filter((k) => k !== \"msc4354_sticky_key\").length;\n // Don't even bother about empty events (saves us from costly type/\"key in\" checks in bigger rooms)\n if (eventKeysCount === 0) return false;\n\n // We first decide if it's a MSC4143 event (per device state key)\n if (eventKeysCount > 1 && \"application\" in content) {\n // We have a MSC4143 event membership event with a proper joined content\n return true;\n } else if (eventKeysCount === 1 && \"memberships\" in content) {\n // Events used to have this format in the past, but are now deprecated.\n // Given that state events ~cannot be deleted, there can be some remaining events in the room, just ignore them.\n return false;\n } else {\n // Invalid or left content\n return false;\n }\n}\n\nfunction isValidMembership(\n membership: CallMembership,\n room: Pick<Room, \"hasMembershipState\">,\n slotDescription: SlotDescription,\n logger: Logger,\n): boolean {\n if (membership.slotDescription.id !== slotDescription.id) {\n logger.info(\n `Ignoring membership of user ${membership.userId} for a different slot. Theirs: ${JSON.stringify(membership.slotDescription)}, Expected: ${JSON.stringify(slotDescription)}`,\n );\n return false;\n }\n\n if (membership.isExpired()) {\n logger.info(`Ignoring expired device membership ${membership.userId}/${membership.deviceId}`);\n return false;\n }\n\n if (!room.hasMembershipState(membership.userId ?? \"\", KnownMembership.Join)) {\n logger.info(`Ignoring membership of user ${membership.userId} who is not in the room.`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Reads the slot state event's content for the given slot description.\n *\n * @returns The slot event's content, or `undefined` if no slot event exists for the given description.\n */\nfunction getSlotEventContent(\n room: Pick<Room, \"getLiveTimeline\">,\n slotDescription: SlotDescription,\n): RtcSlotEventContent | undefined {\n const slotId = computeSlotId(slotDescription);\n const slotEvent = room\n .getLiveTimeline()\n .getState(EventTimeline.FORWARDS)\n ?.getStateEvents(EventType.RTCSlot, slotId);\n if (!slotEvent) return undefined;\n\n return slotEvent.getContent<RtcSlotEventContent>();\n}\n\n/**\n * Whether the given slot is closed.\n *\n * @returns `true` if the slot is closed, `false` if the slot is open or `undefined`\n * if no slot exists.\n */\nfunction isSlotClosed(room: Pick<Room, \"getLiveTimeline\">, slotDescription: SlotDescription): boolean | undefined {\n const content = getSlotEventContent(room, slotDescription) as Partial<RtcSlotEventContent> | undefined;\n if (content === undefined) return undefined;\n\n return (\n content.status !== \"open\" ||\n typeof content.application !== \"object\" ||\n content.application?.type !== slotDescription.application\n );\n}\n\n/**\n * Collects the raw member events from room state and sticky store.\n */\nfunction collectMembersEvents(\n room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"_unstable_getStickyEvents\">,\n slotDescription: SlotDescription,\n options: SessionMembershipsForSlotOpts,\n logger: Logger,\n): MatrixEvent[] {\n const { listenForStickyEvents, listenForMemberStateEvents } = options;\n let callMemberEvents: MatrixEvent[] = [];\n if (listenForStickyEvents && !isSlotClosed(room, slotDescription)) {\n // prefill with sticky events\n callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership);\n }\n if (listenForMemberStateEvents) {\n const roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!roomState) {\n logger.warn(\"Couldn't get state for room \" + room.roomId + \"using empty membership array\");\n return [];\n }\n const callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);\n callMemberEvents = callMemberEvents.concat(\n callMemberStateEvents.filter(\n (callMemberStateEvent) =>\n !callMemberEvents.some(\n // only care about state events which have keys which we have not yet seen in the sticky events.\n // TODO: I believe this can discard a joined state event if there is a matching left sticky event.\n (stickyEvent) =>\n stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey(),\n ),\n ),\n );\n }\n return callMemberEvents;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsB,MAAM,IAAI,UAAU,QAAQ,cAAc;AAChE,SAAS,iBAAiB,QAAQ,kCAAkC;AACpE,SAAS,aAAa,QAAQ,6BAA6B;AAG3D,SAAS,SAAS,EAAE,YAAY,QAAQ,oBAAoB;AAC5D,SAAS,eAAe,QAAQ,yBAAyB;AAEzD,SAAS,cAAc,QAAQ,qBAAqB;AACpD,SAAS,cAAc,QAAQ,yBAAyB;AACxD,SAAS,iBAAiB,EAAE,4BAA4B,QAAQ,wBAAwB;AAExF,SAAS,WAAW,EAAE,eAAe,QAAQ,aAAa;AAY1D,SACI,sBAAsB,QAGnB,yBAAyB;AAChC,SAAS,oBAAoB,QAAQ,2BAA2B;AAChE,SAAS,oBAAoB,QAAQ,2BAA2B;AAChE,SAAS,cAAc,QAAQ,iBAAiB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ChC,OAAsC,EACtC,MAAc,EACD;EACb,MAAM;IAAE,qBAAqB;IAAE;EAA2B,CAAC,GAAG,OAAO;EACrE,IAAI,gBAA+B,GAAG,EAAE;EACxC,IAAI,qBAAqB,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE;IAC/D;IACA,gBAAgB,GAAG,CAAC,GAAG,IAAI,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAE,CAAC,IAAK,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,SAAS,CAAC,aAAa,CAAC;EACnH;EACA,IAAI,0BAA0B,EAAE;IAC5B,MAAM,SAAS,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC;IACzE,IAAI,CAAC,SAAS,EAAE;MACZ,MAAM,CAAC,IAAI,CAAC,8BAA8B,GAAG,IAAI,CAAC,MAAM,GAAG,8BAA8B,CAAC;MAC1F,OAAO,EAAE;IACb;IACA,MAAM,qBAAqB,GAAG,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,qBAAqB,CAAC;IACvF,gBAAgB,GAAG,gBAAgB,CAAC,MAAM,CACtC,qBAAqB,CAAC,MAAM,CACvB,oBAAoB,IACjB,CAAC,gBAAgB,CAAC,IAAI;IAClB;IACA;IACC,WAAW,IACR,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,kBAAkB,KAAK,oBAAoB,CAAC,WAAW,CAAC,CACzF,CACR,CACJ,CAAC;EACL;EACA,OAAO,gBAAgB;AAC3B","ignoreList":[]}
@@ -773,11 +773,14 @@ export class MembershipManager extends TypedEventEmitter {
773
773
  const retryCounterString = "(" + retries + "/" + this.maximumNetworkErrorRetryCount + ")";
774
774
 
775
775
  // Variables for scheduling the new event
776
- let retryDuration = this.networkErrorRetryMs;
776
+ const retryDuration = this.networkErrorRetryMs;
777
777
  if (error instanceof Error && error.name === "AbortError") {
778
- // We do not wait for the timeout on local timeouts.
779
- retryDuration = 0;
780
- this.logger.warn("Network local timeout error while sending event, immediate retry (" + retryCounterString + ")", error);
778
+ // A local timeout means the server accepted the request but is slow to answer. Retry immediately and
779
+ // do not count it towards the fatal retry limit: the server's delayed leave already bounds how long a
780
+ // stalled restart can go unnoticed, and the resulting forced re-join recovers the membership. Giving
781
+ // up here would only replace a temporary media pause with a "connection lost" error for the user.
782
+ this.logger.warn("Network local timeout error while sending event, immediate retry", error);
783
+ return createInsertActionUpdate(type, 0);
781
784
  } else if (error instanceof Error && error.message.includes("updating delayed event")) {
782
785
  // TODO: We do not want error message matching here but instead the error should be a typed HTTPError
783
786
  // and be handled below automatically (the same as in the SPA case).