Typed Event Emitter class which can act as a Base Model for all our model and communication events. This makes it much easier for us to distinguish between events, as we now need to properly type this, so that our events are not stringly-based and prone to silly typos.

Type parameters:

  • Events - List of all events emitted by this TypedEventEmitter. Normally an enum type.
  • Arguments - A ListenerMap type providing mappings from event names to listener types.
  • SuperclassArguments - TODO: not really sure. Alternative listener mappings, I think? But only honoured for .emit?

Hierarchy (View Summary)

Constructors

Properties

Accessors

Methods

addAccountData addEphemeralEvents addEventsToTimeline addListener addLiveEvents addLocalEchoReceipt addPendingEvent addReceipt addReceiptToStructure addTags addTimeline canInvite clearLoadedMembersIfNeeded compareEventOrdering createThread createThreadsTimelineSets decryptAllEvents decryptCriticalEvents emit emitPromised eventShouldLiveIn fetchRoomThreads findEventById findPredecessor findThreadForEvent fixupNotifications getAccountData getAltAliases getAvatarFallbackMember getAvatarUrl getBlacklistUnverifiedDevices getCanonicalAlias getCreator getDefaultRoomName getDMInviter getEncryptionTargetMembers getEventForTxnId getEventReadUpTo getGuestAccess getHistoryVisibility getInvitedAndJoinedMemberCount getInvitedMemberCount getJoinedMemberCount getJoinedMembers getJoinRule getLastActiveTimestamp getLastLiveEvent getLastThread getLastUnthreadedReceiptFor getLiveTimeline getMember getMembers getMembersWithMembership getMxcAvatarUrl getMyMembership getOldestThreadedReceiptTs getOrCreateFilteredTimelineSet getPendingEvent getPendingEvents getReadReceiptForUserId getReceiptsForEvent getRecommendedVersion getRoomUnreadNotificationCount getThread getThreads getThreadUnreadNotificationCount getTimelineForEvent getTimelineNeedsRefresh getTimelineSets getType getUnfilteredTimelineSet getUnreadCountForEventContext getUnreadNotificationCount getUsersReadUpTo getVersion guessDMUserId handleRemoteEcho hasEncryptionStateEvent hasMembershipState hasPendingEvent hasThreadUnreadNotification hasUserReadEvent isCallRoom isElementVideoRoom isSpaceRoom listenerCount listeners loadMembersIfNeeded maySendMessage membersLoaded off on once partitionThreadedEvents prependListener prependOnceListener processPollEvents processThreadedEvents processThreadRoots rawListeners recalculate refreshLiveTimeline removeAllListeners removeEvent removeEvents removeFilteredTimelineSet removeListener removePendingEvent resetLiveTimeline resetThreadUnreadNotificationCountFromSync setBlacklistUnverifiedDevices setSummary setThreadUnreadNotificationCount setTimelineNeedsRefresh setUnread setUnreadNotificationCount shouldEncryptForInvitedMembers updateMyMembership updatePendingEvent userMayUpgradeRoom

Constructors

  • Construct a new Room.

    For a room, we store an ordered sequence of timelines, which may or may not be continuous. Each timeline lists a series of events, as well as tracking the room state at the start and the end of the timeline. It also tracks forward and backward pagination tokens, as well as containing links to the next timeline in the sequence.

    There is one special timeline - the 'live' timeline, which represents the timeline to which events are being added in real-time as they are received from the /sync API. Note that you should not retain references to this timeline - even if it is the current timeline right now, it may not remain so if the server gives us a timeline gap in /sync.

    In order that we can find events from their ids later, we also maintain a map from event_id to timeline and index.

    Parameters

    • roomId: string

      Required. The ID of this room.

    • client: MatrixClient

      Required. The client, used to lazy load members.

    • myUserId: string

      Required. The ID of the syncing user.

    • opts: IOpts = {}

      Configuration options

    Returns Room

Properties

accountData: Map<string, MatrixEvent> = ...

accountData Dict of per-room account_data events; the keys are the event type and the values are the events.

cachedThreadReadReceipts: Map<string, CachedReceiptStructure[]> = ...
client: MatrixClient

Required. The client, used to lazy load members.

currentState: RoomState

currentState The state of the room at the time of the newest event in the timeline.

Present for backwards compatibility. Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.

myUserId: string

Required. The ID of the syncing user.

name: string

The human-readable display name for this room.

normalizedName: string

The un-homoglyphed name for this room.

oldState: RoomState

oldState The state of the room at the time of the oldest event in the live timeline.

