UNPKG

matrix-js-sdk

Version:
1,112 lines (1,055 loc) 147 kB
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /* Copyright 2015 - 2023 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. */ import { M_POLL_START } from "matrix-events-sdk"; import { DuplicateStrategy, EventTimelineSet } from "./event-timeline-set.js"; import { Direction, EventTimeline } from "./event-timeline.js"; import { getHttpUriForMxc } from "../content-repo.js"; import * as utils from "../utils.js"; import { normalize, noUnsafeEventProps, removeElement } from "../utils.js"; import { MatrixEvent, MatrixEventEvent } from "./event.js"; import { EventStatus } from "./event-status.js"; import { RoomMember } from "./room-member.js"; import { RoomSummary } from "./room-summary.js"; import { logger } from "../logger.js"; import { TypedReEmitter } from "../ReEmitter.js"; import { EVENT_VISIBILITY_CHANGE_TYPE, EventType, RelationType, RoomCreateTypeField, RoomType, UNSIGNED_THREAD_ID_FIELD, UNSTABLE_ELEMENT_FUNCTIONAL_USERS } from "../@types/event.js"; import { PendingEventOrdering } from "../client.js"; import { Filter } from "../filter.js"; import { RoomStateEvent } from "./room-state.js"; import { BeaconEvent } from "./beacon.js"; import { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, Thread, THREAD_RELATION_TYPE, ThreadEvent, ThreadFilterType } from "./thread.js"; import { MAIN_ROOM_TIMELINE, ReceiptType } from "../@types/read_receipts.js"; import { RelationsContainer } from "./relations-container.js"; import { ReadReceipt, synthesizeReceipt } from "./read-receipt.js"; import { isPollEvent, Poll, PollEvent } from "./poll.js"; import { RoomReceipts } from "./room-receipts.js"; import { compareEventOrdering } from "./compare-event-ordering.js"; import { KnownMembership } from "../@types/membership.js"; import { RoomVersionStability } from "../serverCapabilities.js"; import { RoomStickyEventsStore, RoomStickyEventsEvent } from "./room-sticky-events.js"; // 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 var KNOWN_SAFE_ROOM_VERSION = "10"; var SAFE_ROOM_VERSIONS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; // 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. var MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30; export var NotificationCountType = /*#__PURE__*/function (NotificationCountType) { NotificationCountType["Highlight"] = "highlight"; NotificationCountType["Total"] = "total"; return NotificationCountType; }({}); export var RoomEvent = /*#__PURE__*/function (RoomEvent) { RoomEvent["MyMembership"] = "Room.myMembership"; RoomEvent["Tags"] = "Room.tags"; RoomEvent["AccountData"] = "Room.accountData"; RoomEvent["Receipt"] = "Room.receipt"; RoomEvent["Name"] = "Room.name"; RoomEvent["Redaction"] = "Room.redaction"; RoomEvent["RedactionCancelled"] = "Room.redactionCancelled"; RoomEvent["LocalEchoUpdated"] = "Room.localEchoUpdated"; RoomEvent["Timeline"] = "Room.timeline"; RoomEvent["TimelineReset"] = "Room.timelineReset"; RoomEvent["TimelineRefresh"] = "Room.TimelineRefresh"; RoomEvent["OldStateUpdated"] = "Room.OldStateUpdated"; RoomEvent["CurrentStateUpdated"] = "Room.CurrentStateUpdated"; RoomEvent["HistoryImportedWithinTimeline"] = "Room.historyImportedWithinTimeline"; RoomEvent["UnreadNotifications"] = "Room.UnreadNotifications"; RoomEvent["Summary"] = "Room.Summary"; return RoomEvent; }({}); export class Room extends ReadReceipt { /** * 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. * * @param roomId - Required. The ID of this room. * @param client - Required. The client, used to lazy load members. * @param myUserId - Required. The ID of the syncing user. * @param opts - Configuration options */ constructor(roomId, client, myUserId) { var _this; var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; // 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. super(); _this = this; this.roomId = roomId; this.client = client; this.myUserId = myUserId; this.opts = opts; _defineProperty(this, "reEmitter", void 0); _defineProperty(this, "txnToEvent", new Map()); // Pending in-flight requests { string: MatrixEvent } _defineProperty(this, "notificationCounts", {}); _defineProperty(this, "bumpStamp", undefined); _defineProperty(this, "threadNotifications", new Map()); _defineProperty(this, "cachedThreadReadReceipts", new Map()); // Useful to know at what point the current user has started using threads in this room _defineProperty(this, "oldestThreadedReceiptTs", Infinity); /** * A record of the latest unthread receipts per user * This is useful in determining whether a user has read a thread or not */ _defineProperty(this, "unthreadedReceipts", new Map()); _defineProperty(this, "timelineSets", void 0); _defineProperty(this, "polls", new Map()); /** * Empty array if the timeline sets have not been initialised. After initialisation: * 0: All threads * 1: Threads the current user has participated in */ _defineProperty(this, "threadsTimelineSets", []); // any filtered timeline sets we're maintaining for this room _defineProperty(this, "filteredTimelineSets", {}); // filter_id: timelineSet _defineProperty(this, "timelineNeedsRefresh", false); _defineProperty(this, "pendingEventList", void 0); // read by megolm via getter; boolean value - null indicates "use global value" _defineProperty(this, "blacklistUnverifiedDevices", void 0); _defineProperty(this, "selfMembership", void 0); /** * A `Hero` is a stripped `m.room.member` event which contains the important renderable fields from the event. * * It is used in MSC4186 (Simplified Sliding Sync) as a replacement for the old `summary` field. * * When we are doing old-style (`/v3/sync`) sync, we simulate the SSS behaviour by constructing * a `Hero` object based on the user id we get from the summary. Obviously, in that case, * the `Hero` will lack a `displayName` or `avatarUrl`. */ _defineProperty(this, "heroes", null); // flags to stop logspam about missing m.room.create events _defineProperty(this, "getTypeWarning", false); _defineProperty(this, "membersPromise", void 0); // XXX: These should be read-only /** * The human-readable display name for this room. */ _defineProperty(this, "name", void 0); /** * The un-homoglyphed name for this room. */ _defineProperty(this, "normalizedName", void 0); /** * 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 } }` */ _defineProperty(this, "tags", {}); // $tagName: { $metadata: $value } /** * accountData Dict of per-room account_data events; the keys are the * event type and the values are the events. */ _defineProperty(this, "accountData", new Map()); // $eventType: $event /** * The room summary. */ _defineProperty(this, "summary", null); /** * oldState The state of the room at the time of the oldest event in the live timeline. * * @deprecated Present for backwards compatibility. * Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead */ _defineProperty(this, "oldState", void 0); /** * currentState The state of the room at the time of the newest event in the timeline. * * @deprecated Present for backwards compatibility. * Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead. */ _defineProperty(this, "currentState", void 0); _defineProperty(this, "relations", void 0); /** * A collection of events known by the client * This is not a comprehensive list of the threads that exist in this room */ _defineProperty(this, "threads", new Map()); /** * 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 */ _defineProperty(this, "visibilityEvents", new Map()); /** * The latest receipts (synthetic and real) for each user in each thread * (and unthreaded). */ _defineProperty(this, "roomReceipts", new RoomReceipts(this)); /** * Stores and tracks sticky events */ _defineProperty(this, "stickyEvents", new RoomStickyEventsStore()); _defineProperty(this, "threadTimelineSetsPromise", null); _defineProperty(this, "threadsReady", false); _defineProperty(this, "updateThreadRootEvents", (thread, toStartOfTimeline, recreateEvent) => { if (thread.length) { var _this$threadsTimeline; this.updateThreadRootEvent((_this$threadsTimeline = this.threadsTimelineSets) === null || _this$threadsTimeline === void 0 ? void 0 : _this$threadsTimeline[0], thread, toStartOfTimeline, recreateEvent); if (thread.hasCurrentUserParticipated) { var _this$threadsTimeline2; this.updateThreadRootEvent((_this$threadsTimeline2 = this.threadsTimelineSets) === null || _this$threadsTimeline2 === void 0 ? void 0 : _this$threadsTimeline2[1], thread, toStartOfTimeline, recreateEvent); } } }); _defineProperty(this, "updateThreadRootEvent", (timelineSet, thread, toStartOfTimeline, recreateEvent) => { if (timelineSet && thread.rootEvent) { if (recreateEvent) { timelineSet.removeEvent(thread.id); } if (Thread.hasServerSideSupport) { timelineSet.addLiveEvent(thread.rootEvent, { duplicateStrategy: DuplicateStrategy.Replace, fromCache: false, roomState: this.currentState, addToState: false }); } else { timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline, addToState: false }); } } }); _defineProperty(this, "tryApplyRedaction", event => { // FIXME: apply redactions to notification list // NB: We continue to add the redaction event to the timeline at the // end of this function so clients can say "so and so redacted an event" // if they wish to. Also this may be needed to trigger an update. if (event.isRedaction()) { var redactId = event.event.redacts; // if we know about this event, redact its contents now. var redactedEvent = redactId ? this.findEventById(redactId) : undefined; if (redactId) { try { this.stickyEvents.handleRedaction(redactedEvent || redactId); } catch (ex) { // Non-critical failure, but we should warn. logger.error("Failed to handle redaction for sticky event", ex); } } if (redactedEvent) { this.applyEventAsRedaction(event, redactedEvent); } } else if (event.getType() === EventType.RoomMember) { var membership = event.getContent()["membership"]; if (membership !== KnownMembership.Ban && !(membership === KnownMembership.Leave && event.getStateKey() !== event.getSender())) { // Not a ban or kick, therefore not a membership event we care about here. return; } var redactEvents = event.getContent()["org.matrix.msc4293.redact_events"]; if (redactEvents !== true) { // Invalid or not set - nothing to redact. return; } var state = this.getLiveTimeline().getState(Direction.Forward); if (!state.maySendRedactionForEvent(event, event.getSender())) { // If the sender can't redact the membership event, then they won't be able to // redact any of the target's events either, so skip. return; } // The redaction is possible, so let's find all the events and apply it. var events = this.getTimelineSets().map(s => s.getTimelines()).reduce((p, c) => { p.push(...c); return p; }, []).map(t => t.getEvents().filter(e => e.getSender() === event.getStateKey())).reduce((p, c) => { p.push(...c); return c; }, []); for (var toRedact of events) { this.applyEventAsRedaction(event, toRedact); } } }); this.setMaxListeners(100); this.reEmitter = new TypedReEmitter(this); opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological; this.name = roomId; this.normalizedName = roomId; this.relations = new RelationsContainer(this.client, this); // Listen to our own receipt event as a more modular way of processing our own // receipts. No need to remove the listener: it's on ourself anyway. this.on(RoomEvent.Receipt, this.onReceipt); this.reEmitter.reEmit(this.stickyEvents, [RoomStickyEventsEvent.Update]); // 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 => { var mapper = this.client.getEventMapper({ decrypt: false }); events.forEach(/*#__PURE__*/function () { var _ref = _asyncToGenerator(function* (serializedEvent) { var event = mapper(serializedEvent); yield client.decryptEventIfNeeded(event); event.setStatus(EventStatus.NOT_SENT); _this.addPendingEvent(event, event.getTxnId()); }); return function (_x) { return _ref.apply(this, arguments); }; }()); }); } // awaited by getEncryptionTargetMembers while room members are loading if (!this.opts.lazyLoadMembers) { this.membersPromise = Promise.resolve(false); } else { this.membersPromise = undefined; } } createThreadsTimelineSets() { var _this2 = this; return _asyncToGenerator(function* () { var _this2$client; if (_this2.threadTimelineSetsPromise) { return _this2.threadTimelineSetsPromise; } if ((_this2$client = _this2.client) !== null && _this2$client !== void 0 && _this2$client.supportsThreads()) { try { _this2.threadTimelineSetsPromise = Promise.all([_this2.createThreadTimelineSet(), _this2.createThreadTimelineSet(ThreadFilterType.My)]); var timelineSets = yield _this2.threadTimelineSetsPromise; _this2.threadsTimelineSets[0] = timelineSets[0]; _this2.threadsTimelineSets[1] = timelineSets[1]; return timelineSets; } catch (_unused) { _this2.threadTimelineSetsPromise = null; return null; } } return 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 Signals when all events have been decrypted */ decryptCriticalEvents() { var _this3 = this; return _asyncToGenerator(function* () { if (!_this3.client.getCrypto()) return; var readReceiptEventId = _this3.getEventReadUpTo(_this3.client.getUserId(), true); var events = _this3.getLiveTimeline().getEvents(); var readReceiptTimelineIndex = events.findIndex(matrixEvent => { return matrixEvent.event.event_id === readReceiptEventId; }); var decryptionPromises = events.slice(readReceiptTimelineIndex).reverse().map(event => _this3.client.decryptEventIfNeeded(event)); yield Promise.allSettled(decryptionPromises); })(); } /** * Bulk decrypt events in a room * * @returns Signals when all events have been decrypted */ decryptAllEvents() { var _this4 = this; return _asyncToGenerator(function* () { if (!_this4.client.getCrypto()) return; var decryptionPromises = _this4.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0) // copy before reversing .reverse().map(event => _this4.client.decryptEventIfNeeded(event)); yield Promise.allSettled(decryptionPromises); })(); } /** * Gets the creator of the room * @returns The creator of the room, or null if it could not be determined */ getCreator() { var _createEvent$getSende; var createEvent = this.currentState.getStateEvents(EventType.RoomCreate, ""); return (_createEvent$getSende = createEvent === null || createEvent === void 0 ? void 0 : createEvent.getSender()) !== null && _createEvent$getSende !== void 0 ? _createEvent$getSende : null; } /** * Gets the version of the room * @returns The version of the room */ getVersion() { return this.currentState.getRoomVersion(); } /** * 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. */ getRecommendedVersion() { var _this5 = this; return _asyncToGenerator(function* () { var capabilities = {}; try { capabilities = yield _this5.client.getCapabilities(); } catch (_unused2) {} var versionCap = capabilities["m.room_versions"]; if (!versionCap) { versionCap = { default: KNOWN_SAFE_ROOM_VERSION, available: {} }; for (var safeVer of SAFE_ROOM_VERSIONS) { versionCap.available[safeVer] = RoomVersionStability.Stable; } } var result = _this5.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."); try { capabilities = yield _this5.client.fetchCapabilities(); } catch (e) { logger.warn("Failed to refresh room version capabilities", e); } versionCap = capabilities["m.room_versions"]; if (!versionCap) { logger.warn("No room version capability - assuming upgrade required."); return result; } else { result = _this5.checkVersionAgainstCapability(versionCap); } } return result; })(); } checkVersionAgainstCapability(versionCap) { var currentVersion = this.getVersion(); logger.log("[".concat(this.roomId, "] Current version: ").concat(currentVersion)); logger.log("[".concat(this.roomId, "] Version capability: "), versionCap); var 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; var 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 ".concat(this.roomId)); } else { logger.warn("Non-urgent upgrade required on ".concat(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 userId - The ID of the user to test against * @returns True if the given user is permitted to upgrade the room */ userMayUpgradeRoom(userId) { return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId); } /** * 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' */ getPendingEvents() { if (!this.pendingEventList) { throw new Error("Cannot call getPendingEvents with pendingEventOrdering == " + this.opts.pendingEventOrdering); } return this.pendingEventList; } /** * Removes a pending event for this room * * @returns True if an element was removed. */ removePendingEvent(eventId) { if (!this.pendingEventList) { throw new Error("Cannot call removePendingEvent with pendingEventOrdering == " + this.opts.pendingEventOrdering); } var removed = 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 eventId - The event ID to check for. */ hasPendingEvent(eventId) { var _this$pendingEventLis, _this$pendingEventLis2; return (_this$pendingEventLis = (_this$pendingEventLis2 = this.pendingEventList) === null || _this$pendingEventLis2 === void 0 ? void 0 : _this$pendingEventLis2.some(event => event.getId() === eventId)) !== null && _this$pendingEventLis !== void 0 ? _this$pendingEventLis : false; } /** * Get a specific event from the pending event list, if configured, null otherwise. * * @param eventId - The event ID to check for. */ getPendingEvent(eventId) { var _this$pendingEventLis3, _this$pendingEventLis4; return (_this$pendingEventLis3 = (_this$pendingEventLis4 = this.pendingEventList) === null || _this$pendingEventLis4 === void 0 ? void 0 : _this$pendingEventLis4.find(event => event.getId() === eventId)) !== null && _this$pendingEventLis3 !== void 0 ? _this$pendingEventLis3 : null; } /** * Get the live unfiltered timeline for this room. * * @returns live timeline */ getLiveTimeline() { return this.getUnfilteredTimelineSet().getLiveTimeline(); } /** * The live event timeline for this room, with the oldest event at index 0. * * @deprecated Present for backwards compatibility. * Use getLiveTimeline().getEvents() instead */ get timeline() { return this.getLiveTimeline().getEvents(); } /** * Get the timestamp of the last message in the room * * @returns the timestamp of the last message in the room */ getLastActiveTimestamp() { var timeline = this.getLiveTimeline(); var events = timeline.getEvents(); if (events.length) { var lastEvent = events[events.length - 1]; return lastEvent.getTs(); } else { return Number.MIN_SAFE_INTEGER; } } /** * 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 {@link 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 MatrixEvent if there is a last event; else undefined. */ getLastLiveEvent() { var _lastRoomEvent$getTs, _lastThreadEvent$getT; var roomEvents = this.getLiveTimeline().getEvents(); var lastRoomEvent = roomEvents[roomEvents.length - 1]; var lastThread = this.getLastThread(); if (!lastThread) return lastRoomEvent; var lastThreadEvent = lastThread.events[lastThread.events.length - 1]; return ((_lastRoomEvent$getTs = lastRoomEvent === null || lastRoomEvent === void 0 ? void 0 : lastRoomEvent.getTs()) !== null && _lastRoomEvent$getTs !== void 0 ? _lastRoomEvent$getTs : 0) > ((_lastThreadEvent$getT = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT !== void 0 ? _lastThreadEvent$getT : 0) ? lastRoomEvent : lastThreadEvent; } /** * 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 {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}. * * @returns the thread with the most recent event in its live time line. undefined if there is no thread. */ getLastThread() { return this.getThreads().reduce((lastThread, thread) => { var _threadEvent$getTs, _lastThreadEvent$getT2; if (!lastThread) return thread; var threadEvent = thread.events[thread.events.length - 1]; var lastThreadEvent = lastThread.events[lastThread.events.length - 1]; if (((_threadEvent$getTs = threadEvent === null || threadEvent === void 0 ? void 0 : threadEvent.getTs()) !== null && _threadEvent$getTs !== void 0 ? _threadEvent$getTs : 0) >= ((_lastThreadEvent$getT2 = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT2 !== void 0 ? _lastThreadEvent$getT2 : 0)) { // Last message of current thread is newer → new last thread. // Equal also means newer, because it was added to the thread map later. return thread; } return lastThread; }, undefined); } /** * @returns the membership type (join | leave | invite | knock) for the logged in user */ getMyMembership() { var _this$selfMembership; return (_this$selfMembership = this.selfMembership) !== null && _this$selfMembership !== void 0 ? _this$selfMembership : KnownMembership.Leave; } /** * If this room is a DM we're invited to, * try to find out who invited us * @returns user id of the inviter */ getDMInviter() { var me = this.getMember(this.myUserId); if (me) { return me.getDMInviter(); } if (this.selfMembership === KnownMembership.Invite) { // fall back to summary information var memberCount = this.getInvitedAndJoinedMemberCount(); if (memberCount === 2) { var _this$heroes; return (_this$heroes = this.heroes) === null || _this$heroes === void 0 || (_this$heroes = _this$heroes[0]) === null || _this$heroes === void 0 ? void 0 : _this$heroes.userId; } } } /** * Assuming this room is a DM room, tries to guess with which user. * @returns user id of the other member (could be syncing user) */ guessDMUserId() { var me = this.getMember(this.myUserId); if (me) { var 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 if (Array.isArray(this.heroes) && this.heroes.length) { return this.heroes[0].userId; } var members = this.currentState.getMembers(); var 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; } /** * Gets the "functional members" in this room. * * Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the * current membership states of those users. * * @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md. */ getFunctionalMembers() { var mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, ""); if (Array.isArray(mFunctionalMembers === null || mFunctionalMembers === void 0 ? void 0 : mFunctionalMembers.getContent().service_members)) { return mFunctionalMembers.getContent().service_members; } return []; } getAvatarFallbackMember() { var _this$heroes2; var functionalMembers = this.getFunctionalMembers(); // Only generate a fallback avatar if the conversation is with a single specific other user (a "DM"). var nonFunctionalMemberCount = 0; this.getMembers().forEach(m => { if (m.membership !== "join" && m.membership !== "invite") return; if (functionalMembers.includes(m.userId)) return; nonFunctionalMemberCount++; }); if (nonFunctionalMemberCount > 2) return; // Prefer the list of heroes, if present. It should only include the single other user in the DM. var nonFunctionalHeroes = (_this$heroes2 = this.heroes) === null || _this$heroes2 === void 0 ? void 0 : _this$heroes2.filter(h => !functionalMembers.includes(h.userId)); var hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length; if (hasHeroes) { // use first hero that has a display name or avatar url, or whose user ID // can be looked up as a member of the room for (var hero of nonFunctionalHeroes) { // If the hero was from a legacy sync (`/v3/sync`), we will need to look the user ID up in the room // the display name and avatar URL will not be set. if (!hero.fromMSC4186) { // attempt to look up renderable fields from the m.room.member event if it exists var member = this.getMember(hero.userId); if (member) { return member; } } else { // use the Hero supplied values for the room member. // TODO: It's unfortunate that this function, which clearly only cares about the // avatar url, returns the entire RoomMember event. We need to fake an event // to meet this API shape. var heroMember = new RoomMember(this.roomId, hero.userId); // set the display name and avatar url heroMember.setMembershipEvent(new MatrixEvent({ // ensure it's unique even if we hit the same millisecond event_id: "$" + this.roomId + hero.userId + new Date().getTime(), type: EventType.RoomMember, state_key: hero.userId, content: { displayname: hero.displayName, avatar_url: hero.avatarUrl } })); return heroMember; } } var availableMember = nonFunctionalHeroes.map(hero => { return this.getMember(hero.userId); }).find(member => !!member); if (availableMember) { return availableMember; } } // Consider *all*, including previous, members, to generate the avatar for DMs where the other user left. // Needed to generate a matching avatar for rooms named "Empty Room (was Alice)". var members = this.getMembers(); var nonFunctionalMembers = members === null || members === void 0 ? void 0 : members.filter(m => !functionalMembers.includes(m.userId)); if (nonFunctionalMembers.length <= 2) { var _availableMember = nonFunctionalMembers.find(m => { return m.userId !== this.myUserId; }); if (_availableMember) { return _availableMember; } } // If all else failed, but the homeserver gave us heroes that previously could not be found in the room members, // trust and try falling back to a hero, creating a one-off member for it if (hasHeroes) { var availableUser = nonFunctionalHeroes.map(hero => { return this.client.getUser(hero.userId); }).find(user => !!user); if (availableUser) { var _member = new RoomMember(this.roomId, availableUser.userId); _member.user = availableUser; return _member; } } } /** * Sets the membership this room was received as during sync * @param membership - join | leave | invite */ updateMyMembership(membership) { var prevMembership = this.selfMembership; this.selfMembership = membership; if (prevMembership !== membership) { if (membership === KnownMembership.Leave) { this.cleanupAfterLeaving(); } this.emit(RoomEvent.MyMembership, this, membership, prevMembership); } } loadMembersFromServer() { var _this6 = this; return _asyncToGenerator(function* () { var lastSyncToken = _this6.client.store.getSyncToken(); var response = yield _this6.client.members(_this6.roomId, undefined, KnownMembership.Leave, lastSyncToken !== null && lastSyncToken !== void 0 ? lastSyncToken : undefined); return response.chunk; })(); } loadMembers() { var _this7 = this; return _asyncToGenerator(function* () { // were the members loaded from the server? var fromServer = false; var rawMembersEvents = yield _this7.client.store.getOutOfBandMembers(_this7.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 || _this7.hasEncryptionStateEvent()) { fromServer = true; rawMembersEvents = yield _this7.loadMembersFromServer(); logger.log("LL: got ".concat(rawMembersEvents.length, " ") + "members from server for room ".concat(_this7.roomId)); } var memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(_this7.client.getEventMapper()); return { memberEvents, fromServer }; })(); } /** * Check if loading of out-of-band-members has completed * * @returns 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. */ membersLoaded() { if (!this.opts.lazyLoadMembers) { return true; } return this.currentState.outOfBandMembersReady(); } /** * 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 */ loadMembersIfNeeded() { 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(); var inMemoryUpdate = this.loadMembers().then(result => { this.currentState.setOutOfBandMembers(result.memberEvents); // recalculate the room name: it may have been based on members, so may have changed this.recalculate(); return result.fromServer; }).catch(err => { // allow retries on fail this.membersPromise = undefined; this.currentState.markOutOfBandMembersFailed(); throw err; }); // update members in storage, but don't wait for it inMemoryUpdate.then(fromServer => { if (fromServer) { var oobMembers = this.currentState.getMembers().filter(m => m.isOutOfBand()).map(m => { var _m$events$member; return (_m$events$member = m.events.member) === null || _m$events$member === void 0 ? void 0 : _m$events$member.event; }); logger.log("LL: telling store to write ".concat(oobMembers.length) + " members for room ".concat(this.roomId)); var 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 */ clearLoadedMembersIfNeeded() { var _this8 = this; return _asyncToGenerator(function* () { if (_this8.opts.lazyLoadMembers && _this8.membersPromise) { yield _this8.loadMembersIfNeeded(); yield _this8.client.store.clearOutOfBandMembers(_this8.roomId); _this8.currentState.clearOutOfBandMembers(); _this8.membersPromise = undefined; } })(); } /** * called when sync receives this room in the leave section * to do cleanup after leaving a room. Possibly called multiple times. */ cleanupAfterLeaving() { this.clearLoadedMembersIfNeeded().catch(err => { logger.error("error after clearing loaded members from " + "room ".concat(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()`. */ refreshLiveTimeline() { var _this9 = this; return _asyncToGenerator(function* () { var liveTimelineBefore = _this9.getLiveTimeline(); var forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS); var backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS); var eventsBefore = liveTimelineBefore.getEvents(); var mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1]; logger.log("[refreshLiveTimeline for ".concat(_this9.roomId, "] at ") + "mostRecentEventInTimeline=".concat(mostRecentEventInTimeline && mostRecentEventInTimeline.getId(), " ") + "liveTimelineBefore=".concat(liveTimelineBefore.toString(), " ") + "forwardPaginationToken=".concat(forwardPaginationToken, " ") + "backwardPaginationToken=".concat(backwardPaginationToken)); // Get the main TimelineSet var timelineSet = _this9.getUnfilteredTimelineSet(); var newTimeline = null; // 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 = yield _this9.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. _this9.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. _this9.emit(RoomEvent.TimelineRefresh, _this9, 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 = yield _this9.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. var liveTimeline = timelineSet.getLiveTimeline(); if (!liveTimeline || liveTimeline.getPaginationToken(Direction.Forward) === null && liveTimeline.getPaginationToken(Direction.Backward) === null && liveTimeline.getEvents().length === 0) { logger.log("[refreshLiveTimeline for ".concat(_this9.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 _this9.fixUpLegacyTimelineFields(); } else { logger.log("[refreshLiveTimeline for ".concat(_this9.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 ✅ _this9.setTimelineNeedsRefresh(false); // Emit an event which clients can react to and re-load the timeline // from the SDK _this9.emit(RoomEvent.TimelineRefresh, _this9, timelineSet); })(); } /** * Reset the live timeline of all timelineSets, and start new ones. * * <p>This is used when /sync returns a 'limited' timeline. * * @param backPaginationToken - token for back-paginating the new timeline * @param 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. */ resetLiveTimeline(backPaginationToken, forwardPaginationToken) { for (var timelineSet of this.timelineSets) { timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : undefined, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : undefined); } for (var thread of this.threads.values()) { thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken); } this.fixUpLegacyTimelineFields(); } /** * Fix up this.timeline, this.oldState and this.currentState * * @internal */ fixUpLegacyTimelineFields() { var previousOldState = this.oldState; var previousCurrentState = this.currentState; // maintain 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.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.Ev