>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport interface ICreateFilterOpts {\n // Populate the filtered timeline with already loaded events in the room\n // timeline. Useful to disable for some filters that can't be achieved by the\n // client in an efficient manner\n prepopulateTimeline?: boolean;\n useSyncEvents?: boolean;\n pendingEvents?: boolean;\n}\n\nexport enum RoomEvent {\n MyMembership = \"Room.myMembership\",\n Tags = \"Room.tags\",\n AccountData = \"Room.accountData\",\n Receipt = \"Room.receipt\",\n Name = \"Room.name\",\n Redaction = \"Room.redaction\",\n RedactionCancelled = \"Room.redactionCancelled\",\n LocalEchoUpdated = \"Room.localEchoUpdated\",\n Timeline = \"Room.timeline\",\n TimelineReset = \"Room.timelineReset\",\n TimelineRefresh = \"Room.TimelineRefresh\",\n OldStateUpdated = \"Room.OldStateUpdated\",\n CurrentStateUpdated = \"Room.CurrentStateUpdated\",\n HistoryImportedWithinTimeline = \"Room.historyImportedWithinTimeline\",\n UnreadNotifications = \"Room.UnreadNotifications\",\n}\n\nexport type RoomEmittedEvents =\n | RoomEvent\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | ThreadEvent.New\n | ThreadEvent.Update\n | ThreadEvent.NewReply\n | ThreadEvent.Delete\n | MatrixEventEvent.BeforeRedaction\n | BeaconEvent.New\n | BeaconEvent.Update\n | BeaconEvent.Destroy\n | BeaconEvent.LivenessChange\n | PollEvent.New;\n\nexport type RoomEventHandlerMap = {\n /**\n * Fires when the logged in user's membership in the room is updated.\n *\n * @param room - The room in which the membership has been updated\n * @param membership - The new membership value\n * @param prevMembership - The previous membership value\n */\n [RoomEvent.MyMembership]: (room: Room, membership: string, prevMembership?: string) => void;\n /**\n * Fires whenever a room's tags are updated.\n * @param event - The tags event\n * @param room - The room whose Room.tags was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.tags\", function(event, room){\n * var newTags = event.getContent().tags;\n * if (newTags[\"favourite\"]) showStar(room);\n * });\n * ```\n */\n [RoomEvent.Tags]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever a room's account_data is updated.\n * @param event - The account_data event\n * @param room - The room whose account_data was updated.\n * @param prevEvent - The event being replaced by\n * the new account data, if known.\n * @example\n * ```\n * matrixClient.on(\"Room.accountData\", function(event, room, oldEvent){\n * if (event.getType() === \"m.room.colorscheme\") {\n * applyColorScheme(event.getContents());\n * }\n * });\n * ```\n */\n [RoomEvent.AccountData]: (event: MatrixEvent, room: Room, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a receipt is received for a room\n * @param event - The receipt event\n * @param room - The room whose receipts was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.receipt\", function(event, room){\n * var receiptContent = event.getContent();\n * });\n * ```\n */\n [RoomEvent.Receipt]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever the name of a room is updated.\n * @param room - The room whose Room.name was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.name\", function(room){\n * var newName = room.name;\n * });\n * ```\n */\n [RoomEvent.Name]: (room: Room) => void;\n /**\n * Fires when an event we had previously received is redacted.\n *\n * (Note this is *not* fired when the redaction happens before we receive the\n * event).\n *\n * @param event - The matrix redaction event\n * @param room - The room containing the redacted event\n */\n [RoomEvent.Redaction]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when an event that was previously redacted isn't anymore.\n * This happens when the redaction couldn't be sent and\n * was subsequently cancelled by the user. Redactions have a local echo\n * which is undone in this scenario.\n *\n * @param event - The matrix redaction event that was cancelled.\n * @param room - The room containing the unredacted event\n */\n [RoomEvent.RedactionCancelled]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when the status of a transmitted event is updated.\n *\n * When an event is first transmitted, a temporary copy of the event is\n * inserted into the timeline, with a temporary event id, and a status of\n * 'SENDING'.\n *\n *
Once the echo comes back from the server, the content of the event\n * (MatrixEvent.event) is replaced by the complete event from the homeserver,\n * thus updating its event id, as well as server-generated fields such as the\n * timestamp. Its status is set to null.\n *\n *
Once the /send request completes, if the remote echo has not already\n * arrived, the event is updated with a new event id and the status is set to\n * 'SENT'. The server-generated fields are of course not updated yet.\n *\n *
If the /send fails, In this case, the event's status is set to\n * 'NOT_SENT'. If it is later resent, the process starts again, setting the\n * status to 'SENDING'. Alternatively, the message may be cancelled, which\n * removes the event from the room, and sets the status to 'CANCELLED'.\n *\n *
This event is raised to reflect each of the transitions above.\n *\n * @param event - The matrix event which has been updated\n *\n * @param room - The room containing the redacted event\n *\n * @param oldEventId - The previous event id (the temporary event id,\n * except when updating a successfully-sent event when its echo arrives)\n *\n * @param oldStatus - The previous event status.\n */\n [RoomEvent.LocalEchoUpdated]: (\n event: MatrixEvent,\n room: Room,\n oldEventId?: string,\n oldStatus?: EventStatus | null,\n ) => void;\n [RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.HistoryImportedWithinTimeline]: (markerEvent: MatrixEvent, room: Room) => void;\n [RoomEvent.UnreadNotifications]: (unreadNotifications?: NotificationCount, threadId?: string) => void;\n [RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;\n [ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;\n /**\n * Fires when a new poll instance is added to the room state\n * @param poll - the new poll\n */\n [PollEvent.New]: (poll: Poll) => void;\n} & Pick &\n EventTimelineSetHandlerMap &\n Pick &\n Pick<\n RoomStateEventHandlerMap,\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | BeaconEvent.New\n > &\n Pick;\n\nexport class Room extends ReadReceipt {\n public readonly reEmitter: TypedReEmitter;\n private txnToEvent: Map = new Map(); // Pending in-flight requests { string: MatrixEvent }\n private notificationCounts: NotificationCount = {};\n private readonly threadNotifications = new Map();\n public readonly cachedThreadReadReceipts = new Map();\n // Useful to know at what point the current user has started using threads in this room\n private oldestThreadedReceiptTs = Infinity;\n /**\n * A record of the latest unthread receipts per user\n * This is useful in determining whether a user has read a thread or not\n */\n private unthreadedReceipts = new Map();\n private readonly timelineSets: EventTimelineSet[];\n public readonly polls: Map = new Map();\n public readonly threadsTimelineSets: EventTimelineSet[] = [];\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record = {}; // filter_id: timelineSet\n private timelineNeedsRefresh = false;\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices?: boolean;\n private selfMembership?: string;\n private summaryHeroes: string[] | null = null;\n // flags to stop logspam about missing m.room.create events\n private getTypeWarning = false;\n private getVersionWarning = false;\n private membersPromise?: Promise;\n\n // XXX: These should be read-only\n /**\n * The human-readable display name for this room.\n */\n public name: string;\n /**\n * The un-homoglyphed name for this room.\n */\n public normalizedName: string;\n /**\n * Dict of room tags; the keys are the tag name and the values\n * are any metadata associated with the tag - e.g. `{ \"fav\" : { order: 1 } }`\n */\n public tags: Record> = {}; // $tagName: { $metadata: $value }\n /**\n * accountData Dict of per-room account_data events; the keys are the\n * event type and the values are the events.\n */\n public accountData: Map = new Map(); // $eventType: $event\n /**\n * The room summary.\n */\n public summary: RoomSummary | null = null;\n // legacy fields\n /**\n * The live event timeline for this room, with the oldest event at index 0.\n * Present for backwards compatibility - prefer getLiveTimeline().getEvents()\n */\n public timeline!: MatrixEvent[];\n /**\n * oldState The state of the room at the time of the oldest\n * event in the live timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).\n */\n public oldState!: RoomState;\n /**\n * currentState The state of the room at the time of the\n * newest event in the timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.FORWARDS).\n */\n public currentState!: RoomState;\n public readonly relations = new RelationsContainer(this.client, this);\n\n /**\n * A collection of events known by the client\n * This is not a comprehensive list of the threads that exist in this room\n */\n private threads = new Map();\n public lastThread?: Thread;\n\n /**\n * A mapping of eventId to all visibility changes to apply\n * to the event, by chronological order, as per\n * https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * # Invariants\n *\n * - within each list, all events are classed by\n * chronological order;\n * - all events are events such that\n * `asVisibilityEvent()` returns a non-null `IVisibilityChange`;\n * - within each list with key `eventId`, all events\n * are in relation to `eventId`.\n *\n * @experimental\n */\n private visibilityEvents = new Map();\n\n /**\n * Construct a new Room.\n *\n * For a room, we store an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline. It also tracks\n * forward and backward pagination tokens, as well as containing links to the\n * next timeline in the sequence.\n *\n *
There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n *
In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @param roomId - Required. The ID of this room.\n * @param client - Required. The client, used to lazy load members.\n * @param myUserId - Required. The ID of the syncing user.\n * @param opts - Configuration options\n */\n public constructor(\n public readonly roomId: string,\n public readonly client: MatrixClient,\n public readonly myUserId: string,\n private readonly opts: IOpts = {},\n ) {\n super();\n // In some cases, we add listeners for every displayed Matrix event, so it's\n // common to have quite a few more than the default limit.\n this.setMaxListeners(100);\n this.reEmitter = new TypedReEmitter(this);\n\n opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n\n this.name = roomId;\n this.normalizedName = roomId;\n\n // all our per-room timeline sets. the first one is the unfiltered ones;\n // the subsequent ones are the filtered ones in no particular order.\n this.timelineSets = [new EventTimelineSet(this, opts)];\n this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.fixUpLegacyTimelineFields();\n\n if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {\n this.pendingEventList = [];\n this.client.store.getPendingEvents(this.roomId).then((events) => {\n const mapper = this.client.getEventMapper({\n toDevice: false,\n decrypt: false,\n });\n events.forEach(async (serializedEvent: Partial) => {\n const event = mapper(serializedEvent);\n await client.decryptEventIfNeeded(event);\n event.setStatus(EventStatus.NOT_SENT);\n this.addPendingEvent(event, event.getTxnId()!);\n });\n });\n }\n\n // awaited by getEncryptionTargetMembers while room members are loading\n if (!this.opts.lazyLoadMembers) {\n this.membersPromise = Promise.resolve(false);\n } else {\n this.membersPromise = undefined;\n }\n }\n\n private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;\n public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null> {\n if (this.threadTimelineSetsPromise) {\n return this.threadTimelineSetsPromise;\n }\n\n if (this.client?.supportsThreads()) {\n try {\n this.threadTimelineSetsPromise = Promise.all([\n this.createThreadTimelineSet(),\n this.createThreadTimelineSet(ThreadFilterType.My),\n ]);\n const timelineSets = await this.threadTimelineSetsPromise;\n this.threadsTimelineSets.push(...timelineSets);\n return timelineSets;\n } catch (e) {\n this.threadTimelineSetsPromise = null;\n return null;\n }\n }\n return null;\n }\n\n /**\n * Bulk decrypt critical events in a room\n *\n * Critical events represents the minimal set of events to decrypt\n * for a typical UI to function properly\n *\n * - Last event of every room (to generate likely message preview)\n * - All events up to the read receipt (to calculate an accurate notification count)\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptCriticalEvents(): Promise {\n if (!this.client.isCryptoEnabled()) return;\n\n const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId()!, true);\n const events = this.getLiveTimeline().getEvents();\n const readReceiptTimelineIndex = events.findIndex((matrixEvent) => {\n return matrixEvent.event.event_id === readReceiptEventId;\n });\n\n const decryptionPromises = events\n .slice(readReceiptTimelineIndex)\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true }));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Bulk decrypt events in a room\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptAllEvents(): Promise {\n if (!this.client.isCryptoEnabled()) return;\n\n const decryptionPromises = this.getUnfilteredTimelineSet()\n .getLiveTimeline()\n .getEvents()\n .slice(0) // copy before reversing\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true }));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Gets the creator of the room\n * @returns The creator of the room, or null if it could not be determined\n */\n public getCreator(): string | null {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n return createEvent?.getContent()[\"creator\"] ?? null;\n }\n\n /**\n * Gets the version of the room\n * @returns The version of the room, or null if it could not be determined\n */\n public getVersion(): string {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getVersionWarning) {\n logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getVersionWarning = true;\n }\n return \"1\";\n }\n return createEvent.getContent()[\"room_version\"] ?? \"1\";\n }\n\n /**\n * Determines whether this room needs to be upgraded to a new version\n * @returns What version the room should be upgraded to, or null if\n * the room does not require upgrading at this time.\n * @deprecated Use #getRecommendedVersion() instead\n */\n public shouldUpgradeToVersion(): string | null {\n // TODO: Remove this function.\n // This makes assumptions about which versions are safe, and can easily\n // be wrong. Instead, people are encouraged to use getRecommendedVersion\n // which determines a safer value. This function doesn't use that function\n // because this is not async-capable, and to avoid breaking the contract\n // we're deprecating this.\n\n if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {\n return KNOWN_SAFE_ROOM_VERSION;\n }\n\n return null;\n }\n\n /**\n * Determines the recommended room version for the room. This returns an\n * object with 3 properties: `version` as the new version the\n * room should be upgraded to (may be the same as the current version);\n * `needsUpgrade` to indicate if the room actually can be\n * upgraded (ie: does the current version not match?); and `urgent`\n * to indicate if the new version patches a vulnerability in a previous\n * version.\n * @returns\n * Resolves to the version the room should be upgraded to.\n */\n public async getRecommendedVersion(): Promise {\n const capabilities = await this.client.getCapabilities();\n let versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n versionCap = {\n default: KNOWN_SAFE_ROOM_VERSION,\n available: {},\n };\n for (const safeVer of SAFE_ROOM_VERSIONS) {\n versionCap.available[safeVer] = RoomVersionStability.Stable;\n }\n }\n\n let result = this.checkVersionAgainstCapability(versionCap);\n if (result.urgent && result.needsUpgrade) {\n // Something doesn't feel right: we shouldn't need to update\n // because the version we're on should be in the protocol's\n // namespace. This usually means that the server was updated\n // before the client was, making us think the newest possible\n // room version is not stable. As a solution, we'll refresh\n // the capability we're using to determine this.\n logger.warn(\n \"Refreshing room version capability because the server looks \" +\n \"to be supporting a newer room version we don't know about.\",\n );\n\n const caps = await this.client.getCapabilities(true);\n versionCap = caps[\"m.room_versions\"];\n if (!versionCap) {\n logger.warn(\"No room version capability - assuming upgrade required.\");\n return result;\n } else {\n result = this.checkVersionAgainstCapability(versionCap);\n }\n }\n\n return result;\n }\n\n private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {\n const currentVersion = this.getVersion();\n logger.log(`[${this.roomId}] Current version: ${currentVersion}`);\n logger.log(`[${this.roomId}] Version capability: `, versionCap);\n\n const result: IRecommendedVersion = {\n version: currentVersion,\n needsUpgrade: false,\n urgent: false,\n };\n\n // If the room is on the default version then nothing needs to change\n if (currentVersion === versionCap.default) return result;\n\n const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === \"stable\");\n\n // Check if the room is on an unstable version. We determine urgency based\n // off the version being in the Matrix spec namespace or not (if the version\n // is in the current namespace and unstable, the room is probably vulnerable).\n if (!stableVersions.includes(currentVersion)) {\n result.version = versionCap.default;\n result.needsUpgrade = true;\n result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n if (result.urgent) {\n logger.warn(`URGENT upgrade required on ${this.roomId}`);\n } else {\n logger.warn(`Non-urgent upgrade required on ${this.roomId}`);\n }\n return result;\n }\n\n // The room is on a stable, but non-default, version by this point.\n // No upgrade needed.\n return result;\n }\n\n /**\n * Determines whether the given user is permitted to perform a room upgrade\n * @param userId - The ID of the user to test against\n * @returns True if the given user is permitted to upgrade the room\n */\n public userMayUpgradeRoom(userId: string): boolean {\n return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n }\n\n /**\n * Get the list of pending sent events for this room\n *\n * @returns A list of the sent events\n * waiting for remote echo.\n *\n * @throws If `opts.pendingEventOrdering` was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call getPendingEvents with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n return this.pendingEventList;\n }\n\n /**\n * Removes a pending event for this room\n *\n * @returns True if an element was removed.\n */\n public removePendingEvent(eventId: string): boolean {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call removePendingEvent with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n const removed = utils.removeElement(\n this.pendingEventList,\n function (ev) {\n return ev.getId() == eventId;\n },\n false,\n );\n\n this.savePendingEvents();\n\n return removed;\n }\n\n /**\n * Check whether the pending event list contains a given event by ID.\n * If pending event ordering is not \"detached\" then this returns false.\n *\n * @param eventId - The event ID to check for.\n */\n public hasPendingEvent(eventId: string): boolean {\n return this.pendingEventList?.some((event) => event.getId() === eventId) ?? false;\n }\n\n /**\n * Get a specific event from the pending event list, if configured, null otherwise.\n *\n * @param eventId - The event ID to check for.\n */\n public getPendingEvent(eventId: string): MatrixEvent | null {\n return this.pendingEventList?.find((event) => event.getId() === eventId) ?? null;\n }\n\n /**\n * Get the live unfiltered timeline for this room.\n *\n * @returns live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().getLiveTimeline();\n }\n\n /**\n * Get the timestamp of the last message in the room\n *\n * @returns the timestamp of the last message in the room\n */\n public getLastActiveTimestamp(): number {\n const timeline = this.getLiveTimeline();\n const events = timeline.getEvents();\n if (events.length) {\n const lastEvent = events[events.length - 1];\n return lastEvent.getTs();\n } else {\n return Number.MIN_SAFE_INTEGER;\n }\n }\n\n /**\n * @returns the membership type (join | leave | invite) for the logged in user\n */\n public getMyMembership(): string {\n return this.selfMembership ?? \"leave\";\n }\n\n /**\n * If this room is a DM we're invited to,\n * try to find out who invited us\n * @returns user id of the inviter\n */\n public getDMInviter(): string | undefined {\n const me = this.getMember(this.myUserId);\n if (me) {\n return me.getDMInviter();\n }\n\n if (this.selfMembership === \"invite\") {\n // fall back to summary information\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount === 2) {\n return this.summaryHeroes?.[0];\n }\n }\n }\n\n /**\n * Assuming this room is a DM room, tries to guess with which user.\n * @returns user id of the other member (could be syncing user)\n */\n public guessDMUserId(): string {\n const me = this.getMember(this.myUserId);\n if (me) {\n const inviterId = me.getDMInviter();\n if (inviterId) {\n return inviterId;\n }\n }\n // Remember, we're assuming this room is a DM, so returning the first member we find should be fine\n if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) {\n return this.summaryHeroes[0];\n }\n const members = this.currentState.getMembers();\n const anyMember = members.find((m) => m.userId !== this.myUserId);\n if (anyMember) {\n return anyMember.userId;\n }\n // it really seems like I'm the only user in the room\n // so I probably created a room with just me in it\n // and marked it as a DM. Ok then\n return this.myUserId;\n }\n\n public getAvatarFallbackMember(): RoomMember | undefined {\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount > 2) {\n return;\n }\n const hasHeroes = Array.isArray(this.summaryHeroes) && this.summaryHeroes.length;\n if (hasHeroes) {\n const availableMember = this.summaryHeroes!.map((userId) => {\n return this.getMember(userId);\n }).find((member) => !!member);\n if (availableMember) {\n return availableMember;\n }\n }\n const members = this.currentState.getMembers();\n // could be different than memberCount\n // as this includes left members\n if (members.length <= 2) {\n const availableMember = members.find((m) => {\n return m.userId !== this.myUserId;\n });\n if (availableMember) {\n return availableMember;\n }\n }\n // if all else fails, try falling back to a user,\n // and create a one-off member for it\n if (hasHeroes) {\n const availableUser = this.summaryHeroes!.map((userId) => {\n return this.client.getUser(userId);\n }).find((user) => !!user);\n if (availableUser) {\n const member = new RoomMember(this.roomId, availableUser.userId);\n member.user = availableUser;\n return member;\n }\n }\n }\n\n /**\n * Sets the membership this room was received as during sync\n * @param membership - join | leave | invite\n */\n public updateMyMembership(membership: string): void {\n const prevMembership = this.selfMembership;\n this.selfMembership = membership;\n if (prevMembership !== membership) {\n if (membership === \"leave\") {\n this.cleanupAfterLeaving();\n }\n this.emit(RoomEvent.MyMembership, this, membership, prevMembership);\n }\n }\n\n private async loadMembersFromServer(): Promise {\n const lastSyncToken = this.client.store.getSyncToken();\n const response = await this.client.members(this.roomId, undefined, \"leave\", lastSyncToken ?? undefined);\n return response.chunk;\n }\n\n private async loadMembers(): Promise<{ memberEvents: MatrixEvent[]; fromServer: boolean }> {\n // were the members loaded from the server?\n let fromServer = false;\n let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);\n // If the room is encrypted, we always fetch members from the server at\n // least once, in case the latest state wasn't persisted properly. Note\n // that this function is only called once (unless loading the members\n // fails), since loadMembersIfNeeded always returns this.membersPromise\n // if set, which will be the result of the first (successful) call.\n if (rawMembersEvents === null || (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId))) {\n fromServer = true;\n rawMembersEvents = await this.loadMembersFromServer();\n logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);\n }\n const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());\n return { memberEvents, fromServer };\n }\n\n /**\n * Check if loading of out-of-band-members has completed\n *\n * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).\n * False if the load is not started or is in progress.\n */\n public membersLoaded(): boolean {\n if (!this.opts.lazyLoadMembers) {\n return true;\n }\n\n return this.currentState.outOfBandMembersReady();\n }\n\n /**\n * Preloads the member list in case lazy loading\n * of memberships is in use. Can be called multiple times,\n * it will only preload once.\n * @returns when preloading is done and\n * accessing the members on the room will take\n * all members in the room into account\n */\n public loadMembersIfNeeded(): Promise {\n if (this.membersPromise) {\n return this.membersPromise;\n }\n\n // mark the state so that incoming messages while\n // the request is in flight get marked as superseding\n // the OOB members\n this.currentState.markOutOfBandMembersStarted();\n\n const inMemoryUpdate = this.loadMembers()\n .then((result) => {\n this.currentState.setOutOfBandMembers(result.memberEvents);\n return result.fromServer;\n })\n .catch((err) => {\n // allow retries on fail\n this.membersPromise = undefined;\n this.currentState.markOutOfBandMembersFailed();\n throw err;\n });\n // update members in storage, but don't wait for it\n inMemoryUpdate\n .then((fromServer) => {\n if (fromServer) {\n const oobMembers = this.currentState\n .getMembers()\n .filter((m) => m.isOutOfBand())\n .map((m) => m.events.member?.event as IStateEventWithRoomId);\n logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);\n const store = this.client.store;\n return (\n store\n .setOutOfBandMembers(this.roomId, oobMembers)\n // swallow any IDB error as we don't want to fail\n // because of this\n .catch((err) => {\n logger.log(\"LL: storing OOB room members failed, oh well\", err);\n })\n );\n }\n })\n .catch((err) => {\n // as this is not awaited anywhere,\n // at least show the error in the console\n logger.error(err);\n });\n\n this.membersPromise = inMemoryUpdate;\n\n return this.membersPromise;\n }\n\n /**\n * Removes the lazily loaded members from storage if needed\n */\n public async clearLoadedMembersIfNeeded(): Promise {\n if (this.opts.lazyLoadMembers && this.membersPromise) {\n await this.loadMembersIfNeeded();\n await this.client.store.clearOutOfBandMembers(this.roomId);\n this.currentState.clearOutOfBandMembers();\n this.membersPromise = undefined;\n }\n }\n\n /**\n * called when sync receives this room in the leave section\n * to do cleanup after leaving a room. Possibly called multiple times.\n */\n private cleanupAfterLeaving(): void {\n this.clearLoadedMembersIfNeeded().catch((err) => {\n logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);\n logger.log(err);\n });\n }\n\n /**\n * Empty out the current live timeline and re-request it. This is used when\n * historical messages are imported into the room via MSC2716 `/batch_send`\n * because the client may already have that section of the timeline loaded.\n * We need to force the client to throw away their current timeline so that\n * when they back paginate over the area again with the historical messages\n * in between, it grabs the newly imported messages. We can listen for\n * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready\n * to be discovered in the room and the timeline needs a refresh. The SDK\n * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a\n * valid marker and can check the needs refresh status via\n * `room.getTimelineNeedsRefresh()`.\n */\n public async refreshLiveTimeline(): Promise {\n const liveTimelineBefore = this.getLiveTimeline();\n const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);\n const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);\n const eventsBefore = liveTimelineBefore.getEvents();\n const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] at ` +\n `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +\n `liveTimelineBefore=${liveTimelineBefore.toString()} ` +\n `forwardPaginationToken=${forwardPaginationToken} ` +\n `backwardPaginationToken=${backwardPaginationToken}`,\n );\n\n // Get the main TimelineSet\n const timelineSet = this.getUnfilteredTimelineSet();\n\n let newTimeline: Optional;\n // If there isn't any event in the timeline, let's go fetch the latest\n // event and construct a timeline from it.\n //\n // This should only really happen if the user ran into an error\n // with refreshing the timeline before which left them in a blank\n // timeline from `resetLiveTimeline`.\n if (!mostRecentEventInTimeline) {\n newTimeline = await this.client.getLatestTimeline(timelineSet);\n } else {\n // Empty out all of `this.timelineSets`. But we also need to keep the\n // same `timelineSet` references around so the React code updates\n // properly and doesn't ignore the room events we emit because it checks\n // that the `timelineSet` references are the same. We need the\n // `timelineSet` empty so that the `client.getEventTimeline(...)` call\n // later, will call `/context` and create a new timeline instead of\n // returning the same one.\n this.resetLiveTimeline(null, null);\n\n // Make the UI timeline show the new blank live timeline we just\n // reset so that if the network fails below it's showing the\n // accurate state of what we're working with instead of the\n // disconnected one in the TimelineWindow which is just hanging\n // around by reference.\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n\n // Use `client.getEventTimeline(...)` to construct a new timeline from a\n // `/context` response state and events for the most recent event before\n // we reset everything. The `timelineSet` we pass in needs to be empty\n // in order for this function to call `/context` and generate a new\n // timeline.\n newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()!);\n }\n\n // If a racing `/sync` beat us to creating a new timeline, use that\n // instead because it's the latest in the room and any new messages in\n // the scrollback will include the history.\n const liveTimeline = timelineSet.getLiveTimeline();\n if (\n !liveTimeline ||\n (liveTimeline.getPaginationToken(Direction.Forward) === null &&\n liveTimeline.getPaginationToken(Direction.Backward) === null &&\n liveTimeline.getEvents().length === 0)\n ) {\n logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);\n // Set the pagination token back to the live sync token (`null`) instead\n // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)\n // so that it matches the next response from `/sync` and we can properly\n // continue the timeline.\n newTimeline!.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n\n // Set our new fresh timeline as the live timeline to continue syncing\n // forwards and back paginating from.\n timelineSet.setLiveTimeline(newTimeline!);\n // Fixup `this.oldstate` so that `scrollback` has the pagination tokens\n // available\n this.fixUpLegacyTimelineFields();\n } else {\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] \\`/sync\\` or some other request beat us to creating a new ` +\n `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +\n `this timeline will include the history.`,\n );\n }\n\n // The timeline has now been refreshed ✅\n this.setTimelineNeedsRefresh(false);\n\n // Emit an event which clients can react to and re-load the timeline\n // from the SDK\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * This is used when /sync returns a 'limited' timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {\n for (const timelineSet of this.timelineSets) {\n timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n }\n for (const thread of this.threads.values()) {\n thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);\n }\n\n this.fixUpLegacyTimelineFields();\n }\n\n /**\n * Fix up this.timeline, this.oldState and this.currentState\n *\n * @internal\n */\n private fixUpLegacyTimelineFields(): void {\n const previousOldState = this.oldState;\n const previousCurrentState = this.currentState;\n\n // maintain this.timeline as a reference to the live timeline,\n // and this.oldState and this.currentState as references to the\n // state at the start and end of that timeline. These are more\n // for backwards-compatibility than anything else.\n this.timeline = this.getLiveTimeline().getEvents();\n this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS)!;\n this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n\n // Let people know to register new listeners for the new state\n // references. The reference won't necessarily change every time so only\n // emit when we see a change.\n if (previousOldState !== this.oldState) {\n this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);\n }\n\n if (previousCurrentState !== this.currentState) {\n this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);\n\n // Re-emit various events on the current room state\n // TODO: If currentState really only exists for backwards\n // compatibility, shouldn't we be doing this some other way?\n this.reEmitter.stopReEmitting(previousCurrentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n this.reEmitter.reEmit(this.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n }\n }\n\n /**\n * Returns whether there are any devices in the room that are unverified\n *\n * Note: Callers should first check if crypto is enabled on this device. If it is\n * disabled, then we aren't tracking room devices at all, so we can't answer this, and an\n * error will be thrown.\n *\n * @returns the result\n */\n public async hasUnverifiedDevices(): Promise {\n if (!this.client.isRoomEncrypted(this.roomId)) {\n return false;\n }\n const e2eMembers = await this.getEncryptionTargetMembers();\n for (const member of e2eMembers) {\n const devices = this.client.getStoredDevicesForUser(member.userId);\n if (devices.some((device) => device.isUnverified())) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the timeline sets for this room.\n * @returns array of timeline sets for this room\n */\n public getTimelineSets(): EventTimelineSet[] {\n return this.timelineSets;\n }\n\n /**\n * Helper to return the main unfiltered timeline set for this room\n * @returns room's unfiltered timeline set\n */\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSets[0];\n }\n\n /**\n * Get the timeline which contains the given event from the unfiltered set, if any\n *\n * @param eventId - event ID to look for\n * @returns timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline | null {\n const event = this.findEventById(eventId);\n const thread = this.findThreadForEvent(event);\n if (thread) {\n return thread.timelineSet.getTimelineForEvent(eventId);\n } else {\n return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n }\n }\n\n /**\n * Add a new timeline to this room's unfiltered timeline set\n *\n * @returns newly-created timeline\n */\n public addTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().addTimeline();\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @param value - The value to set\n */\n public setTimelineNeedsRefresh(value: boolean): void {\n this.timelineNeedsRefresh = value;\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @returns .\n */\n public getTimelineNeedsRefresh(): boolean {\n return this.timelineNeedsRefresh;\n }\n\n /**\n * Get an event which is stored in our unfiltered timeline set, or in a thread\n *\n * @param eventId - event ID to look for\n * @returns the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n let event = this.getUnfilteredTimelineSet().findEventById(eventId);\n\n if (!event) {\n const threads = this.getThreads();\n for (let i = 0; i < threads.length; i++) {\n const thread = threads[i];\n event = thread.findEventById(eventId);\n if (event) {\n return event;\n }\n }\n }\n\n return event;\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getUnreadNotificationCount(type = NotificationCountType.Total): number {\n let count = this.getRoomUnreadNotificationCount(type);\n for (const threadNotification of this.threadNotifications.values()) {\n count += threadNotification[type] ?? 0;\n }\n return count;\n }\n\n /**\n * Get the notification for the event context (room or thread timeline)\n */\n public getUnreadCountForEventContext(type = NotificationCountType.Total, event: MatrixEvent): number {\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n return (\n (isThreadEvent\n ? this.getThreadUnreadNotificationCount(event.threadRootId, type)\n : this.getRoomUnreadNotificationCount(type)) ?? 0\n );\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getRoomUnreadNotificationCount(type = NotificationCountType.Total): number {\n return this.notificationCounts[type] ?? 0;\n }\n\n /**\n * Get one of the notification counts for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getThreadUnreadNotificationCount(threadId: string, type = NotificationCountType.Total): number {\n return this.threadNotifications.get(threadId)?.[type] ?? 0;\n }\n\n /**\n * Checks if the current room has unread thread notifications\n * @returns\n */\n public hasThreadUnreadNotification(): boolean {\n for (const notification of this.threadNotifications.values()) {\n if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Swet one of the notification count for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns\n */\n public setThreadUnreadNotificationCount(threadId: string, type: NotificationCountType, count: number): void {\n const notification: NotificationCount = {\n highlight: this.threadNotifications.get(threadId)?.highlight,\n total: this.threadNotifications.get(threadId)?.total,\n ...{\n [type]: count,\n },\n };\n\n this.threadNotifications.set(threadId, notification);\n\n this.emit(RoomEvent.UnreadNotifications, notification, threadId);\n }\n\n /**\n * @returns the notification count type for all the threads in the room\n */\n public get threadsAggregateNotificationType(): NotificationCountType | null {\n let type: NotificationCountType | null = null;\n for (const threadNotification of this.threadNotifications.values()) {\n if ((threadNotification.highlight ?? 0) > 0) {\n return NotificationCountType.Highlight;\n } else if ((threadNotification.total ?? 0) > 0 && !type) {\n type = NotificationCountType.Total;\n }\n }\n return type;\n }\n\n /**\n * Resets the thread notifications for this room\n */\n public resetThreadUnreadNotificationCount(notificationsToKeep?: string[]): void {\n if (notificationsToKeep) {\n for (const [threadId] of this.threadNotifications) {\n if (!notificationsToKeep.includes(threadId)) {\n this.threadNotifications.delete(threadId);\n }\n }\n } else {\n this.threadNotifications.clear();\n }\n this.emit(RoomEvent.UnreadNotifications);\n }\n\n /**\n * Set one of the notification counts for this room\n * @param type - The type of notification count to set.\n * @param count - The new count\n */\n public setUnreadNotificationCount(type: NotificationCountType, count: number): void {\n this.notificationCounts[type] = count;\n this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.setUnreadNotificationCount(type, count);\n }\n\n public setSummary(summary: IRoomSummary): void {\n const heroes = summary[\"m.heroes\"];\n const joinedCount = summary[\"m.joined_member_count\"];\n const invitedCount = summary[\"m.invited_member_count\"];\n if (Number.isInteger(joinedCount)) {\n this.currentState.setJoinedMemberCount(joinedCount!);\n }\n if (Number.isInteger(invitedCount)) {\n this.currentState.setInvitedMemberCount(invitedCount!);\n }\n if (Array.isArray(heroes)) {\n // be cautious about trusting server values,\n // and make sure heroes doesn't contain our own id\n // just to be sure\n this.summaryHeroes = heroes.filter((userId) => {\n return userId !== this.myUserId;\n });\n }\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @param value - true to blacklist unverified devices, null\n * to use the global value for this room.\n */\n public setBlacklistUnverifiedDevices(value: boolean): void {\n this.blacklistUnverifiedDevices = value;\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @returns true if blacklisting unverified devices, null\n * if the global value should be used for this room.\n */\n public getBlacklistUnverifiedDevices(): boolean | null {\n if (this.blacklistUnverifiedDevices === undefined) return null;\n return this.blacklistUnverifiedDevices;\n }\n\n /**\n * Get the avatar URL for a room if one was set.\n * @param baseUrl - The homeserver base URL. See\n * {@link MatrixClient#getHomeserverUrl}.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDefault - True to allow an identicon for this room if an\n * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n * @returns the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: ResizeMethod,\n allowDefault = true,\n ): string | null {\n const roomAvatarEvent = this.currentState.getStateEvents(EventType.RoomAvatar, \"\");\n if (!roomAvatarEvent && !allowDefault) {\n return null;\n }\n\n const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;\n if (mainUrl) {\n return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);\n }\n\n return null;\n }\n\n /**\n * Get the mxc avatar url for the room, if one was set.\n * @returns the mxc avatar url or falsy\n */\n public getMxcAvatarUrl(): string | null {\n return this.currentState.getStateEvents(EventType.RoomAvatar, \"\")?.getContent()?.url || null;\n }\n\n /**\n * Get this room's canonical alias\n * The alias returned by this function may not necessarily\n * still point to this room.\n * @returns The room's canonical alias, or null if there is none\n */\n public getCanonicalAlias(): string | null {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alias || null;\n }\n return null;\n }\n\n /**\n * Get this room's alternative aliases\n * @returns The room's alternative aliases, or an empty array\n */\n public getAltAliases(): string[] {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alt_aliases || [];\n }\n return [];\n }\n\n /**\n * Add events to a timeline\n *\n * Will fire \"Room.timeline\" for each event added.\n *\n * @param events - A list of events to add.\n *\n * @param toStartOfTimeline - True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the last element of 'events'.\n *\n * @param timeline - timeline to\n * add events to.\n *\n * @param paginationToken - token for the next batch of events\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string,\n ): void {\n timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);\n }\n\n /**\n * Get the instance of the thread associated with the current event\n * @param eventId - the ID of the current event\n * @returns a thread instance if known\n */\n public getThread(eventId: string): Thread | null {\n return this.threads.get(eventId) ?? null;\n }\n\n /**\n * Get all the known threads in the room\n */\n public getThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get a member from the current room state.\n * @param userId - The user ID of the member.\n * @returns The member or `null`.\n */\n public getMember(userId: string): RoomMember | null {\n return this.currentState.getMember(userId);\n }\n\n /**\n * Get all currently loaded members from the current\n * room state.\n * @returns Room members\n */\n public getMembers(): RoomMember[] {\n return this.currentState.getMembers();\n }\n\n /**\n * Get a list of members whose membership state is \"join\".\n * @returns A list of currently joined members.\n */\n public getJoinedMembers(): RoomMember[] {\n return this.getMembersWithMembership(\"join\");\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * This is a wrapper around the method of the same name in roomState, returning\n * its result for the room's current state.\n * @returns The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n return this.currentState.getJoinedMemberCount();\n }\n\n /**\n * Returns the number of invited members in this room\n * @returns The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n return this.currentState.getInvitedMemberCount();\n }\n\n /**\n * Returns the number of invited + joined members in this room\n * @returns The number of members in this room whose membership is 'invite' or 'join'\n */\n public getInvitedAndJoinedMemberCount(): number {\n return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n }\n\n /**\n * Get a list of members with given membership state.\n * @param membership - The membership state.\n * @returns A list of members with the given membership state.\n */\n public getMembersWithMembership(membership: string): RoomMember[] {\n return this.currentState.getMembers().filter(function (m) {\n return m.membership === membership;\n });\n }\n\n /**\n * Get a list of members we should be encrypting for in this room\n * @returns A list of members who\n * we should encrypt messages for in this room.\n */\n public async getEncryptionTargetMembers(): Promise {\n await this.loadMembersIfNeeded();\n let members = this.getMembersWithMembership(\"join\");\n if (this.shouldEncryptForInvitedMembers()) {\n members = members.concat(this.getMembersWithMembership(\"invite\"));\n }\n return members;\n }\n\n /**\n * Determine whether we should encrypt messages for invited users in this room\n * @returns if we should encrypt messages for invited users\n */\n public shouldEncryptForInvitedMembers(): boolean {\n const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n return ev?.getContent()?.history_visibility !== \"joined\";\n }\n\n /**\n * Get the default room name (i.e. what a given user would see if the\n * room had no m.room.name)\n * @param userId - The userId from whose perspective we want\n * to calculate the default name\n * @returns The default room name\n */\n public getDefaultRoomName(userId: string): string {\n return this.calculateRoomName(userId, true);\n }\n\n /**\n * Check if the given user_id has the given membership state.\n * @param userId - The user ID to check.\n * @param membership - The membership e.g. `'join'`\n * @returns True if this user_id has the given membership state.\n */\n public hasMembershipState(userId: string, membership: string): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n return member.membership === membership;\n }\n\n /**\n * Add a timelineSet for this room with the given filter\n * @param filter - The filter to be applied to this timelineSet\n * @param opts - Configuration options\n * @returns The timelineSet\n */\n public getOrCreateFilteredTimelineSet(\n filter: Filter,\n { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true }: ICreateFilterOpts = {},\n ): EventTimelineSet {\n if (this.filteredTimelineSets[filter.filterId!]) {\n return this.filteredTimelineSets[filter.filterId!];\n }\n const opts = Object.assign({ filter, pendingEvents }, this.opts);\n const timelineSet = new EventTimelineSet(this, opts);\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n if (useSyncEvents) {\n this.filteredTimelineSets[filter.filterId!] = timelineSet;\n this.timelineSets.push(timelineSet);\n }\n\n const unfilteredLiveTimeline = this.getLiveTimeline();\n // Not all filter are possible to replicate client-side only\n // When that's the case we do not want to prepopulate from the live timeline\n // as we would get incorrect results compared to what the server would send back\n if (prepopulateTimeline) {\n // populate up the new timelineSet with filtered events from our live\n // unfiltered timeline.\n //\n // XXX: This is risky as our timeline\n // may have grown huge and so take a long time to filter.\n // see https://github.com/vector-im/vector-web/issues/2109\n\n unfilteredLiveTimeline.getEvents().forEach(function (event) {\n timelineSet.addLiveEvent(event);\n });\n\n // find the earliest unfiltered timeline\n let timeline = unfilteredLiveTimeline;\n while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)!;\n }\n\n timelineSet\n .getLiveTimeline()\n .setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);\n } else if (useSyncEvents) {\n const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);\n timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);\n }\n\n // alternatively, we could try to do something like this to try and re-paginate\n // in the filtered events from nothing, but Mark says it's an abuse of the API\n // to do so:\n //\n // timelineSet.resetLiveTimeline(\n // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n // );\n\n return timelineSet;\n }\n\n private async getThreadListFilter(filterType = ThreadFilterType.All): Promise {\n const myUserId = this.client.getUserId()!;\n const filter = new Filter(myUserId);\n\n const definition: IFilterDefinition = {\n room: {\n timeline: {\n [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name],\n },\n },\n };\n\n if (filterType === ThreadFilterType.My) {\n definition!.room!.timeline![FILTER_RELATED_BY_SENDERS.name] = [myUserId];\n }\n\n filter.setDefinition(definition);\n const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);\n\n filter.filterId = filterId;\n\n return filter;\n }\n\n private async createThreadTimelineSet(filterType?: ThreadFilterType): Promise {\n let timelineSet: EventTimelineSet;\n if (Thread.hasServerSideListSupport) {\n timelineSet = new EventTimelineSet(\n this,\n {\n ...this.opts,\n pendingEvents: false,\n },\n undefined,\n undefined,\n filterType ?? ThreadFilterType.All,\n );\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n } else if (Thread.hasServerSideSupport) {\n const filter = await this.getThreadListFilter(filterType);\n\n timelineSet = this.getOrCreateFilteredTimelineSet(filter, {\n prepopulateTimeline: false,\n useSyncEvents: false,\n pendingEvents: false,\n });\n } else {\n timelineSet = new EventTimelineSet(this, {\n pendingEvents: false,\n });\n\n Array.from(this.threads).forEach(([, thread]) => {\n if (thread.length === 0) return;\n const currentUserParticipated = thread.timeline.some((event) => {\n return event.getSender() === this.client.getUserId();\n });\n if (filterType !== ThreadFilterType.My || currentUserParticipated) {\n timelineSet.getLiveTimeline().addEvent(thread.rootEvent!, {\n toStartOfTimeline: false,\n });\n }\n });\n }\n\n return timelineSet;\n }\n\n private threadsReady = false;\n\n /**\n * Takes the given thread root events and creates threads for them.\n */\n public processThreadRoots(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n for (const rootEvent of events) {\n EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);\n if (!this.getThread(rootEvent.getId()!)) {\n this.createThread(rootEvent.getId()!, rootEvent, [], toStartOfTimeline);\n }\n }\n }\n\n /**\n * Fetch the bare minimum of room threads required for the thread list to work reliably.\n * With server support that means fetching one page.\n * Without server support that means fetching as much at once as the server allows us to.\n */\n public async fetchRoomThreads(): Promise {\n if (this.threadsReady || !this.client.supportsThreads()) {\n return;\n }\n\n if (Thread.hasServerSideListSupport) {\n await Promise.all([\n this.fetchRoomThreadList(ThreadFilterType.All),\n this.fetchRoomThreadList(ThreadFilterType.My),\n ]);\n } else {\n const allThreadsFilter = await this.getThreadListFilter();\n\n const { chunk: events } = await this.client.createMessagesRequest(\n this.roomId,\n \"\",\n Number.MAX_SAFE_INTEGER,\n Direction.Backward,\n allThreadsFilter,\n );\n\n if (!events.length) return;\n\n // Sorted by last_reply origin_server_ts\n const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {\n /**\n * `origin_server_ts` in a decentralised world is far from ideal\n * but for lack of any better, we will have to use this\n * Long term the sorting should be handled by homeservers and this\n * is only meant as a short term patch\n */\n const threadAMetadata = eventA.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n )!;\n const threadBMetadata = eventB.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n )!;\n return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;\n });\n\n let latestMyThreadsRootEvent: MatrixEvent | undefined;\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of threadRoots) {\n const opts = {\n duplicateStrategy: DuplicateStrategy.Ignore,\n fromCache: false,\n roomState,\n };\n this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);\n\n const threadRelationship = rootEvent.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n );\n if (threadRelationship?.current_user_participated) {\n this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);\n latestMyThreadsRootEvent = rootEvent;\n }\n }\n\n this.processThreadRoots(threadRoots, true);\n\n this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);\n if (latestMyThreadsRootEvent) {\n this.client.decryptEventIfNeeded(latestMyThreadsRootEvent);\n }\n }\n\n this.on(ThreadEvent.NewReply, this.onThreadNewReply);\n this.on(ThreadEvent.Delete, this.onThreadDelete);\n this.threadsReady = true;\n }\n\n public async processPollEvents(events: MatrixEvent[]): Promise {\n const processPollStartEvent = (event: MatrixEvent): void => {\n if (!M_POLL_START.matches(event.getType())) return;\n try {\n const poll = new Poll(event, this.client, this);\n this.polls.set(event.getId()!, poll);\n this.emit(PollEvent.New, poll);\n } catch {}\n // poll creation can fail for malformed poll start events\n };\n\n const processPollRelationEvent = (event: MatrixEvent): void => {\n const relationEventId = event.relationEventId;\n if (relationEventId && this.polls.has(relationEventId)) {\n const poll = this.polls.get(relationEventId);\n poll?.onNewRelation(event);\n }\n };\n\n const processPollEvent = (event: MatrixEvent): void => {\n processPollStartEvent(event);\n processPollRelationEvent(event);\n };\n\n for (const event of events) {\n try {\n await this.client.decryptEventIfNeeded(event);\n processPollEvent(event);\n } catch {}\n }\n }\n\n /**\n * Fetch a single page of threadlist messages for the specific thread filter\n * @internal\n */\n private async fetchRoomThreadList(filter?: ThreadFilterType): Promise {\n const timelineSet = filter === ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];\n\n const { chunk: events, end } = await this.client.createThreadListMessagesRequest(\n this.roomId,\n null,\n undefined,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n\n timelineSet.getLiveTimeline().setPaginationToken(end ?? null, Direction.Backward);\n\n if (!events.length) return;\n\n const matrixEvents = events.map(this.client.getEventMapper());\n this.processThreadRoots(matrixEvents, true);\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of matrixEvents) {\n timelineSet.addLiveEvent(rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState,\n });\n }\n }\n\n private onThreadNewReply(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, true);\n }\n\n private onThreadDelete(thread: Thread): void {\n this.threads.delete(thread.id);\n\n const timeline = this.getTimelineForEvent(thread.id);\n const roomEvent = timeline?.getEvents()?.find((it) => it.getId() === thread.id);\n if (roomEvent) {\n thread.clearEventMetadata(roomEvent);\n } else {\n logger.debug(\"onThreadDelete: Could not find root event in room timeline\");\n }\n for (const timelineSet of this.threadsTimelineSets) {\n timelineSet.removeEvent(thread.id);\n }\n }\n\n /**\n * Forget the timelineSet for this room with the given filter\n *\n * @param filter - the filter whose timelineSet is to be forgotten\n */\n public removeFilteredTimelineSet(filter: Filter): void {\n const timelineSet = this.filteredTimelineSets[filter.filterId!];\n delete this.filteredTimelineSets[filter.filterId!];\n const i = this.timelineSets.indexOf(timelineSet);\n if (i > -1) {\n this.timelineSets.splice(i, 1);\n }\n }\n\n public eventShouldLiveIn(\n event: MatrixEvent,\n events?: MatrixEvent[],\n roots?: Set,\n ): {\n shouldLiveInRoom: boolean;\n shouldLiveInThread: boolean;\n threadId?: string;\n } {\n if (!this.client?.supportsThreads()) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // A thread root is always shown in both timelines\n if (event.isThreadRoot || roots?.has(event.getId()!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.getId(),\n };\n }\n\n // A thread relation is always only shown in a thread\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: true,\n threadId: event.threadRootId,\n };\n }\n\n const parentEventId = event.getAssociatedId();\n let parentEvent: MatrixEvent | undefined;\n if (parentEventId) {\n parentEvent = this.findEventById(parentEventId) ?? events?.find((e) => e.getId() === parentEventId);\n }\n\n // Treat relations and redactions as extensions of their parents so evaluate parentEvent instead\n if (parentEvent && (event.isRelation() || event.isRedaction())) {\n return this.eventShouldLiveIn(parentEvent, events, roots);\n }\n\n // Edge case where we know the event is a relation but don't have the parentEvent\n if (roots?.has(event.relationEventId!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.relationEventId,\n };\n }\n\n // We've exhausted all scenarios, can safely assume that this event should live in the room timeline only\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n public findThreadForEvent(event?: MatrixEvent): Thread | null {\n if (!event) return null;\n\n const { threadId } = this.eventShouldLiveIn(event);\n return threadId ? this.getThread(threadId) : null;\n }\n\n private addThreadedEvents(threadId: string, events: MatrixEvent[], toStartOfTimeline = false): void {\n let thread = this.getThread(threadId);\n\n if (!thread) {\n const rootEvent = this.findEventById(threadId) ?? events.find((e) => e.getId() === threadId);\n thread = this.createThread(threadId, rootEvent, events, toStartOfTimeline);\n }\n\n thread.addEvents(events, toStartOfTimeline);\n }\n\n /**\n * Adds events to a thread's timeline. Will fire \"Thread.update\"\n */\n public processThreadedEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach(this.applyRedaction);\n\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n for (const event of events) {\n const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);\n if (shouldLiveInThread && !eventsByThread[threadId!]) {\n eventsByThread[threadId!] = [];\n }\n eventsByThread[threadId!]?.push(event);\n }\n\n Object.entries(eventsByThread).map(([threadId, threadEvents]) =>\n this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline),\n );\n }\n\n private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean, recreateEvent: boolean): void => {\n if (thread.length) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);\n if (thread.hasCurrentUserParticipated) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);\n }\n }\n };\n\n private updateThreadRootEvent = (\n timelineSet: Optional,\n thread: Thread,\n toStartOfTimeline: boolean,\n recreateEvent: boolean,\n ): void => {\n if (timelineSet && thread.rootEvent) {\n if (recreateEvent) {\n timelineSet.removeEvent(thread.id);\n }\n if (Thread.hasServerSideSupport) {\n timelineSet.addLiveEvent(thread.rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState: this.currentState,\n });\n } else {\n timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline });\n }\n }\n };\n\n public createThread(\n threadId: string,\n rootEvent: MatrixEvent | undefined,\n events: MatrixEvent[] = [],\n toStartOfTimeline: boolean,\n ): Thread {\n if (this.threads.has(threadId)) {\n return this.threads.get(threadId)!;\n }\n\n if (rootEvent) {\n const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()!);\n if (relatedEvents?.length) {\n // Include all relations of the root event, given it'll be visible in both timelines,\n // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`\n events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));\n }\n }\n\n const thread = new Thread(threadId, rootEvent, {\n room: this,\n client: this.client,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n receipts: this.cachedThreadReadReceipts.get(threadId) ?? [],\n });\n\n // All read receipts should now come down from sync, we do not need to keep\n // a reference to the cached receipts anymore.\n this.cachedThreadReadReceipts.delete(threadId);\n\n // If we managed to create a thread and figure out its `id` then we can use it\n // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the\n // eventtimeline sometimes looks up thread information via the room.\n this.threads.set(thread.id, thread);\n\n // This is necessary to be able to jump to events in threads:\n // If we jump to an event in a thread where neither the event, nor the root,\n // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,\n // and pass the event through this.\n thread.addEvents(events, false);\n\n this.reEmitter.reEmit(thread, [\n ThreadEvent.Delete,\n ThreadEvent.Update,\n ThreadEvent.NewReply,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n const isNewer =\n this.lastThread?.rootEvent &&\n rootEvent?.localTimestamp &&\n this.lastThread.rootEvent?.localTimestamp < rootEvent?.localTimestamp;\n\n if (!this.lastThread || isNewer) {\n this.lastThread = thread;\n }\n\n if (this.threadsReady) {\n this.updateThreadRootEvents(thread, toStartOfTimeline, false);\n }\n this.emit(ThreadEvent.New, thread, toStartOfTimeline);\n\n return thread;\n }\n\n private applyRedaction = (event: MatrixEvent): void => {\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n\n // if we know about this event, redact its contents now.\n const redactedEvent = redactId ? this.findEventById(redactId) : undefined;\n if (redactedEvent) {\n redactedEvent.makeRedacted(event);\n\n // If this is in the current state, replace it with the redacted version\n if (redactedEvent.isState()) {\n const currentStateEvent = this.currentState.getStateEvents(\n redactedEvent.getType(),\n redactedEvent.getStateKey()!,\n );\n if (currentStateEvent?.getId() === redactedEvent.getId()) {\n this.currentState.setStateEvents([redactedEvent]);\n }\n }\n\n this.emit(RoomEvent.Redaction, event, this);\n\n // TODO: we stash user displaynames (among other things) in\n // RoomMember objects which are then attached to other events\n // (in the sender and target fields). We should get those\n // RoomMember objects to update themselves when the events that\n // they are based on are changed.\n\n // Remove any visibility change on this event.\n this.visibilityEvents.delete(redactId!);\n\n // If this event is a visibility change event, remove it from the\n // list of visibility changes and update any event affected by it.\n if (redactedEvent.isVisibilityEvent()) {\n this.redactVisibilityChangeEvent(event);\n }\n }\n\n // FIXME: apply redactions to notification list\n\n // NB: We continue to add the redaction event to the timeline so\n // clients can say \"so and so redacted an event\" if they wish to. Also\n // this may be needed to trigger an update.\n }\n };\n\n private processLiveEvent(event: MatrixEvent): void {\n this.applyRedaction(event);\n\n // Implement MSC3531: hiding messages.\n if (event.isVisibilityEvent()) {\n // This event changes the visibility of another event, record\n // the visibility change, inform clients if necessary.\n this.applyNewVisibilityEvent(event);\n }\n // If any pending visibility change is waiting for this (older) event,\n this.applyPendingVisibilityEvents(event);\n\n // Sliding Sync modifications:\n // The proxy cannot guarantee every sent event will have a transaction_id field, so we need\n // to check the event ID against the list of pending events if there is no transaction ID\n // field. Only do this for events sent by us though as it's potentially expensive to loop\n // the pending events map.\n const txnId = event.getUnsigned().transaction_id;\n if (!txnId && event.getSender() === this.myUserId) {\n // check the txn map for a matching event ID\n for (const [tid, localEvent] of this.txnToEvent) {\n if (localEvent.getId() === event.getId()) {\n logger.debug(\"processLiveEvent: found sent event without txn ID: \", tid, event.getId());\n // update the unsigned field so we can re-use the same codepaths\n const unsigned = event.getUnsigned();\n unsigned.transaction_id = tid;\n event.setUnsigned(unsigned);\n break;\n }\n }\n }\n }\n\n /**\n * Add an event to the end of this room's live timelines. Will fire\n * \"Room.timeline\".\n *\n * @param event - Event to be added\n * @param addLiveEventOptions - addLiveEvent options\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n private addLiveEvent(event: MatrixEvent, addLiveEventOptions: IAddLiveEventOptions): void {\n const { duplicateStrategy, timelineWasEmpty, fromCache } = addLiveEventOptions;\n\n // add to our timeline sets\n for (const timelineSet of this.timelineSets) {\n timelineSet.addLiveEvent(event, {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n });\n }\n\n // synthesize and inject implicit read receipts\n // Done after adding the event because otherwise the app would get a read receipt\n // pointing to an event that wasn't yet in the timeline\n // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n if (event.sender && event.getType() !== EventType.RoomRedaction) {\n this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);\n\n // Any live events from a user could be taken as implicit\n // presence information: evidence that they are currently active.\n // ...except in a world where we use 'user.currentlyActive' to reduce\n // presence spam, this isn't very useful - we'll get a transition when\n // they are no longer currently active anyway. So don't bother to\n // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n }\n }\n\n /**\n * Add a pending outgoing event to this room.\n *\n * The event is added to either the pendingEventList, or the live timeline,\n * depending on the setting of opts.pendingEventOrdering.\n *\n *
This is an internal method, intended for use by MatrixClient.\n *\n * @param event - The event to add.\n *\n * @param txnId - Transaction id for this outgoing event\n *\n * @throws if the event doesn't have status SENDING, or we aren't given a\n * unique transaction id.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public addPendingEvent(event: MatrixEvent, txnId: string): void {\n if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n throw new Error(\"addPendingEvent called on an event with status \" + event.status);\n }\n\n if (this.txnToEvent.get(txnId)) {\n throw new Error(\"addPendingEvent called on an event with known txnId \" + txnId);\n }\n\n // call setEventMetadata to set up event.sender etc\n // as event is shared over all timelineSets, we set up its metadata based\n // on the unfiltered timelineSet.\n EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS)!, false);\n\n this.txnToEvent.set(txnId, event);\n if (this.pendingEventList) {\n if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {\n logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n event.setStatus(EventStatus.NOT_SENT);\n }\n this.pendingEventList.push(event);\n this.savePendingEvents();\n if (event.isRelation()) {\n // For pending events, add them to the relations collection immediately.\n // (The alternate case below already covers this as part of adding to\n // the timeline set.)\n this.aggregateNonLiveRelation(event);\n }\n\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n let redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);\n if (!redactedEvent && redactId) {\n redactedEvent = this.findEventById(redactId);\n }\n if (redactedEvent) {\n redactedEvent.markLocallyRedacted(event);\n this.emit(RoomEvent.Redaction, event, this);\n }\n }\n } else {\n for (const timelineSet of this.timelineSets) {\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter()!.filterRoomTimeline([event]).length) {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n } else {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this);\n }\n\n /**\n * Persists all pending events to local storage\n *\n * If the current room is encrypted only encrypted events will be persisted\n * all messages that are not yet encrypted will be discarded\n *\n * This is because the flow of EVENT_STATUS transition is\n * `queued => sending => encrypting => sending => sent`\n *\n * Steps 3 and 4 are skipped for unencrypted room.\n * It is better to discard an unencrypted message rather than persisting\n * it locally for everyone to read\n */\n private savePendingEvents(): void {\n if (this.pendingEventList) {\n const pendingEvents = this.pendingEventList\n .map((event) => {\n return {\n ...event.event,\n txn_id: event.getTxnId(),\n };\n })\n .filter((event) => {\n // Filter out the unencrypted messages if the room is encrypted\n const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId);\n return isEventEncrypted || !isRoomEncrypted;\n });\n\n this.client.store.setPendingEvents(this.roomId, pendingEvents);\n }\n }\n\n /**\n * Used to aggregate the local echo for a relation, and also\n * for re-applying a relation after it's redaction has been cancelled,\n * as the local echo for the redaction of the relation would have\n * un-aggregated the relation. Note that this is different from regular messages,\n * which are just kept detached for their local echo.\n *\n * Also note that live events are aggregated in the live EventTimelineSet.\n * @param event - the relation event that needs to be aggregated.\n */\n private aggregateNonLiveRelation(event: MatrixEvent): void {\n this.relations.aggregateChildEvent(event);\n }\n\n public getEventForTxnId(txnId: string): MatrixEvent | undefined {\n return this.txnToEvent.get(txnId);\n }\n\n /**\n * Deal with the echo of a message we sent.\n *\n *
We move the event to the live timeline if it isn't there already, and\n * update it.\n *\n * @param remoteEvent - The event received from\n * /sync\n * @param localEvent - The local echo, which\n * should be either in the pendingEventList or the timeline.\n *\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public handleRemoteEcho(remoteEvent: MatrixEvent, localEvent: MatrixEvent): void {\n const oldEventId = localEvent.getId()!;\n const newEventId = remoteEvent.getId()!;\n const oldStatus = localEvent.status;\n\n logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);\n\n // no longer pending\n this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id!);\n\n // if it's in the pending list, remove it\n if (this.pendingEventList) {\n this.removePendingEvent(oldEventId);\n }\n\n // replace the event source (this will preserve the plaintext payload if\n // any, which is good, because we don't want to try decoding it again).\n localEvent.handleRemoteEcho(remoteEvent.event);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);\n const thread = threadId ? this.getThread(threadId) : null;\n thread?.setEventMetadata(localEvent);\n thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n\n if (shouldLiveInRoom) {\n for (const timelineSet of this.timelineSets) {\n // if it's already in the timeline, update the timeline map. If it's not, add it.\n timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);\n }\n\n /**\n * Update the status / event id on a pending event, to reflect its transmission\n * progress.\n *\n *
This is an internal method.\n *\n * @param event - local echo event\n * @param newStatus - status to assign\n * @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId?: string): void {\n logger.log(\n `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +\n `event ID ${event.getId()} -> ${newEventId}`,\n );\n\n // if the message was sent, we expect an event id\n if (newStatus == EventStatus.SENT && !newEventId) {\n throw new Error(\"updatePendingEvent called with status=SENT, but no new event id\");\n }\n\n // SENT races against /sync, so we have to special-case it.\n if (newStatus == EventStatus.SENT) {\n const timeline = this.getTimelineForEvent(newEventId!);\n if (timeline) {\n // we've already received the event via the event stream.\n // nothing more to do here, assuming the transaction ID was correctly matched.\n // Let's check that.\n const remoteEvent = this.findEventById(newEventId!);\n const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;\n if (!remoteTxnId && remoteEvent) {\n // This code path is mostly relevant for the Sliding Sync proxy.\n // The remote event did not contain a transaction ID, so we did not handle\n // the remote echo yet. Handle it now.\n const unsigned = remoteEvent.getUnsigned();\n unsigned.transaction_id = event.getTxnId();\n remoteEvent.setUnsigned(unsigned);\n // the remote event is _already_ in the timeline, so we need to remove it so\n // we can convert the local event into the final event.\n this.removeEvent(remoteEvent.getId()!);\n this.handleRemoteEcho(remoteEvent, event);\n }\n return;\n }\n }\n\n const oldStatus = event.status;\n const oldEventId = event.getId()!;\n\n if (!oldStatus) {\n throw new Error(\"updatePendingEventStatus called on an event which is not a local echo.\");\n }\n\n const allowed = ALLOWED_TRANSITIONS[oldStatus];\n if (!allowed?.includes(newStatus)) {\n throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);\n }\n\n event.setStatus(newStatus);\n\n if (newStatus == EventStatus.SENT) {\n // update the event id\n event.replaceLocalEventId(newEventId!);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);\n const thread = threadId ? this.getThread(threadId) : undefined;\n thread?.setEventMetadata(event);\n thread?.timelineSet.replaceEventId(oldEventId, newEventId!);\n\n if (shouldLiveInRoom) {\n // if the event was already in the timeline (which will be the case if\n // opts.pendingEventOrdering==chronological), we need to update the\n // timeline map.\n for (const timelineSet of this.timelineSets) {\n timelineSet.replaceEventId(oldEventId, newEventId!);\n }\n }\n } else if (newStatus == EventStatus.CANCELLED) {\n // remove it from the pending event list, or the timeline.\n if (this.pendingEventList) {\n const removedEvent = this.getPendingEvent(oldEventId);\n this.removePendingEvent(oldEventId);\n if (removedEvent?.isRedaction()) {\n this.revertRedactionLocalEcho(removedEvent);\n }\n }\n this.removeEvent(oldEventId);\n }\n this.savePendingEvents();\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);\n }\n\n private revertRedactionLocalEcho(redactionEvent: MatrixEvent): void {\n const redactId = redactionEvent.event.redacts;\n if (!redactId) {\n return;\n }\n const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.unmarkLocallyRedacted();\n // re-render after undoing redaction\n this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);\n // reapply relation now redaction failed\n if (redactedEvent.isRelation()) {\n this.aggregateNonLiveRelation(redactedEvent);\n }\n }\n }\n\n /**\n * Add some events to this room. This can include state events, message\n * events and typing notifications. These events are treated as \"live\" so\n * they will go to the end of the timeline.\n *\n * @param events - A list of events to add.\n * @param addLiveEventOptions - addLiveEvent options\n * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.\n */\n public addLiveEvents(events: MatrixEvent[], addLiveEventOptions?: IAddLiveEventOptions): void;\n /**\n * @deprecated In favor of the overload with `IAddLiveEventOptions`\n */\n public addLiveEvents(events: MatrixEvent[], duplicateStrategy?: DuplicateStrategy, fromCache?: boolean): void;\n public addLiveEvents(\n events: MatrixEvent[],\n duplicateStrategyOrOpts?: DuplicateStrategy | IAddLiveEventOptions,\n fromCache = false,\n ): void {\n let duplicateStrategy: DuplicateStrategy | undefined = duplicateStrategyOrOpts as DuplicateStrategy;\n let timelineWasEmpty: boolean | undefined = false;\n if (typeof duplicateStrategyOrOpts === \"object\") {\n ({\n duplicateStrategy,\n fromCache = false,\n /* roomState, (not used here) */\n timelineWasEmpty,\n } = duplicateStrategyOrOpts);\n } else if (duplicateStrategyOrOpts !== undefined) {\n // Deprecation warning\n // FIXME: Remove after 2023-06-01 (technical debt)\n logger.warn(\n \"Overload deprecated: \" +\n \"`Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` \" +\n \"is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`\",\n );\n }\n\n if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n }\n\n // sanity check that the live timeline is still live\n for (let i = 0; i < this.timelineSets.length; i++) {\n const liveTimeline = this.timelineSets[i].getLiveTimeline();\n if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" +\n i +\n \" is no longer live - it has a pagination token \" +\n \"(\" +\n liveTimeline.getPaginationToken(EventTimeline.FORWARDS) +\n \")\",\n );\n }\n if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);\n }\n }\n\n const threadRoots = this.findThreadRoots(events);\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n\n const options: IAddLiveEventOptions = {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n };\n\n for (const event of events) {\n // TODO: We should have a filter to say \"only add state event types X Y Z to the timeline\".\n this.processLiveEvent(event);\n\n if (event.getUnsigned().transaction_id) {\n const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id!);\n if (existingEvent) {\n // remote echo of an event we sent earlier\n this.handleRemoteEcho(event, existingEvent);\n continue; // we can skip adding the event to the timeline sets, it is already there\n }\n }\n\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInThread && !eventsByThread[threadId ?? \"\"]) {\n eventsByThread[threadId ?? \"\"] = [];\n }\n eventsByThread[threadId ?? \"\"]?.push(event);\n\n if (shouldLiveInRoom) {\n this.addLiveEvent(event, options);\n }\n }\n\n Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {\n this.addThreadedEvents(threadId, threadEvents, false);\n });\n }\n\n public partitionThreadedEvents(\n events: MatrixEvent[],\n ): [timelineEvents: MatrixEvent[], threadedEvents: MatrixEvent[]] {\n // Indices to the events array, for readability\n const ROOM = 0;\n const THREAD = 1;\n if (this.client.supportsThreads()) {\n const threadRoots = this.findThreadRoots(events);\n return events.reduce(\n (memo, event: MatrixEvent) => {\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInRoom) {\n memo[ROOM].push(event);\n }\n\n if (shouldLiveInThread) {\n event.setThreadId(threadId ?? \"\");\n memo[THREAD].push(event);\n }\n\n return memo;\n },\n [[] as MatrixEvent[], [] as MatrixEvent[]],\n );\n } else {\n // When `experimentalThreadSupport` is disabled treat all events as timelineEvents\n return [events as MatrixEvent[], [] as MatrixEvent[]];\n }\n }\n\n /**\n * Given some events, find the IDs of all the thread roots that are referred to by them.\n */\n private findThreadRoots(events: MatrixEvent[]): Set {\n const threadRoots = new Set();\n for (const event of events) {\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n threadRoots.add(event.relationEventId ?? \"\");\n }\n }\n return threadRoots;\n }\n\n /**\n * Add a receipt event to the room.\n * @param event - The m.receipt event.\n * @param synthetic - True if this event is implicit.\n */\n public addReceipt(event: MatrixEvent, synthetic = false): void {\n const content = event.getContent();\n Object.keys(content).forEach((eventId: string) => {\n Object.keys(content[eventId]).forEach((receiptType: ReceiptType | string) => {\n Object.keys(content[eventId][receiptType]).forEach((userId: string) => {\n const receipt = content[eventId][receiptType][userId] as Receipt;\n const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;\n const receiptDestination: Thread | this | undefined = receiptForMainTimeline\n ? this\n : this.threads.get(receipt.thread_id ?? \"\");\n\n if (receiptDestination) {\n receiptDestination.addReceiptToStructure(\n eventId,\n receiptType as ReceiptType,\n userId,\n receipt,\n synthetic,\n );\n\n // If the read receipt sent for the logged in user matches\n // the last event of the live timeline, then we know for a fact\n // that the user has read that message.\n // We can mark the room as read and not wait for the local echo\n // from synapse\n // This needs to be done after the initial sync as we do not want this\n // logic to run whilst the room is being initialised\n if (this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {\n const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];\n if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n receiptDestination.setUnread(NotificationCountType.Total, 0);\n receiptDestination.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n } else {\n // The thread does not exist locally, keep the read receipt\n // in a cache locally, and re-apply the `addReceipt` logic\n // when the thread is created\n this.cachedThreadReadReceipts.set(receipt.thread_id!, [\n ...(this.cachedThreadReadReceipts.get(receipt.thread_id!) ?? []),\n { eventId, receiptType, userId, receipt, synthetic },\n ]);\n }\n\n const me = this.client.getUserId();\n // Track the time of the current user's oldest threaded receipt in the room.\n if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {\n this.oldestThreadedReceiptTs = receipt.ts;\n }\n\n // Track each user's unthreaded read receipt.\n if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {\n this.unthreadedReceipts.set(userId, receipt);\n }\n });\n });\n });\n\n // send events after we've regenerated the structure & cache, otherwise things that\n // listened for the event would read stale data.\n this.emit(RoomEvent.Receipt, event, this);\n }\n\n /**\n * Adds/handles ephemeral events such as typing notifications and read receipts.\n * @param events - A list of events to process\n */\n public addEphemeralEvents(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === EventType.Typing) {\n this.currentState.setTypingEvent(event);\n } else if (event.getType() === EventType.Receipt) {\n this.addReceipt(event);\n } // else ignore - life is too short for us to care about these events\n }\n }\n\n /**\n * Removes events from this room.\n * @param eventIds - A list of eventIds to remove.\n */\n public removeEvents(eventIds: string[]): void {\n for (const eventId of eventIds) {\n this.removeEvent(eventId);\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param eventId - The id of the event to remove\n *\n * @returns true if the event was removed from any of the room's timeline sets\n */\n public removeEvent(eventId: string): boolean {\n let removedAny = false;\n for (const timelineSet of this.timelineSets) {\n const removed = timelineSet.removeEvent(eventId);\n if (removed) {\n if (removed.isRedaction()) {\n this.revertRedactionLocalEcho(removed);\n }\n removedAny = true;\n }\n }\n return removedAny;\n }\n\n /**\n * Recalculate various aspects of the room, including the room name and\n * room summary. Call this any time the room's current state is modified.\n * May fire \"Room.name\" if the room name is updated.\n *\n * @remarks\n * Fires {@link RoomEvent.Name}\n */\n public recalculate(): void {\n // set fake stripped state events if this is an invite room so logic remains\n // consistent elsewhere.\n const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n if (membershipEvent) {\n const membership = membershipEvent.getContent().membership;\n this.updateMyMembership(membership!);\n\n if (membership === \"invite\") {\n const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n strippedStateEvents.forEach((strippedEvent) => {\n const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n if (!existingEvent) {\n // set the fake stripped event instead\n this.currentState.setStateEvents([\n new MatrixEvent({\n type: strippedEvent.type,\n state_key: strippedEvent.state_key,\n content: strippedEvent.content,\n event_id: \"$fake\" + Date.now(),\n room_id: this.roomId,\n user_id: this.myUserId, // technically a lie\n }),\n ]);\n }\n });\n }\n }\n\n const oldName = this.name;\n this.name = this.calculateRoomName(this.myUserId);\n this.normalizedName = normalize(this.name);\n this.summary = new RoomSummary(this.roomId, {\n title: this.name,\n });\n\n if (oldName !== this.name) {\n this.emit(RoomEvent.Name, this);\n }\n }\n\n /**\n * Update the room-tag event for the room. The previous one is overwritten.\n * @param event - the m.tag event\n */\n public addTags(event: MatrixEvent): void {\n // event content looks like:\n // content: {\n // tags: {\n // $tagName: { $metadata: $value },\n // $tagName: { $metadata: $value },\n // }\n // }\n\n // XXX: do we need to deep copy here?\n this.tags = event.getContent().tags || {};\n\n // XXX: we could do a deep-comparison to see if the tags have really\n // changed - but do we want to bother?\n this.emit(RoomEvent.Tags, event, this);\n }\n\n /**\n * Update the account_data events for this room, overwriting events of the same type.\n * @param events - an array of account_data events to add\n */\n public addAccountData(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === \"m.tag\") {\n this.addTags(event);\n }\n const eventType = event.getType();\n const lastEvent = this.accountData.get(eventType);\n this.accountData.set(eventType, event);\n this.emit(RoomEvent.AccountData, event, this, lastEvent);\n }\n }\n\n /**\n * Access account_data event of given event type for this room\n * @param type - the type of account_data event to be accessed\n * @returns the account_data event in question\n */\n public getAccountData(type: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(type);\n }\n\n /**\n * Returns whether the syncing user has permission to send a message in the room\n * @returns true if the user should be permitted to send\n * message events into the room.\n */\n public maySendMessage(): boolean {\n return (\n this.getMyMembership() === \"join\" &&\n (this.client.isRoomEncrypted(this.roomId)\n ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId)\n : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId))\n );\n }\n\n /**\n * Returns whether the given user has permissions to issue an invite for this room.\n * @param userId - the ID of the Matrix user to check permissions for\n * @returns true if the user should be permitted to issue invites for this room.\n */\n public canInvite(userId: string): boolean {\n let canInvite = this.getMyMembership() === \"join\";\n const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n const me = this.getMember(userId);\n if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n canInvite = false;\n }\n return canInvite;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns the join_rule applied to this room\n */\n public getJoinRule(): JoinRule {\n return this.currentState.getJoinRule();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getHistoryVisibility(): HistoryVisibility {\n return this.currentState.getHistoryVisibility();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getGuestAccess(): GuestAccess {\n return this.currentState.getGuestAccess();\n }\n\n /**\n * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n * @returns the type of the room.\n */\n public getType(): RoomType | string | undefined {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getTypeWarning) {\n logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getTypeWarning = true;\n }\n return undefined;\n }\n return createEvent.getContent()[RoomCreateTypeField];\n }\n\n /**\n * Returns whether the room is a space-room as defined by MSC1772.\n * @returns true if the room's type is RoomType.Space\n */\n public isSpaceRoom(): boolean {\n return this.getType() === RoomType.Space;\n }\n\n /**\n * Returns whether the room is a call-room as defined by MSC3417.\n * @returns true if the room's type is RoomType.UnstableCall\n */\n public isCallRoom(): boolean {\n return this.getType() === RoomType.UnstableCall;\n }\n\n /**\n * Returns whether the room is a video room.\n * @returns true if the room's type is RoomType.ElementVideo\n */\n public isElementVideoRoom(): boolean {\n return this.getType() === RoomType.ElementVideo;\n }\n\n /**\n * Find the predecessor of this room.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and use it if found (MSC3946).\n * @returns null if this room has no predecessor. Otherwise, returns\n * the roomId, last eventId and viaServers of the predecessor room.\n *\n * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n * as well as m.room.create events to find predecessors.\n *\n * Note: if an m.predecessor event is used, eventId may be undefined\n * since last_known_event_id is optional.\n *\n * Note: viaServers may be undefined, and will definitely be undefined if\n * this predecessor comes from a RoomCreate event (rather than a\n * RoomPredecessor, which has the optional via_servers property).\n */\n public findPredecessor(\n msc3946ProcessDynamicPredecessor = false,\n ): { roomId: string; eventId?: string; viaServers?: string[] } | null {\n const currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!currentState) {\n return null;\n }\n return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);\n }\n\n private roomNameGenerator(state: RoomNameState): string {\n if (this.client.roomNameGenerator) {\n const name = this.client.roomNameGenerator(this.roomId, state);\n if (name !== null) {\n return name;\n }\n }\n\n switch (state.type) {\n case RoomNameType.Actual:\n return state.name;\n case RoomNameType.Generated:\n switch (state.subtype) {\n case \"Inviting\":\n return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;\n default:\n return memberNamesToRoomName(state.names, state.count);\n }\n case RoomNameType.EmptyRoom:\n if (state.oldName) {\n return `Empty room (was ${state.oldName})`;\n } else {\n return \"Empty room\";\n }\n }\n }\n\n /**\n * This is an internal method. Calculates the name of the room from the current\n * room state.\n * @param userId - The client's user ID. Used to filter room members\n * correctly.\n * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there\n * was no m.room.name event.\n * @returns The calculated room name.\n */\n private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {\n if (!ignoreRoomNameEvent) {\n // check for an alias, if any. for now, assume first alias is the\n // official one.\n const mRoomName = this.currentState.getStateEvents(EventType.RoomName, \"\");\n if (mRoomName?.getContent().name) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: mRoomName.getContent().name,\n });\n }\n }\n\n const alias = this.getCanonicalAlias();\n if (alias) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: alias,\n });\n }\n\n const joinedMemberCount = this.currentState.getJoinedMemberCount();\n const invitedMemberCount = this.currentState.getInvitedMemberCount();\n // -1 because these numbers include the syncing user\n let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n // get service members (e.g. helper bots) for exclusion\n let excludedUserIds: string[] = [];\n const mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, \"\");\n if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {\n excludedUserIds = mFunctionalMembers!.getContent().service_members;\n }\n\n // get members that are NOT ourselves and are actually in the room.\n let otherNames: string[] = [];\n if (this.summaryHeroes) {\n // if we have a summary, the member state events should be in the room state\n this.summaryHeroes.forEach((userId) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return;\n }\n const member = this.getMember(userId);\n otherNames.push(member ? member.name : userId);\n });\n } else {\n let otherMembers = this.currentState.getMembers().filter((m) => {\n return m.userId !== userId && (m.membership === \"invite\" || m.membership === \"join\");\n });\n otherMembers = otherMembers.filter(({ userId }) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return false;\n }\n return true;\n });\n // make sure members have stable order\n otherMembers.sort((a, b) => utils.compare(a.userId, b.userId));\n // only 5 first members, immitate summaryHeroes\n otherMembers = otherMembers.slice(0, 5);\n otherNames = otherMembers.map((m) => m.name);\n }\n\n if (inviteJoinCount) {\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: otherNames,\n count: inviteJoinCount,\n });\n }\n\n const myMembership = this.getMyMembership();\n // if I have created a room and invited people through\n // 3rd party invites\n if (myMembership == \"join\") {\n const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n\n if (thirdPartyInvites?.length) {\n const thirdPartyNames = thirdPartyInvites.map((i) => {\n return i.getContent().display_name;\n });\n\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n subtype: \"Inviting\",\n names: thirdPartyNames,\n count: thirdPartyNames.length + 1,\n });\n }\n }\n\n // let's try to figure out who was here before\n let leftNames = otherNames;\n // if we didn't have heroes, try finding them in the room state\n if (!leftNames.length) {\n leftNames = this.currentState\n .getMembers()\n .filter((m) => {\n return m.userId !== userId && m.membership !== \"invite\" && m.membership !== \"join\";\n })\n .map((m) => m.name);\n }\n\n let oldName: string | undefined;\n if (leftNames.length) {\n oldName = this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: leftNames,\n count: leftNames.length + 1,\n });\n }\n\n return this.roomNameGenerator({\n type: RoomNameType.EmptyRoom,\n oldName,\n });\n }\n\n /**\n * When we receive a new visibility change event:\n *\n * - store this visibility change alongside the timeline, in case we\n * later need to apply it to an event that we haven't received yet;\n * - if we have already received the event whose visibility has changed,\n * patch it to reflect the visibility change and inform listeners.\n */\n private applyNewVisibilityEvent(event: MatrixEvent): void {\n const visibilityChange = event.asVisibilityChange();\n if (!visibilityChange) {\n // The event is ill-formed.\n return;\n }\n\n // Ignore visibility change events that are not emitted by moderators.\n const userId = event.getSender();\n if (!userId) {\n return;\n }\n const isPowerSufficient =\n (EVENT_VISIBILITY_CHANGE_TYPE.name &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) ||\n (EVENT_VISIBILITY_CHANGE_TYPE.altName &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId));\n if (!isPowerSufficient) {\n // Powerlevel is insufficient.\n return;\n }\n\n // Record this change in visibility.\n // If the event is not in our timeline and we only receive it later,\n // we may need to apply the visibility change at a later date.\n\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);\n if (visibilityEventsOnOriginalEvent) {\n // It would be tempting to simply erase the latest visibility change\n // but we need to record all of the changes in case the latest change\n // is ever redacted.\n //\n // In practice, linear scans through `visibilityEvents` should be fast.\n // However, to protect against a potential DoS attack, we limit the\n // number of iterations in this loop.\n let index = visibilityEventsOnOriginalEvent.length - 1;\n const min = Math.max(\n 0,\n visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH,\n );\n for (; index >= min; --index) {\n const target = visibilityEventsOnOriginalEvent[index];\n if (target.getTs() < event.getTs()) {\n break;\n }\n }\n if (index === -1) {\n visibilityEventsOnOriginalEvent.unshift(event);\n } else {\n visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);\n }\n } else {\n this.visibilityEvents.set(visibilityChange.eventId, [event]);\n }\n\n // Finally, let's check if the event is already in our timeline.\n // If so, we need to patch it and inform listeners.\n\n const originalEvent = this.findEventById(visibilityChange.eventId);\n if (!originalEvent) {\n return;\n }\n originalEvent.applyVisibilityEvent(visibilityChange);\n }\n\n private redactVisibilityChangeEvent(event: MatrixEvent): void {\n // Sanity checks.\n if (!event.isVisibilityEvent) {\n throw new Error(\"expected a visibility change event\");\n }\n const relation = event.getRelation();\n const originalEventId = relation?.event_id;\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId!);\n if (!visibilityEventsOnOriginalEvent) {\n // No visibility changes on the original event.\n // In particular, this change event was not recorded,\n // most likely because it was ill-formed.\n return;\n }\n const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());\n if (index === -1) {\n // This change event was not recorded, most likely because\n // it was ill-formed.\n return;\n }\n // Remove visibility change.\n visibilityEventsOnOriginalEvent.splice(index, 1);\n\n // If we removed the latest visibility change event, propagate changes.\n if (index === visibilityEventsOnOriginalEvent.length) {\n const originalEvent = this.findEventById(originalEventId!);\n if (!originalEvent) {\n return;\n }\n if (index === 0) {\n // We have just removed the only visibility change event.\n this.visibilityEvents.delete(originalEventId!);\n originalEvent.applyVisibilityEvent();\n } else {\n const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];\n const newVisibility = newEvent.asVisibilityChange();\n if (!newVisibility) {\n // Event is ill-formed.\n // This breaks our invariant.\n throw new Error(\"at this stage, visibility changes should be well-formed\");\n }\n originalEvent.applyVisibilityEvent(newVisibility);\n }\n }\n }\n\n /**\n * When we receive an event whose visibility has been altered by\n * a (more recent) visibility change event, patch the event in\n * place so that clients now not to display it.\n *\n * @param event - Any matrix event. If this event has at least one a\n * pending visibility change event, apply the latest visibility\n * change event.\n */\n private applyPendingVisibilityEvents(event: MatrixEvent): void {\n const visibilityEvents = this.visibilityEvents.get(event.getId()!);\n if (!visibilityEvents || visibilityEvents.length == 0) {\n // No pending visibility change in store.\n return;\n }\n const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];\n const visibilityChange = visibilityEvent.asVisibilityChange();\n if (!visibilityChange) {\n return;\n }\n if (visibilityChange.visible) {\n // Events are visible by default, no need to apply a visibility change.\n // Note that we need to keep the visibility changes in `visibilityEvents`,\n // in case we later fetch an older visibility change event that is superseded\n // by `visibilityChange`.\n }\n if (visibilityEvent.getTs() < event.getTs()) {\n // Something is wrong, the visibility change cannot happen before the\n // event. Presumably an ill-formed event.\n return;\n }\n event.applyVisibilityEvent(visibilityChange);\n }\n\n /**\n * Find when a client has gained thread capabilities by inspecting the oldest\n * threaded receipt\n * @returns the timestamp of the oldest threaded receipt\n */\n public getOldestThreadedReceiptTs(): number {\n return this.oldestThreadedReceiptTs;\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.unthreadedReceipts.get(userId);\n }\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n *\n * We consider a room fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n * This also detects all unread threads and applies the same logic to those\n * contexts\n */\n public fixupNotifications(userId: string): void {\n super.fixupNotifications(userId);\n\n const unreadThreads = this.getThreads().filter(\n (thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0,\n );\n\n for (const thread of unreadThreads) {\n thread.fixupNotifications(userId);\n }\n }\n}\n\n// a map from current event status to a list of allowed next statuses\nconst ALLOWED_TRANSITIONS: Record = {\n [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],\n [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENT]: [],\n [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],\n [EventStatus.CANCELLED]: [],\n};\n\nexport enum RoomNameType {\n EmptyRoom,\n Generated,\n Actual,\n}\n\nexport interface EmptyRoomNameState {\n type: RoomNameType.EmptyRoom;\n oldName?: string;\n}\n\nexport interface GeneratedRoomNameState {\n type: RoomNameType.Generated;\n subtype?: \"Inviting\";\n names: string[];\n count: number;\n}\n\nexport interface ActualRoomNameState {\n type: RoomNameType.Actual;\n name: string;\n}\n\nexport type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;\n\n// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn\nfunction memberNamesToRoomName(names: string[], count: number): string {\n const countWithoutMe = count - 1;\n if (!names.length) {\n return \"Empty room\";\n } else if (names.length === 1 && countWithoutMe <= 1) {\n return names[0];\n } else if (names.length === 2 && countWithoutMe <= 2) {\n return `${names[0]} and ${names[1]}`;\n } else {\n const plural = countWithoutMe > 1;\n if (plural) {\n return `${names[0]} and ${countWithoutMe} others`;\n } else {\n return `${names[0]} and 1 other`;\n }\n }\n}\n"],"mappings":";;;;;;;;AAgBA,IAAAA,gBAAA,GAAAC,OAAA;AAEA,IAAAC,iBAAA,GAAAD,OAAA;AAMA,IAAAE,cAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,KAAA,GAAAC,uBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AACA,IAAAO,YAAA,GAAAP,OAAA;AACA,IAAAQ,WAAA,GAAAR,OAAA;AACA,IAAAS,YAAA,GAAAT,OAAA;AACA,IAAAU,OAAA,GAAAV,OAAA;AACA,IAAAW,UAAA,GAAAX,OAAA;AACA,IAAAY,OAAA,GAAAZ,OAAA;AAQA,IAAAa,OAAA,GAAAb,OAAA;AAEA,IAAAc,OAAA,GAAAd,OAAA;AACA,IAAAe,UAAA,GAAAf,OAAA;AACA,IAAAgB,OAAA,GAAAhB,OAAA;AACA,IAAAiB,OAAA,GAAAjB,OAAA;AASA,IAAAkB,cAAA,GAAAlB,OAAA;AAQA,IAAAmB,mBAAA,GAAAnB,OAAA;AACA,IAAAoB,YAAA,GAAApB,OAAA;AACA,IAAAqB,KAAA,GAAArB,OAAA;AAAyC,SAAAsB,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAlB,wBAAAsB,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA,QAAAA,GAAA,oBAAAA,GAAA,wBAAAA,GAAA,4BAAA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