Present for backwards compatibility. Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead

polls: Map<string, Poll> = ...
roomId: string

Required. The ID of this room.

summary: null | RoomSummary = null

The room summary.

tags: Record<string, Record<string, any>> = {}

Dict of room tags; the keys are the tag name and the values are any metadata associated with the tag - e.g. { "fav" : { order: 1 } }

threadsTimelineSets: [] | [EventTimelineSet, EventTimelineSet] = []

Empty array if the timeline sets have not been initialised. After initialisation: 0: All threads 1: Threads the current user has participated in

Accessors

  • get timeline(): MatrixEvent[]
  • The live event timeline for this room, with the oldest event at index 0.

    Returns MatrixEvent[]

    Present for backwards compatibility. Use getLiveTimeline().getEvents() instead

Methods

  • Update the account_data events for this room, overwriting events of the same type.

    Parameters

    • events: MatrixEvent[]

      an array of account_data events to add

    Returns void

  • Adds/handles ephemeral events such as typing notifications and read receipts.

    Parameters

    Returns void

  • Add events to a timeline

    Will fire "Room.timeline" for each event added.

    Parameters

    • events: MatrixEvent[]

      A list of events to add.

    • toStartOfTimeline: boolean

      True to add these events to the start (oldest) instead of the end (newest) of the timeline. If true, the oldest event will be the last element of 'events'.

    • addToState: boolean
    • timeline: EventTimeline

      timeline to add events to.

    • OptionalpaginationToken: string

      token for the next batch of events

    Returns void

    Fires RoomEvent.Timeline

  • Add some events to this room. This can include state events, message events and typing notifications. These events are treated as "live" so they will go to the end of the timeline.

    Parameters

    Returns Promise<void>

    If duplicateStrategy is not falsey, 'replace' or 'ignore'.

  • Add a temporary local-echo receipt to the room to reflect in the client the fact that we've sent one.

    Parameters

    • userId: string

      The user ID if the receipt sender

    • e: MatrixEvent

      The event that is to be acknowledged

    • receiptType: ReceiptType

      The type of receipt

    • unthreaded: boolean = false

      the receipt is unthreaded

    Returns void

  • Add a pending outgoing event to this room.

    The event is added to either the pendingEventList, or the live timeline, depending on the setting of opts.pendingEventOrdering.

    This is an internal method, intended for use by MatrixClient.

    Parameters

    • event: MatrixEvent

      The event to add.

    • txnId: string

      Transaction id for this outgoing event

    Returns void

    if the event doesn't have status SENDING, or we aren't given a unique transaction id.

  • Returns whether the given user has permissions to issue an invite for this room.

    Parameters

    • userId: string

      the ID of the Matrix user to check permissions for

    Returns boolean

    true if the user should be permitted to issue invites for this room.

  • Determine the order of two events in this room.

    In principle this should use the same order as the server, but in practice this is difficult for events that were not received over the Sync API. See MSC4033 for details.

    This implementation leans on the order of events within their timelines, and falls back to comparing event timestamps when they are in different timelines.

    See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are tracking the work to fix this.

    Parameters

    • leftEventId: string

      the id of the first event

    • rightEventId: string

      the id of the second event

    Returns null | number

    -1 if left < right, 1 if left > right, 0 if left == right, null if we can't tell (because we can't find the events).

  • Bulk decrypt critical events in a room

    Critical events represents the minimal set of events to decrypt for a typical UI to function properly

    • Last event of every room (to generate likely message preview)
    • All events up to the read receipt (to calculate an accurate notification count)

    Returns Promise<void>

    Signals when all events have been decrypted

  • Determine which timeline(s) a given event should live in Thread roots live in both the main timeline and their corresponding thread timeline Relations, redactions, replies to thread relation events live only in the thread timeline Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless. Otherwise, the event lives in the main timeline only.

    Note: when a redaction is applied, the redacted event, events relating to it, and the redaction event itself, will all move to the main thread. This method classifies them as inside the thread of the redacted event. They are moved later as part of makeRedacted. This will change if MSC3389 is merged.

    Parameters

    Returns { shouldLiveInRoom: boolean; shouldLiveInThread: boolean; threadId?: string }

  • Fetch the bare minimum of room threads required for the thread list to work reliably. With server support that means fetching one page. Without server support that means fetching as much at once as the server allows us to.

    Returns Promise<void>

  • Find the predecessor of this room.

    Parameters

    • msc3946ProcessDynamicPredecessor: boolean = false

      if true, look for an m.room.predecessor state event and use it if found (MSC3946).

    Returns null | { eventId?: string; roomId: string; viaServers?: string[] }

    null if this room has no predecessor. Otherwise, returns the roomId, last eventId and viaServers of the predecessor room.

    If msc3946ProcessDynamicPredecessor is true, use m.predecessor events as well as m.room.create events to find predecessors.

    Note: if an m.predecessor event is used, eventId may be undefined since last_known_event_id is optional.

    Note: viaServers may be undefined, and will definitely be undefined if this predecessor comes from a RoomCreate event (rather than a RoomPredecessor, which has the optional via_servers property).

  • This issue should also be addressed on synapse's side and is tracked as part of https://github.com/matrix-org/synapse/issues/14837

    We consider a room fully read if the current user has sent the last event in the live timeline of that context and if the read receipt we have on record matches. This also detects all unread threads and applies the same logic to those contexts

    Parameters

    • userId: string

    Returns void

  • Access account_data event of given event type for this room

    Parameters

    • type: string

      the type of account_data event to be accessed

    Returns undefined | MatrixEvent

    the account_data event in question

  • Get this room's alternative aliases

    Returns string[]

    The room's alternative aliases, or an empty array

  • Get the avatar URL for a room if one was set.

    Parameters

    • baseUrl: string

      The homeserver base URL. See MatrixClient#getHomeserverUrl.

    • width: number

      The desired width of the thumbnail.

    • height: number

      The desired height of the thumbnail.

    • resizeMethod: ResizeMethod

      The thumbnail resize method to use, either "crop" or "scale".

    • allowDefault: boolean = true

      True to allow an identicon for this room if an avatar URL wasn't explicitly set. Default: true. (Deprecated)

    Returns null | string

    the avatar URL or null.

  • Whether to send encrypted messages to devices within this room.

    Returns null | boolean

    true if blacklisting unverified devices, null if the global value should be used for this room.

  • Get this room's canonical alias The alias returned by this function may not necessarily still point to this room.

    Returns null | string

    The room's canonical alias, or null if there is none

  • Gets the creator of the room

    Returns null | string

    The creator of the room, or null if it could not be determined

  • Get the default room name (i.e. what a given user would see if the room had no m.room.name)

    Parameters

    • userId: string

      The userId from whose perspective we want to calculate the default name

    Returns string

    The default room name

  • If this room is a DM we're invited to, try to find out who invited us

    Returns undefined | string

    user id of the inviter

  • Get the ID of the event that a given user has read up to, or null if:

    • we have received no read receipts for them, or
    • the receipt we have points at an event we don't have, or
    • the thread ID in the receipt does not match the thread root of the referenced event.

    (The event might not exist if it is not loaded, and the thread ID might not match if the event has moved thread because it was redacted.)

    Parameters

    • userId: string

      The user ID to get read receipt event ID for

    • ignoreSynthesized: boolean = false

      If true, return only receipts that have been sent by the server, not implicit ones generated by the JS SDK.

    Returns null | string

    ID of the latest existing event that the given user has read, or null.

  • Returns the history visibility based on the m.room.history_visibility state event, defaulting to shared.

    Returns GuestAccess

    the history_visibility applied to this room

  • Returns the number of invited + joined members in this room

    Returns number

    The number of members in this room whose membership is 'invite' or 'join'

  • Returns the number of invited members in this room

    Returns number

    The number of members in this room whose membership is 'invite'

  • Returns the number of joined members in this room This method caches the result. This is a wrapper around the method of the same name in roomState, returning its result for the room's current state.

    Returns number

    The number of members in this room whose membership is 'join'

  • Returns the join rule based on the m.room.join_rule state event, defaulting to invite.

    Returns JoinRule

    the join_rule applied to this room

  • Get the timestamp of the last message in the room

    Returns number

    the timestamp of the last message in the room

  • Returns the last live event of this room. "last" means latest timestamp. Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG. Unfortunately, this information is currently not available in the client. See https://github.com/matrix-org/matrix-js-sdk/issues/3325. "live of this room" means from all live timelines: the room and the threads.

    Returns undefined | MatrixEvent

    MatrixEvent if there is a last event; else undefined.

  • Returns the last thread of this room. "last" means latest timestamp of the last thread event. Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG. Unfortunately, this information is currently not available in the client. See https://github.com/matrix-org/matrix-js-sdk/issues/3325.

    Returns undefined | Thread

    the thread with the most recent event in its live time line. undefined if there is no thread.

  • Returns the most recent unthreaded receipt for a given user

    Parameters

    • userId: string

      the MxID of the User

    Returns undefined | Receipt

    an unthreaded Receipt. Can be undefined if receipts have been disabled or a user chooses to use private read receipts (or we have simply not received a receipt from this user yet).

  • Get a member from the current room state.

    Parameters

    • userId: string

      The user ID of the member.

    Returns null | RoomMember

    The member or null.

  • Get a list of members with given membership state.

    Parameters

    • membership: string

      The membership state.

    Returns RoomMember[]

    A list of members with the given membership state.

  • Get the mxc avatar url for the room, if one was set.

    Returns null | string

    the mxc avatar url or falsy

  • Returns string

    the membership type (join | leave | invite | knock) for the logged in user

  • Find when a client has gained thread capabilities by inspecting the oldest threaded receipt

    Returns number

    the timestamp of the oldest threaded receipt

  • Get a specific event from the pending event list, if configured, null otherwise.

    Parameters

    • eventId: string

      The event ID to check for.

    Returns null | MatrixEvent

  • Get the list of pending sent events for this room

    Returns MatrixEvent[]

    A list of the sent events waiting for remote echo.

    If opts.pendingEventOrdering was not 'detached'

  • Gets the latest receipt for a given user in the room

    Parameters

    • userId: string

      The id of the user for which we want the receipt

    • ignoreSynthesized: boolean = false

      Whether to ignore synthesized receipts or not

    • receiptType: ReceiptType = ReceiptType.Read

      Optional. The type of the receipt we want to get

    Returns null | WrappedReceipt

    the latest receipts of the chosen type for the chosen user

  • Determines the recommended room version for the room. This returns an object with 3 properties: version as the new version the room should be upgraded to (may be the same as the current version); needsUpgrade to indicate if the room actually can be upgraded (ie: does the current version not match?); and urgent to indicate if the new version patches a vulnerability in a previous version.

    Returns Promise<IRecommendedVersion>

    Resolves to the version the room should be upgraded to.

  • Get one of the notification counts for this room

    Parameters

    • type: NotificationCountType = NotificationCountType.Total

      The type of notification count to get. default: 'total'

    Returns number

    The notification count, or undefined if there is no count for this type.

  • Get the instance of the thread associated with the current event

    Parameters

    • eventId: string

      the ID of the current event

    Returns null | Thread

    a thread instance if known

  • Get one of the notification counts for a thread

    Parameters

    • threadId: string

      the root event ID

    • type: NotificationCountType = NotificationCountType.Total

      The type of notification count to get. default: 'total'

    Returns number

    The notification count, or undefined if there is no count for this type.

  • Get the timeline which contains the given event from the unfiltered set, if any

    Parameters

    • eventId: string

      event ID to look for

    Returns null | EventTimeline

    timeline containing the given event, or null if unknown

  • Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.

    Returns boolean

    .

  • Returns the type of the room from the m.room.create event content or undefined if none is set

    Returns undefined | string

    the type of the room.

  • Get one of the notification counts for this room

    Parameters

    • type: NotificationCountType = NotificationCountType.Total

      The type of notification count to get. default: 'total'

    Returns number

    The notification count, or undefined if there is no count for this type.

  • Gets the version of the room

    Returns string

    The version of the room, or null if it could not be determined

  • Assuming this room is a DM room, tries to guess with which user.

    Returns string

    user id of the other member (could be syncing user)

  • Return true if this room has an m.room.encryption state event.

    If this returns true, events sent to this room should be encrypted (and MatrixClient.sendEvent and friends will encrypt outgoing events).

    Returns boolean

  • Check if the given user_id has the given membership state.

    Parameters

    • userId: string

      The user ID to check.

    • membership: string

      The membership e.g. 'join'

    Returns boolean

    True if this user_id has the given membership state.

  • Check whether the pending event list contains a given event by ID. If pending event ordering is not "detached" then this returns false.

    Parameters

    • eventId: string

      The event ID to check for.

    Returns boolean

  • Checks if the current room has unread thread notifications

    Returns boolean

  • Determines if the given user has read a particular event ID with the known history of the room. This is not a definitive check as it relies only on what is available to the room at the time of execution.

    Parameters

    • userId: string

      The user ID to check the read state of.

    • eventId: string

      The event ID to check if the user read.

    Returns boolean

    true if the user has read the event, false otherwise.

  • Returns whether the room is a call-room as defined by MSC3417.

    Returns boolean

    true if the room's type is RoomType.UnstableCall

  • Returns whether the room is a video room.

    Returns boolean

    true if the room's type is RoomType.ElementVideo

  • Returns whether the room is a space-room as defined by MSC1772.

    Returns boolean

    true if the room's type is RoomType.Space

  • Preloads the member list in case lazy loading of memberships is in use. Can be called multiple times, it will only preload once.

    Returns Promise<boolean>

    when preloading is done and accessing the members on the room will take all members in the room into account

  • Returns whether the syncing user has permission to send a message in the room

    Returns boolean

    true if the user should be permitted to send message events into the room.

  • Check if loading of out-of-band-members has completed

    Returns boolean

    true if the full membership list of this room has been loaded (including if lazy-loading is disabled). False if the load is not started or is in progress.

  • Adds events to a thread's timeline. Will fire "Thread.update"

    Parameters

    Returns void

  • Takes the given thread root events and creates threads for them.

    Parameters

    Returns void

  • Recalculate various aspects of the room, including the room name and room summary. Call this any time the room's current state is modified. May fire "Room.name" if the room name is updated.

    Returns void

    Fires RoomEvent.Name

  • Empty out the current live timeline and re-request it. This is used when historical messages are imported into the room via MSC2716 /batch_send because the client may already have that section of the timeline loaded. We need to force the client to throw away their current timeline so that when they back paginate over the area again with the historical messages in between, it grabs the newly imported messages. We can listen for UNSTABLE_MSC2716_MARKER, in order to tell when historical messages are ready to be discovered in the room and the timeline needs a refresh. The SDK emits a RoomEvent.HistoryImportedWithinTimeline event when we detect a valid marker and can check the needs refresh status via room.getTimelineNeedsRefresh().

    Returns Promise<void>

  • Removes a single event from this room.

    Parameters

    • eventId: string

      The id of the event to remove

    Returns boolean

    true if the event was removed from any of the room's timeline sets

  • Removes events from this room.

    Parameters

    • eventIds: string[]

      A list of eventIds to remove.

    Returns void

  • Forget the timelineSet for this room with the given filter

    Parameters

    • filter: Filter

      the filter whose timelineSet is to be forgotten

    Returns void

  • Removes a pending event for this room

    Parameters

    • eventId: string

    Returns boolean

    True if an element was removed.

  • Reset the live timeline of all timelineSets, and start new ones.

    This is used when /sync returns a 'limited' timeline.

    Parameters

    • OptionalbackPaginationToken: null | string

      token for back-paginating the new timeline

    • OptionalforwardPaginationToken: null | string

      token for forward-paginating the old live timeline, if absent or null, all timelines are reset, removing old ones (including the previous live timeline which would otherwise be unable to paginate forwards without this token). Removing just the old live timeline whilst preserving previous ones is not supported.

    Returns void

  • Resets the total thread notifications for all threads in this room to zero, excluding any threads whose IDs are given in exceptThreadIds.

    If the room is not encrypted, also resets the highlight notification count to zero for the same set of threads.

    This is intended for use from the sync code since we calculate highlight notification counts locally from decrypted messages. We want to partially trust the total from the server such that we clear notifications when read receipts arrive. The weird name is intended to reflect this. You probably do not want to use this.

    Parameters

    • exceptThreadIds: string[] = []

      The thread IDs to exclude from the reset.

    Returns void

  • Whether to send encrypted messages to devices within this room.

    Parameters

    • value: boolean

      true to blacklist unverified devices, null to use the global value for this room.

    Returns void

  • Swet one of the notification count for a thread

    Parameters

    • threadId: string

      the root event ID

    • type: NotificationCountType

      The type of notification count to get. default: 'total'

    • count: number

    Returns void

  • Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.

    Parameters

    • value: boolean

      The value to set

    Returns void

  • Determine whether we should encrypt messages for invited users in this room

    Returns boolean

    if we should encrypt messages for invited users

  • Sets the membership this room was received as during sync

    Parameters

    • membership: string

      join | leave | invite

    Returns void

  • Update the status / event id on a pending event, to reflect its transmission progress.

    This is an internal method.

    Parameters

    • event: MatrixEvent

      local echo event

    • newStatus: EventStatus

      status to assign

    • OptionalnewEventId: string

      new event id to assign. Ignored unless newStatus == EventStatus.SENT.

    Returns void

  • Determines whether the given user is permitted to perform a room upgrade

    Parameters

    • userId: string

      The ID of the user to test against

    Returns boolean

    True if the given user is permitted to upgrade the room