Class Room

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.

Hierarchy

Constructors

Properties

Accessors

Methods

addAccountData addEphemeralEvents addEventsToTimeline addListener addLiveEvent addLiveEvents addLocalEchoReceipt addPendingEvent addReceipt addReceiptToStructure addTags addThreadedEvents addTimeline aggregateNonLiveRelation applyNewVisibilityEvent applyPendingVisibilityEvents applyRedaction calculateRoomName canInvite checkVersionAgainstCapability cleanupAfterLeaving clearLoadedMembersIfNeeded createThread createThreadTimelineSet createThreadsTimelineSets decryptAllEvents decryptCriticalEvents emit eventNames eventShouldLiveIn fetchRoomThreadList fetchRoomThreads findEventById findThreadForEvent findThreadRoots fixUpLegacyTimelineFields getAccountData getAltAliases getAvatarFallbackMember getAvatarUrl getBlacklistUnverifiedDevices getCanonicalAlias getCreator getDMInviter getDefaultRoomName getEncryptionTargetMembers getEventForTxnId getEventReadUpTo getGuestAccess getHistoryVisibility getInvitedAndJoinedMemberCount getInvitedMemberCount getJoinRule getJoinedMemberCount getJoinedMembers getLastActiveTimestamp getLiveTimeline getMember getMembers getMembersWithMembership getMxcAvatarUrl getMyMembership getOrCreateFilteredTimelineSet getPendingEvent getPendingEvents getReadReceiptForUserId getReceiptsForEvent getRecommendedVersion getRoomUnreadNotificationCount getThread getThreadListFilter getThreadUnreadNotificationCount getThreads getTimelineForEvent getTimelineNeedsRefresh getTimelineSets getType getUnfilteredTimelineSet getUnreadCountForEventContext getUnreadNotificationCount getUsersReadUpTo getVersion guessDMUserId handleRemoteEcho hasMembershipState hasPendingEvent hasThreadUnreadNotification hasUnverifiedDevices hasUserReadEvent isCallRoom isElementVideoRoom isSpaceRoom listenerCount listeners loadMembers loadMembersFromServer loadMembersIfNeeded maySendMessage off on onThreadDelete onThreadNewReply once partitionThreadedEvents prependListener prependOnceListener processLiveEvent processThreadRoots processThreadedEvents rawListeners recalculate redactVisibilityChangeEvent refreshLiveTimeline removeAllListeners removeEvent removeEvents removeFilteredTimelineSet removeListener removePendingEvent resetLiveTimeline resetThreadUnreadNotificationCount revertRedactionLocalEcho roomNameGenerator savePendingEvents setBlacklistUnverifiedDevices setSummary setThreadUnreadNotificationCount setTimelineNeedsRefresh setUnreadNotificationCount shouldEncryptForInvitedMembers shouldUpgradeToVersion updateMyMembership updatePendingEvent updateThreadRootEvent updateThreadRootEvents 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.

    Alias

    module:models/room

    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: Record<string, MatrixEvent> = {}

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

blacklistUnverifiedDevices?: boolean
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 - prefer getLiveTimeline().getState(EventTimeline.FORWARDS).

filteredTimelineSets: Record<string, EventTimelineSet> = {}
getTypeWarning: boolean = false
getVersionWarning: boolean = false
lastThread?: Thread
membersPromise?: Promise<boolean>
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.

notificationCounts: Partial<Record<NotificationCountType, number>> = {}
oldState: RoomState

oldState The state of the room at the time of the oldest event in the live timeline. Present for backwards compatibility - prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).

opts: IOpts = {}

Configuration options

pendingEventList?: MatrixEvent[]
relations: RelationsContainer = ...
roomId: string

Required. The ID of this room.

selfMembership?: string
summary: null | RoomSummary = null

The room summary.

summaryHeroes: null | string[] = null
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 } }

threadNotifications: Map<string, Partial<Record<NotificationCountType, number>>> = ...
threadTimelineSetsPromise: null | Promise<[EventTimelineSet, EventTimelineSet]> = null
threads: Map<string, Thread> = ...
threadsReady: boolean = false
threadsTimelineSets: EventTimelineSet[] = []
timeline: MatrixEvent[]

The live event timeline for this room, with the oldest event at index 0. Present for backwards compatibility - prefer getLiveTimeline().getEvents()

timelineNeedsRefresh: boolean = false
timelineSets: EventTimelineSet[]
txnToEvent: Record<string, MatrixEvent> = {}
visibilityEvents: Map<string, MatrixEvent[]> = ...

A mapping of eventId to all visibility changes to apply to the event, by chronological order, as per https://github.com/matrix-org/matrix-doc/pull/3531

Invariants

  • within each list, all events are classed by chronological order;
  • all events are events such that asVisibilityEvent() returns a non-null IVisibilityChange;
  • within each list with key eventId, all events are in relation to eventId.

