matrix-js-sdk
Version:
Matrix Client-Server SDK for Javascript
1,236 lines (1,127 loc) • 138 kB
text/typescript
/*
Copyright 2015 - 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @module models/room
*/
import { EventTimelineSet, DuplicateStrategy, IAddLiveEventOptions } from "./event-timeline-set";
import { Direction, EventTimeline } from "./event-timeline";
import { getHttpUriForMxc } from "../content-repo";
import * as utils from "../utils";
import { normalize } from "../utils";
import { IEvent, IThreadBundledRelationship, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from "./event";
import { EventStatus } from "./event-status";
import { RoomMember } from "./room-member";
import { IRoomSummary, RoomSummary } from "./room-summary";
import { logger } from '../logger';
import { TypedReEmitter } from '../ReEmitter';
import {
EventType, RoomCreateTypeField, RoomType, UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
EVENT_VISIBILITY_CHANGE_TYPE,
RelationType,
} from "../@types/event";
import { IRoomVersionsCapability, MatrixClient, PendingEventOrdering, RoomVersionStability } from "../client";
import { GuestAccess, HistoryVisibility, JoinRule, ResizeMethod } from "../@types/partials";
import { Filter, IFilterDefinition } from "../filter";
import { RoomState, RoomStateEvent, RoomStateEventHandlerMap } from "./room-state";
import { BeaconEvent, BeaconEventHandlerMap } from "./beacon";
import {
Thread,
ThreadEvent,
EventHandlerMap as ThreadHandlerMap,
FILTER_RELATED_BY_REL_TYPES, THREAD_RELATION_TYPE,
FILTER_RELATED_BY_SENDERS,
ThreadFilterType,
} from "./thread";
import { TypedEventEmitter } from "./typed-event-emitter";
import { ReceiptType } from "../@types/read_receipts";
import { IStateEventWithRoomId } from "../@types/search";
import { RelationsContainer } from "./relations-container";
// These constants are used as sane defaults when the homeserver doesn't support
// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be
// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the
// room versions which are considered okay for people to run without being asked
// to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers
// return an m.room_versions capability.
export const KNOWN_SAFE_ROOM_VERSION = '9';
const SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
function synthesizeReceipt(userId: string, event: MatrixEvent, receiptType: ReceiptType): MatrixEvent {
// console.log("synthesizing receipt for "+event.getId());
return new MatrixEvent({
content: {
[event.getId()]: {
[receiptType]: {
[userId]: {
ts: event.getTs(),
},
},
},
},
type: EventType.Receipt,
room_id: event.getRoomId(),
});
}
interface IOpts {
storageToken?: string;
pendingEventOrdering?: PendingEventOrdering;
timelineSupport?: boolean;
lazyLoadMembers?: boolean;
}
export interface IRecommendedVersion {
version: string;
needsUpgrade: boolean;
urgent: boolean;
}
interface IReceipt {
ts: number;
}
export interface IWrappedReceipt {
eventId: string;
data: IReceipt;
}
interface ICachedReceipt {
type: ReceiptType;
userId: string;
data: IReceipt;
}
type ReceiptCache = {[eventId: string]: ICachedReceipt[]};
interface IReceiptContent {
[eventId: string]: {
[key in ReceiptType]: {
[userId: string]: IReceipt;
};
};
}
const ReceiptPairRealIndex = 0;
const ReceiptPairSyntheticIndex = 1;
// We will only hold a synthetic receipt if we do not have a real receipt or the synthetic is newer.
type Receipts = {
[receiptType: string]: {
[userId: string]: [IWrappedReceipt, IWrappedReceipt]; // Pair<real receipt, synthetic receipt> (both nullable)
};
};
// When inserting a visibility event affecting event `eventId`, we
// need to scan through existing visibility events for `eventId`.
// In theory, this could take an unlimited amount of time if:
//
// - the visibility event was sent by a moderator; and
// - `eventId` already has many visibility changes (usually, it should
// be 2 or less); and
// - for some reason, the visibility changes are received out of order
// (usually, this shouldn't happen at all).
//
// For this reason, we limit the number of events to scan through,
// expecting that a broken visibility change for a single event in
// an extremely uncommon case (possibly a DoS) is a small
// price to pay to keep matrix-js-sdk responsive.
const MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;
export enum NotificationCountType {
Highlight = "highlight",
Total = "total",
}
export interface ICreateFilterOpts {
// Populate the filtered timeline with already loaded events in the room
// timeline. Useful to disable for some filters that can't be achieved by the
// client in an efficient manner
prepopulateTimeline?: boolean;
useSyncEvents?: boolean;
pendingEvents?: boolean;
}
export enum RoomEvent {
MyMembership = "Room.myMembership",
Tags = "Room.tags",
AccountData = "Room.accountData",
Receipt = "Room.receipt",
Name = "Room.name",
Redaction = "Room.redaction",
RedactionCancelled = "Room.redactionCancelled",
LocalEchoUpdated = "Room.localEchoUpdated",
Timeline = "Room.timeline",
TimelineReset = "Room.timelineReset",
TimelineRefresh = "Room.TimelineRefresh",
OldStateUpdated = "Room.OldStateUpdated",
CurrentStateUpdated = "Room.CurrentStateUpdated",
HistoryImportedWithinTimeline = "Room.historyImportedWithinTimeline",
}
type EmittedEvents = RoomEvent
| RoomStateEvent.Events
| RoomStateEvent.Members
| RoomStateEvent.NewMember
| RoomStateEvent.Update
| RoomStateEvent.Marker
| ThreadEvent.New
| ThreadEvent.Update
| ThreadEvent.NewReply
| MatrixEventEvent.BeforeRedaction
| BeaconEvent.New
| BeaconEvent.Update
| BeaconEvent.Destroy
| BeaconEvent.LivenessChange;
export type RoomEventHandlerMap = {
[RoomEvent.MyMembership]: (room: Room, membership: string, prevMembership?: string) => void;
[RoomEvent.Tags]: (event: MatrixEvent, room: Room) => void;
[RoomEvent.AccountData]: (event: MatrixEvent, room: Room, lastEvent?: MatrixEvent) => void;
[RoomEvent.Receipt]: (event: MatrixEvent, room: Room) => void;
[RoomEvent.Name]: (room: Room) => void;
[RoomEvent.Redaction]: (event: MatrixEvent, room: Room) => void;
[RoomEvent.RedactionCancelled]: (event: MatrixEvent, room: Room) => void;
[RoomEvent.LocalEchoUpdated]: (
event: MatrixEvent,
room: Room,
oldEventId?: string,
oldStatus?: EventStatus,
) => void;
[RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;
[RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;
[RoomEvent.HistoryImportedWithinTimeline]: (
markerEvent: MatrixEvent,
room: Room,
) => void;
[RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;
[ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;
} & ThreadHandlerMap
& MatrixEventHandlerMap
& Pick<
RoomStateEventHandlerMap,
RoomStateEvent.Events
| RoomStateEvent.Members
| RoomStateEvent.NewMember
| RoomStateEvent.Update
| RoomStateEvent.Marker
| BeaconEvent.New
>
& Pick<
BeaconEventHandlerMap,
BeaconEvent.Update | BeaconEvent.Destroy | BeaconEvent.LivenessChange
>;
export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap> {
public readonly reEmitter: TypedReEmitter<EmittedEvents, RoomEventHandlerMap>;
private txnToEvent: Record<string, MatrixEvent> = {}; // Pending in-flight requests { string: MatrixEvent }
// receipts should clobber based on receipt_type and user_id pairs hence
// the form of this structure. This is sub-optimal for the exposed APIs
// which pass in an event ID and get back some receipts, so we also store
// a pre-cached list for this purpose.
private receipts: Receipts = {}; // { receipt_type: { user_id: IReceipt } }
private receiptCacheByEventId: ReceiptCache = {}; // { event_id: ICachedReceipt[] }
private notificationCounts: Partial<Record<NotificationCountType, number>> = {};
private readonly timelineSets: EventTimelineSet[];
public readonly threadsTimelineSets: EventTimelineSet[] = [];
// any filtered timeline sets we're maintaining for this room
private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet
private timelineNeedsRefresh = false;
private readonly pendingEventList?: MatrixEvent[];
// read by megolm via getter; boolean value - null indicates "use global value"
private blacklistUnverifiedDevices: boolean = null;
private selfMembership: string = null;
private summaryHeroes: string[] = null;
// flags to stop logspam about missing m.room.create events
private getTypeWarning = false;
private getVersionWarning = false;
private membersPromise?: Promise<boolean>;
// XXX: These should be read-only
/**
* The human-readable display name for this room.
*/
public name: string;
/**
* The un-homoglyphed name for this room.
*/
public normalizedName: string;
/**
* 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 } }
*/
public tags: Record<string, Record<string, any>> = {}; // $tagName: { $metadata: $value }
/**
* accountData Dict of per-room account_data events; the keys are the
* event type and the values are the events.
*/
public accountData: Record<string, MatrixEvent> = {}; // $eventType: $event
/**
* The room summary.
*/
public summary: RoomSummary = null;
/**
* A token which a data store can use to remember the state of the room.
*/
public readonly storageToken?: string;
// legacy fields
/**
* The live event timeline for this room, with the oldest event at index 0.
* Present for backwards compatibility - prefer getLiveTimeline().getEvents()
*/
public timeline: MatrixEvent[];
/**
* 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).
*/
public oldState: 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).
*/
public currentState: RoomState;
public readonly relations = new RelationsContainer(this.client, this);
/**
* @experimental
*/
private threads = new Map<string, Thread>();
public lastThread: Thread;
/**
* 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`.
*
* @experimental
*/
private visibilityEvents = new Map<string, MatrixEvent[]>();
/**
* Construct a new Room.
*
* <p>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.
*
* <p>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.
*
* <p>In order that we can find events from their ids later, we also maintain a
* map from event_id to timeline and index.
*
* @constructor
* @alias module:models/room
* @param {string} roomId Required. The ID of this room.
* @param {MatrixClient} client Required. The client, used to lazy load members.
* @param {string} myUserId Required. The ID of the syncing user.
* @param {Object=} opts Configuration options
* @param {*} opts.storageToken Optional. The token which a data store can use
* to remember the state of the room. What this means is dependent on the store
* implementation.
*
* @param {String=} opts.pendingEventOrdering Controls where pending messages
* appear in a room's timeline. If "<b>chronological</b>", messages will appear
* in the timeline when the call to <code>sendEvent</code> was made. If
* "<b>detached</b>", pending messages will appear in a separate list,
* accessible via {@link module:models/room#getPendingEvents}. Default:
* "chronological".
* @param {boolean} [opts.timelineSupport = false] Set to true to enable improved
* timeline support.
*/
constructor(
public readonly roomId: string,
public readonly client: MatrixClient,
public readonly myUserId: string,
private readonly opts: IOpts = {},
) {
super();
// In some cases, we add listeners for every displayed Matrix event, so it's
// common to have quite a few more than the default limit.
this.setMaxListeners(100);
this.reEmitter = new TypedReEmitter(this);
opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;
this.name = roomId;
// all our per-room timeline sets. the first one is the unfiltered ones;
// the subsequent ones are the filtered ones in no particular order.
this.timelineSets = [new EventTimelineSet(this, opts)];
this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [
RoomEvent.Timeline,
RoomEvent.TimelineReset,
]);
this.fixUpLegacyTimelineFields();
if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {
this.pendingEventList = [];
this.client.store.getPendingEvents(this.roomId).then(events => {
events.forEach(async (serializedEvent: Partial<IEvent>) => {
const event = new MatrixEvent(serializedEvent);
if (event.getType() === EventType.RoomMessageEncrypted) {
await event.attemptDecryption(this.client.crypto);
}
event.setStatus(EventStatus.NOT_SENT);
this.addPendingEvent(event, event.getTxnId());
});
});
}
// awaited by getEncryptionTargetMembers while room members are loading
if (!this.opts.lazyLoadMembers) {
this.membersPromise = Promise.resolve(false);
} else {
this.membersPromise = null;
}
}
private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;
public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet]> {
if (this.threadTimelineSetsPromise) {
return this.threadTimelineSetsPromise;
}
if (this.client?.supportsExperimentalThreads()) {
try {
this.threadTimelineSetsPromise = Promise.all([
this.createThreadTimelineSet(),
this.createThreadTimelineSet(ThreadFilterType.My),
]);
const timelineSets = await this.threadTimelineSetsPromise;
this.threadsTimelineSets.push(...timelineSets);
} catch (e) {
this.threadTimelineSetsPromise = null;
}
}
}
/**
* 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} Signals when all events have been decrypted
*/
public decryptCriticalEvents(): Promise<void> {
const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId(), true);
const events = this.getLiveTimeline().getEvents();
const readReceiptTimelineIndex = events.findIndex(matrixEvent => {
return matrixEvent.event.event_id === readReceiptEventId;
});
const decryptionPromises = events
.slice(readReceiptTimelineIndex)
.filter(event => event.shouldAttemptDecryption())
.reverse()
.map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));
return Promise.allSettled(decryptionPromises) as unknown as Promise<void>;
}
/**
* Bulk decrypt events in a room
*
* @returns {Promise} Signals when all events have been decrypted
*/
public decryptAllEvents(): Promise<void> {
const decryptionPromises = this
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(event => event.shouldAttemptDecryption())
.reverse()
.map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));
return Promise.allSettled(decryptionPromises) as unknown as Promise<void>;
}
/**
* Gets the creator of the room
* @returns {string} The creator of the room, or null if it could not be determined
*/
public getCreator(): string | null {
const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
return createEvent?.getContent()['creator'] ?? null;
}
/**
* Gets the version of the room
* @returns {string} The version of the room, or null if it could not be determined
*/
public getVersion(): string | null {
const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
if (!createEvent) {
if (!this.getVersionWarning) {
logger.warn("[getVersion] Room " + this.roomId + " does not have an m.room.create event");
this.getVersionWarning = true;
}
return '1';
}
const ver = createEvent.getContent()['room_version'];
if (ver === undefined) return '1';
return ver;
}
/**
* Determines whether this room needs to be upgraded to a new version
* @returns {string?} What version the room should be upgraded to, or null if
* the room does not require upgrading at this time.
* @deprecated Use #getRecommendedVersion() instead
*/
public shouldUpgradeToVersion(): string | null {
// TODO: Remove this function.
// This makes assumptions about which versions are safe, and can easily
// be wrong. Instead, people are encouraged to use getRecommendedVersion
// which determines a safer value. This function doesn't use that function
// because this is not async-capable, and to avoid breaking the contract
// we're deprecating this.
if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {
return KNOWN_SAFE_ROOM_VERSION;
}
return null;
}
/**
* Determines the recommended room version for the room. This returns an
* object with 3 properties: <code>version</code> as the new version the
* room should be upgraded to (may be the same as the current version);
* <code>needsUpgrade</code> to indicate if the room actually can be
* upgraded (ie: does the current version not match?); and <code>urgent</code>
* to indicate if the new version patches a vulnerability in a previous
* version.
* @returns {Promise<{version: string, needsUpgrade: boolean, urgent: boolean}>}
* Resolves to the version the room should be upgraded to.
*/
public async getRecommendedVersion(): Promise<IRecommendedVersion> {
const capabilities = await this.client.getCapabilities();
let versionCap = capabilities["m.room_versions"];
if (!versionCap) {
versionCap = {
default: KNOWN_SAFE_ROOM_VERSION,
available: {},
};
for (const safeVer of SAFE_ROOM_VERSIONS) {
versionCap.available[safeVer] = RoomVersionStability.Stable;
}
}
let result = this.checkVersionAgainstCapability(versionCap);
if (result.urgent && result.needsUpgrade) {
// Something doesn't feel right: we shouldn't need to update
// because the version we're on should be in the protocol's
// namespace. This usually means that the server was updated
// before the client was, making us think the newest possible
// room version is not stable. As a solution, we'll refresh
// the capability we're using to determine this.
logger.warn(
"Refreshing room version capability because the server looks " +
"to be supporting a newer room version we don't know about.",
);
const caps = await this.client.getCapabilities(true);
versionCap = caps["m.room_versions"];
if (!versionCap) {
logger.warn("No room version capability - assuming upgrade required.");
return result;
} else {
result = this.checkVersionAgainstCapability(versionCap);
}
}
return result;
}
private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {
const currentVersion = this.getVersion();
logger.log(`[${this.roomId}] Current version: ${currentVersion}`);
logger.log(`[${this.roomId}] Version capability: `, versionCap);
const result = {
version: currentVersion,
needsUpgrade: false,
urgent: false,
};
// If the room is on the default version then nothing needs to change
if (currentVersion === versionCap.default) return result;
const stableVersions = Object.keys(versionCap.available)
.filter((v) => versionCap.available[v] === 'stable');
// Check if the room is on an unstable version. We determine urgency based
// off the version being in the Matrix spec namespace or not (if the version
// is in the current namespace and unstable, the room is probably vulnerable).
if (!stableVersions.includes(currentVersion)) {
result.version = versionCap.default;
result.needsUpgrade = true;
result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);
if (result.urgent) {
logger.warn(`URGENT upgrade required on ${this.roomId}`);
} else {
logger.warn(`Non-urgent upgrade required on ${this.roomId}`);
}
return result;
}
// The room is on a stable, but non-default, version by this point.
// No upgrade needed.
return result;
}
/**
* Determines whether the given user is permitted to perform a room upgrade
* @param {String} userId The ID of the user to test against
* @returns {boolean} True if the given user is permitted to upgrade the room
*/
public userMayUpgradeRoom(userId: string): boolean {
return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);
}
/**
* Get the list of pending sent events for this room
*
* @return {module:models/event.MatrixEvent[]} A list of the sent events
* waiting for remote echo.
*
* @throws If <code>opts.pendingEventOrdering</code> was not 'detached'
*/
public getPendingEvents(): MatrixEvent[] {
if (this.opts.pendingEventOrdering !== PendingEventOrdering.Detached) {
throw new Error(
"Cannot call getPendingEvents with pendingEventOrdering == " +
this.opts.pendingEventOrdering);
}
return this.pendingEventList;
}
/**
* Removes a pending event for this room
*
* @param {string} eventId
* @return {boolean} True if an element was removed.
*/
public removePendingEvent(eventId: string): boolean {
if (this.opts.pendingEventOrdering !== PendingEventOrdering.Detached) {
throw new Error(
"Cannot call removePendingEvent with pendingEventOrdering == " +
this.opts.pendingEventOrdering);
}
const removed = utils.removeElement(
this.pendingEventList,
function(ev) {
return ev.getId() == eventId;
}, false,
);
this.savePendingEvents();
return removed;
}
/**
* Check whether the pending event list contains a given event by ID.
* If pending event ordering is not "detached" then this returns false.
*
* @param {string} eventId The event ID to check for.
* @return {boolean}
*/
public hasPendingEvent(eventId: string): boolean {
if (this.opts.pendingEventOrdering !== PendingEventOrdering.Detached) {
return false;
}
return this.pendingEventList.some(event => event.getId() === eventId);
}
/**
* Get a specific event from the pending event list, if configured, null otherwise.
*
* @param {string} eventId The event ID to check for.
* @return {MatrixEvent}
*/
public getPendingEvent(eventId: string): MatrixEvent | null {
if (this.opts.pendingEventOrdering !== PendingEventOrdering.Detached) {
return null;
}
return this.pendingEventList.find(event => event.getId() === eventId);
}
/**
* Get the live unfiltered timeline for this room.
*
* @return {module:models/event-timeline~EventTimeline} live timeline
*/
public getLiveTimeline(): EventTimeline {
return this.getUnfilteredTimelineSet().getLiveTimeline();
}
/**
* Get the timestamp of the last message in the room
*
* @return {number} the timestamp of the last message in the room
*/
public getLastActiveTimestamp(): number {
const timeline = this.getLiveTimeline();
const events = timeline.getEvents();
if (events.length) {
const lastEvent = events[events.length - 1];
return lastEvent.getTs();
} else {
return Number.MIN_SAFE_INTEGER;
}
}
/**
* @return {string} the membership type (join | leave | invite) for the logged in user
*/
public getMyMembership(): string {
return this.selfMembership;
}
/**
* If this room is a DM we're invited to,
* try to find out who invited us
* @return {string} user id of the inviter
*/
public getDMInviter(): string {
if (this.myUserId) {
const me = this.getMember(this.myUserId);
if (me) {
return me.getDMInviter();
}
}
if (this.selfMembership === "invite") {
// fall back to summary information
const memberCount = this.getInvitedAndJoinedMemberCount();
if (memberCount == 2 && this.summaryHeroes.length) {
return this.summaryHeroes[0];
}
}
}
/**
* Assuming this room is a DM room, tries to guess with which user.
* @return {string} user id of the other member (could be syncing user)
*/
public guessDMUserId(): string {
const me = this.getMember(this.myUserId);
if (me) {
const inviterId = me.getDMInviter();
if (inviterId) {
return inviterId;
}
}
// remember, we're assuming this room is a DM,
// so returning the first member we find should be fine
const hasHeroes = Array.isArray(this.summaryHeroes) &&
this.summaryHeroes.length;
if (hasHeroes) {
return this.summaryHeroes[0];
}
const members = this.currentState.getMembers();
const anyMember = members.find((m) => m.userId !== this.myUserId);
if (anyMember) {
return anyMember.userId;
}
// it really seems like I'm the only user in the room
// so I probably created a room with just me in it
// and marked it as a DM. Ok then
return this.myUserId;
}
public getAvatarFallbackMember(): RoomMember {
const memberCount = this.getInvitedAndJoinedMemberCount();
if (memberCount > 2) {
return;
}
const hasHeroes = Array.isArray(this.summaryHeroes) &&
this.summaryHeroes.length;
if (hasHeroes) {
const availableMember = this.summaryHeroes.map((userId) => {
return this.getMember(userId);
}).find((member) => !!member);
if (availableMember) {
return availableMember;
}
}
const members = this.currentState.getMembers();
// could be different than memberCount
// as this includes left members
if (members.length <= 2) {
const availableMember = members.find((m) => {
return m.userId !== this.myUserId;
});
if (availableMember) {
return availableMember;
}
}
// if all else fails, try falling back to a user,
// and create a one-off member for it
if (hasHeroes) {
const availableUser = this.summaryHeroes.map((userId) => {
return this.client.getUser(userId);
}).find((user) => !!user);
if (availableUser) {
const member = new RoomMember(
this.roomId, availableUser.userId);
member.user = availableUser;
return member;
}
}
}
/**
* Sets the membership this room was received as during sync
* @param {string} membership join | leave | invite
*/
public updateMyMembership(membership: string): void {
const prevMembership = this.selfMembership;
this.selfMembership = membership;
if (prevMembership !== membership) {
if (membership === "leave") {
this.cleanupAfterLeaving();
}
this.emit(RoomEvent.MyMembership, this, membership, prevMembership);
}
}
private async loadMembersFromServer(): Promise<IStateEventWithRoomId[]> {
const lastSyncToken = this.client.store.getSyncToken();
const response = await this.client.members(this.roomId, undefined, "leave", lastSyncToken);
return response.chunk;
}
private async loadMembers(): Promise<{ memberEvents: MatrixEvent[], fromServer: boolean }> {
// were the members loaded from the server?
let fromServer = false;
let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);
// If the room is encrypted, we always fetch members from the server at
// least once, in case the latest state wasn't persisted properly. Note
// that this function is only called once (unless loading the members
// fails), since loadMembersIfNeeded always returns this.membersPromise
// if set, which will be the result of the first (successful) call.
if (rawMembersEvents === null ||
(this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId))
) {
fromServer = true;
rawMembersEvents = await this.loadMembersFromServer();
logger.log(`LL: got ${rawMembersEvents.length} ` +
`members from server for room ${this.roomId}`);
}
const memberEvents = rawMembersEvents.map(this.client.getEventMapper());
return { memberEvents, fromServer };
}
/**
* Preloads the member list in case lazy loading
* of memberships is in use. Can be called multiple times,
* it will only preload once.
* @return {Promise} when preloading is done and
* accessing the members on the room will take
* all members in the room into account
*/
public loadMembersIfNeeded(): Promise<boolean> {
if (this.membersPromise) {
return this.membersPromise;
}
// mark the state so that incoming messages while
// the request is in flight get marked as superseding
// the OOB members
this.currentState.markOutOfBandMembersStarted();
const inMemoryUpdate = this.loadMembers().then((result) => {
this.currentState.setOutOfBandMembers(result.memberEvents);
// now the members are loaded, start to track the e2e devices if needed
if (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId)) {
this.client.crypto.trackRoomDevices(this.roomId);
}
return result.fromServer;
}).catch((err) => {
// allow retries on fail
this.membersPromise = null;
this.currentState.markOutOfBandMembersFailed();
throw err;
});
// update members in storage, but don't wait for it
inMemoryUpdate.then((fromServer) => {
if (fromServer) {
const oobMembers = this.currentState.getMembers()
.filter((m) => m.isOutOfBand())
.map((m) => m.events.member.event as IStateEventWithRoomId);
logger.log(`LL: telling store to write ${oobMembers.length}`
+ ` members for room ${this.roomId}`);
const store = this.client.store;
return store.setOutOfBandMembers(this.roomId, oobMembers)
// swallow any IDB error as we don't want to fail
// because of this
.catch((err) => {
logger.log("LL: storing OOB room members failed, oh well",
err);
});
}
}).catch((err) => {
// as this is not awaited anywhere,
// at least show the error in the console
logger.error(err);
});
this.membersPromise = inMemoryUpdate;
return this.membersPromise;
}
/**
* Removes the lazily loaded members from storage if needed
*/
public async clearLoadedMembersIfNeeded(): Promise<void> {
if (this.opts.lazyLoadMembers && this.membersPromise) {
await this.loadMembersIfNeeded();
await this.client.store.clearOutOfBandMembers(this.roomId);
this.currentState.clearOutOfBandMembers();
this.membersPromise = null;
}
}
/**
* called when sync receives this room in the leave section
* to do cleanup after leaving a room. Possibly called multiple times.
*/
private cleanupAfterLeaving(): void {
this.clearLoadedMembersIfNeeded().catch((err) => {
logger.error(`error after clearing loaded members from ` +
`room ${this.roomId} after leaving`);
logger.log(err);
});
}
/**
* 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()`.
*/
public async refreshLiveTimeline(): Promise<void> {
const liveTimelineBefore = this.getLiveTimeline();
const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);
const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);
const eventsBefore = liveTimelineBefore.getEvents();
const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];
logger.log(
`[refreshLiveTimeline for ${this.roomId}] at ` +
`mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +
`liveTimelineBefore=${liveTimelineBefore.toString()} ` +
`forwardPaginationToken=${forwardPaginationToken} ` +
`backwardPaginationToken=${backwardPaginationToken}`,
);
// Get the main TimelineSet
const timelineSet = this.getUnfilteredTimelineSet();
let newTimeline: EventTimeline;
// If there isn't any event in the timeline, let's go fetch the latest
// event and construct a timeline from it.
//
// This should only really happen if the user ran into an error
// with refreshing the timeline before which left them in a blank
// timeline from `resetLiveTimeline`.
if (!mostRecentEventInTimeline) {
newTimeline = await this.client.getLatestTimeline(timelineSet);
} else {
// Empty out all of `this.timelineSets`. But we also need to keep the
// same `timelineSet` references around so the React code updates
// properly and doesn't ignore the room events we emit because it checks
// that the `timelineSet` references are the same. We need the
// `timelineSet` empty so that the `client.getEventTimeline(...)` call
// later, will call `/context` and create a new timeline instead of
// returning the same one.
this.resetLiveTimeline(null, null);
// Make the UI timeline show the new blank live timeline we just
// reset so that if the network fails below it's showing the
// accurate state of what we're working with instead of the
// disconnected one in the TimelineWindow which is just hanging
// around by reference.
this.emit(RoomEvent.TimelineRefresh, this, timelineSet);
// Use `client.getEventTimeline(...)` to construct a new timeline from a
// `/context` response state and events for the most recent event before
// we reset everything. The `timelineSet` we pass in needs to be empty
// in order for this function to call `/context` and generate a new
// timeline.
newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId());
}
// If a racing `/sync` beat us to creating a new timeline, use that
// instead because it's the latest in the room and any new messages in
// the scrollback will include the history.
const liveTimeline = timelineSet.getLiveTimeline();
if (!liveTimeline || (
liveTimeline.getPaginationToken(Direction.Forward) === null &&
liveTimeline.getPaginationToken(Direction.Backward) === null &&
liveTimeline.getEvents().length === 0
)) {
logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);
// Set the pagination token back to the live sync token (`null`) instead
// of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)
// so that it matches the next response from `/sync` and we can properly
// continue the timeline.
newTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);
// Set our new fresh timeline as the live timeline to continue syncing
// forwards and back paginating from.
timelineSet.setLiveTimeline(newTimeline);
// Fixup `this.oldstate` so that `scrollback` has the pagination tokens
// available
this.fixUpLegacyTimelineFields();
} else {
logger.log(
`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new ` +
`live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +
`this timeline will include the history.`,
);
}
// The timeline has now been refreshed ✅
this.setTimelineNeedsRefresh(false);
// Emit an event which clients can react to and re-load the timeline
// from the SDK
this.emit(RoomEvent.TimelineRefresh, this, timelineSet);
}
/**
* Reset the live timeline of all timelineSets, and start new ones.
*
* <p>This is used when /sync returns a 'limited' timeline.
*
* @param {string=} backPaginationToken token for back-paginating the new timeline
* @param {string=} forwardPaginationToken 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.
*/
public resetLiveTimeline(backPaginationToken: string | null, forwardPaginationToken: string | null): void {
for (let i = 0; i < this.timelineSets.length; i++) {
this.timelineSets[i].resetLiveTimeline(
backPaginationToken, forwardPaginationToken,
);
}
this.fixUpLegacyTimelineFields();
}
/**
* Fix up this.timeline, this.oldState and this.currentState
*
* @private
*/
private fixUpLegacyTimelineFields(): void {
const previousOldState = this.oldState;
const previousCurrentState = this.currentState;
// maintain this.timeline as a reference to the live timeline,
// and this.oldState and this.currentState as references to the
// state at the start and end of that timeline. These are more
// for backwards-compatibility than anything else.
this.timeline = this.getLiveTimeline().getEvents();
this.oldState = this.getLiveTimeline()
.getState(EventTimeline.BACKWARDS);
this.currentState = this.getLiveTimeline()
.getState(EventTimeline.FORWARDS);
// Let people know to register new listeners for the new state
// references. The reference won't necessarily change every time so only
// emit when we see a change.
if (previousOldState !== this.oldState) {
this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);
}
if (previousCurrentState !== this.currentState) {
this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);
// Re-emit various events on the current room state
// TODO: If currentState really only exists for backwards
// compatibility, shouldn't we be doing this some other way?
this.reEmitter.stopReEmitting(previousCurrentState, [
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update,
RoomStateEvent.Marker,
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange,
]);
this.reEmitter.reEmit(this.currentState, [
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update,
RoomStateEvent.Marker,
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange,
]);
}
}
/**
* 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.
*
* @return {boolean} the result
*/
public async hasUnverifiedDevices(): Promise<boolean> {
if (!this.client.isRoomEncrypted(this.roomId)) {
return false;
}
const e2eMembers = await this.getEncryptionTargetMembers();
for (const member of e2eMembers) {
const devices = this.client.getStoredDevicesForUser(member.userId);
if (devices.some((device) => device.isUnverified())) {
return true;
}
}
return false;
}
/**
* Return the timeline sets for this room.
* @return {EventTimelineSet[]} array of timeline sets for this room
*/
public getTimelineSets(): EventTimelineSet[] {
return this.timelineSets;
}
/**
* Helper to return the main unfiltered timeline set for this room
* @return {EventTimelineSet} room's unfiltered timeline set
*/
public getUnfilteredTimelineSet(): EventTimelineSet {
return this.timelineSets[0];
}
/**
* Get the timeline which contains the given event from the unfiltered set, if any
*
* @param {string} eventId event ID to look for
* @return {?module:models/event-timeline~EventTimeline} timeline containing
* the given event, or null if unknown
*/
public getTimelineForEvent(eventId: string): EventTimeline {
const event = this.findEventById(eventId);
const thread = this.findThreadForEvent(event);
if (thread) {
return thread.timelineSet.getLiveTimeline();
} else {
return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);
}
}
/**
* Add a new timeline to this room's unfiltered timeline set
*
* @return {module:models/event-timeline~EventTimeline} newly-created timeline
*/
public addTimeline(): EventTimeline {
return this.getUnfilteredTimelineSet().addTimeline();
}
/**
* Whether the timeline needs to be refreshed in order to pull in new
* historical messages that were imported.
* @param {Boolean} value The value to set
*/
public setTimelineNeedsRefresh(value: boolean): void {
this.timelineNeedsRefresh = value;
}
/**
* Whether the timeline needs to be refreshed in order to pull in new
* historical messages that were imported.
* @return {Boolean} .
*/
public getTimelineNeedsRefresh(): boolean {
return this.timelineNeedsRefresh;
}
/**
* Get an event which is stored in our unfiltered timeline set, or in a thread
*
* @param {string} eventId event ID to look for
* @return {?module:models/event.MatrixEvent} the given event, or undefined if unknown
*/
public findEventById(eventId: string): MatrixEvent | undefined {
let event = this.getUnfilteredTimelineSet().findEventById(eventId);
if (!event) {
const threads = this.getThreads();
for (let i = 0; i < threads.length; i++) {
const thread = threads[i];
event = thread.findEventById(eventId);
if (event) {
return event;
}
}
}
return event;
}
/**
* Get one of the notification counts for this room
* @param {String} type The type of notification count to get. default: 'total'
* @return {Number} The notification count, or undefined if there is no count
* for this type.
*/
public getUnreadNotificationCount(type = NotificationCountType.Total): number | undefined {
return this.notificationCounts[type];
}
/**
* Set one of the notification counts for this room
* @param {String} type The type of