Accessors

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.

    Fires

    module:client~MatrixClient#event:"Room.timeline"

    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'.

    • timeline: EventTimeline

      timeline to add events to.

    • Optional paginationToken: string

      token for the next batch of events

    Returns void

  • 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.

    Throws

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

    Parameters

    Returns void

  • Deprecated

    In favor of the overload with IAddLiveEventOptions

    Parameters

    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.

    Fires

    module:client~MatrixClient#event:"Room.localEchoUpdated"

    Throws

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

    Parameters

    • event: MatrixEvent

      The event to add.

    • txnId: string

      Transaction id for this outgoing event

    Returns void

  • Parameters

    • threadId: string
    • events: MatrixEvent[]
    • toStartOfTimeline: boolean = false

    Returns void

  • Used to aggregate the local echo for a relation, and also for re-applying a relation after it's redaction has been cancelled, as the local echo for the redaction of the relation would have un-aggregated the relation. Note that this is different from regular messages, which are just kept detached for their local echo.

    Also note that live events are aggregated in the live EventTimelineSet.

    Parameters

    • event: MatrixEvent

      the relation event that needs to be aggregated.

    Returns void

  • When we receive a new visibility change event:

    • store this visibility change alongside the timeline, in case we later need to apply it to an event that we haven't received yet;
    • if we have already received the event whose visibility has changed, patch it to reflect the visibility change and inform listeners.

    Parameters

    Returns void

  • When we receive an event whose visibility has been altered by a (more recent) visibility change event, patch the event in place so that clients now not to display it.

    Parameters

    • event: MatrixEvent

      Any matrix event. If this event has at least one a pending visibility change event, apply the latest visibility change event.

    Returns void

  • This is an internal method. Calculates the name of the room from the current room state.

    Returns

    The calculated room name.

    Parameters

    • userId: string

      The client's user ID. Used to filter room members correctly.

    • ignoreRoomNameEvent: boolean = false

      Return the implicit room name that we'd see if there was no m.room.name event.

    Returns string

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

    Returns

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

    Parameters

    • userId: string

      the ID of the Matrix user to check permissions for

    Returns boolean

  • called when sync receives this room in the leave section to do cleanup after leaving a room. Possibly called multiple times.

    Returns void

  • Removes the lazily loaded members from storage if needed

    Returns Promise<void>

  • Bulk decrypt events in a room

    Returns

    Signals when all events have been decrypted

    Returns Promise<void>

  • 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

    Signals when all events have been decrypted

    Returns Promise<void>

  • Parameters

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

    • shouldLiveInRoom: boolean
    • shouldLiveInThread: boolean
    • Optional 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>

  • Get an event which is stored in our unfiltered timeline set, or in a thread

    Returns

    the given event, or undefined if unknown

    Parameters

    • eventId: string

      event ID to look for

    Returns undefined | MatrixEvent

  • Given some events, find the IDs of all the thread roots that are referred to by them.

    Parameters

    Returns Set<string>

  • Private

    Fix up this.timeline, this.oldState and this.currentState

    Returns void

  • Access account_data event of given event type for this room

    Returns

    the account_data event in question

    Parameters

    • type: string

      the type of account_data event to be accessed

    Returns undefined | MatrixEvent

  • Get this room's alternative aliases

    Returns

    The room's alternative aliases, or an empty array

    Returns string[]

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

    Returns

    the avatar URL or null.

    Parameters

    • baseUrl: string

      The homeserver base URL. See module:client~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

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

    Returns

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

    Returns null | boolean

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

    Returns

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

    Returns null | string

  • Gets the creator of the room

    Returns

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

    Returns null | string

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

    Returns

    user id of the inviter

    Returns undefined | string

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

    Returns

    The default room name

    Parameters

    • userId: string

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

    Returns string

  • Get a list of members we should be encrypting for in this room

    Returns

    A list of members who we should encrypt messages for in this room.

    Returns Promise<RoomMember[]>

  • Get the ID of the event that a given user has read up to, or null if we have received no read receipts from them.

    Returns

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

    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

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

    Returns

    the history_visibility applied to this room

    Returns GuestAccess

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

    Returns

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

    Returns number

  • Returns the number of invited members in this room

    Returns

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

    Returns number

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

    Returns

    the join_rule applied to this room

    Returns JoinRule

  • 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

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

    Returns number

  • Get the timestamp of the last message in the room

    Returns

    the timestamp of the last message in the room

    Returns number

  • Get a member from the current room state.

    Returns

    The member or null.

    Parameters

    • userId: string

      The user ID of the member.

    Returns null | RoomMember

  • Get a list of members with given membership state.

    Returns

    A list of members with the given membership state.

    Parameters

    • membership: string

      The membership state.

    Returns RoomMember[]

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

    Returns

    the mxc avatar url or falsy

    Returns null | string

  • Returns

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

    Returns string

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

    Returns

    Parameters

    • eventId: string

      The event ID to check for.

    Returns null | MatrixEvent

  • Get the list of pending sent events for this room

    Returns

    A list of the sent events waiting for remote echo.

    Throws

    If opts.pendingEventOrdering was not 'detached'

    Returns MatrixEvent[]

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

    Returns

    the latest receipts of the chosen type for the chosen user

    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

  • 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

    Resolves to the version the room should be upgraded to.

    Returns Promise<IRecommendedVersion>

  • Get one of the notification counts for this room

    Returns

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

    Parameters

    • type: NotificationCountType = NotificationCountType.Total

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

    Returns number

  • Experimental

    Get one of the notification counts for a thread

    Returns

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

    Parameters

    • threadId: string

      the root event ID

    • type: NotificationCountType = NotificationCountType.Total

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

    Returns number

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

    Returns

    timeline containing the given event, or null if unknown

    Parameters

    • eventId: string

      event ID to look for

    Returns null | EventTimeline

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

    Returns

    .

    Returns boolean

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

    Returns

    the type of the room.

    Returns undefined | string

  • Get one of the notification counts for this room

    Returns

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

    Parameters

    • type: NotificationCountType = NotificationCountType.Total

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

    Returns number

  • Gets the version of the room

    Returns

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

    Returns string

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

    Returns

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

    Returns string

  • Private

    Deal with the echo of a message we sent.

    We move the event to the live timeline if it isn't there already, and update it.

    Fires

    module:client~MatrixClient#event:"Room.localEchoUpdated"

    Parameters

    • remoteEvent: MatrixEvent

      The event received from /sync

    • localEvent: MatrixEvent

      The local echo, which should be either in the pendingEventList or the timeline.

    Returns void

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

    Returns

    True if this user_id has the given membership state.

    Parameters

    • userId: string

      The user ID to check.

    • membership: string

      The membership e.g. 'join'

    Returns boolean

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

    Returns

    Parameters

    • eventId: string

      The event ID to check for.

    Returns boolean

  • Experimental

    Checks if the current room has unread thread notifications

    Returns

    Returns boolean

  • Returns whether there are any devices in the room that are unverified

    Note: Callers should first check if crypto is enabled on this device. If it is disabled, then we aren't tracking room devices at all, so we can't answer this, and an error will be thrown.

    Returns

    the result

    Returns Promise<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.

    Returns

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

    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

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

    Returns

    true if the room's type is RoomType.UnstableCall

    Returns boolean

  • Returns whether the room is a video room.

    Returns

    true if the room's type is RoomType.ElementVideo

    Returns boolean

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

    Returns

    true if the room's type is RoomType.Space

    Returns boolean

  • Returns Promise<{
        fromServer: boolean;
        memberEvents: MatrixEvent[];
    }>

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

    Returns

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

    Returns Promise<boolean>

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

    Returns

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

    Returns boolean

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

    Parameters

    Returns void

  • Experimental

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

    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.

    Fires

    module:client~MatrixClient#event:"Room.name"

    Returns void

  • 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.HistoryImportedWithinTimelineevent when we detect a valid marker and can check the needs refresh status viaroom.getTimelineNeedsRefresh()`.

    Returns Promise<void>

  • Removes a single event from this room.

    Returns

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

    Parameters

    • eventId: string

      The id of the event to remove

    Returns boolean

  • 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

    Returns

    True if an element was removed.

    Parameters

    • eventId: string

    Returns boolean

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

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

    Parameters

    • Optional backPaginationToken: null | string

      token for back-paginating the new timeline

    • Optional forwardPaginationToken: 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

  • Experimental

    Resets the thread notifications for this room

    Parameters

    • Optional notificationsToKeep: string[]

    Returns void

  • Persists all pending events to local storage

    If the current room is encrypted only encrypted events will be persisted all messages that are not yet encrypted will be discarded

    This is because the flow of EVENT_STATUS transition is queued => sending => encrypting => sending => sent

    Steps 3 and 4 are skipped for unencrypted room. It is better to discard an unencrypted message rather than persisting it locally for everyone to read

    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

  • Experimental

    Swet one of the notification count for a thread

    Returns

    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

    if we should encrypt messages for invited users

    Returns boolean

  • Determines whether this room needs to be upgraded to a new version

    Returns

    What version the room should be upgraded to, or null if the room does not require upgrading at this time.

    Deprecated

    Use #getRecommendedVersion() instead

    Returns null | string

  • 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.

    Fires

    module:client~MatrixClient#event:"Room.localEchoUpdated"

    Parameters

    • event: MatrixEvent

      local echo event

    • newStatus: EventStatus

      status to assign

    • Optional newEventId: string

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

    Returns void

  • Parameters

    • thread: Thread
    • toStartOfTimeline: boolean
    • recreateEvent: boolean

    Returns void

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

    Returns

    True if the given user is permitted to upgrade the room

    Parameters

    • userId: string

      The ID of the user to test against

    Returns boolean

Generated using TypeDoc