Merge branch 'develop' of github.com:matrix-org/matrix-react-sdk into t3chguy/fix/18088
Conflicts: src/components/structures/LoggedInView.tsx src/stores/SpaceStore.tsx
This commit is contained in:
commit
a688e5b8b3
318 changed files with 7386 additions and 4032 deletions
|
@ -37,6 +37,10 @@ export enum RightPanelPhases {
|
|||
SpaceMemberList = "SpaceMemberList",
|
||||
SpaceMemberInfo = "SpaceMemberInfo",
|
||||
Space3pidMemberInfo = "Space3pidMemberInfo",
|
||||
|
||||
// Thread stuff
|
||||
ThreadView = "ThreadView",
|
||||
ThreadPanel = "ThreadPanel",
|
||||
}
|
||||
|
||||
// These are the phases that are safe to persist (the ones that don't require additional
|
||||
|
|
|
@ -19,7 +19,7 @@ import { ListIteratee, Many, sortBy, throttle } from "lodash";
|
|||
import { EventType, RoomType } from "matrix-js-sdk/src/@types/event";
|
||||
import { Room } from "matrix-js-sdk/src/models/room";
|
||||
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
|
||||
import { ISpaceSummaryRoom } from "matrix-js-sdk/src/@types/spaces";
|
||||
import { IHierarchyRoom } from "matrix-js-sdk/src/@types/spaces";
|
||||
import { JoinRule } from "matrix-js-sdk/src/@types/partials";
|
||||
import { IRoomCapability } from "matrix-js-sdk/src/client";
|
||||
|
||||
|
@ -64,7 +64,7 @@ export const UPDATE_SELECTED_SPACE = Symbol("selected-space");
|
|||
export const UPDATE_HOME_BEHAVIOUR = Symbol("home-behaviour");
|
||||
// Space Room ID/HOME_SPACE will be emitted when a Space's children change
|
||||
|
||||
export interface ISuggestedRoom extends ISpaceSummaryRoom {
|
||||
export interface ISuggestedRoom extends IHierarchyRoom {
|
||||
viaServers: string[];
|
||||
}
|
||||
|
||||
|
@ -145,9 +145,9 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
return this._allRoomsInHome;
|
||||
}
|
||||
|
||||
public async setActiveRoomInSpace(space: Room | null): Promise<void> {
|
||||
public setActiveRoomInSpace(space: Room | null): void {
|
||||
if (space && !space.isSpaceRoom()) return;
|
||||
if (space !== this.activeSpace) await this.setActiveSpace(space);
|
||||
if (space !== this.activeSpace) this.setActiveSpace(space);
|
||||
|
||||
if (space) {
|
||||
const roomId = this.getNotificationState(space.roomId).getFirstRoomWithNotifications();
|
||||
|
@ -190,7 +190,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
* @param contextSwitch whether to switch the user's context,
|
||||
* should not be done when the space switch is done implicitly due to another event like switching room.
|
||||
*/
|
||||
public async setActiveSpace(space: Room | null, contextSwitch = true) {
|
||||
public setActiveSpace(space: Room | null, contextSwitch = true) {
|
||||
if (space === this.activeSpace || (space && !space.isSpaceRoom())) return;
|
||||
|
||||
this._activeSpace = space;
|
||||
|
@ -293,28 +293,34 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
}
|
||||
|
||||
if (space) {
|
||||
const suggestedRooms = await this.fetchSuggestedRooms(space);
|
||||
if (this._activeSpace === space) {
|
||||
this._suggestedRooms = suggestedRooms;
|
||||
this.emit(SUGGESTED_ROOMS, this._suggestedRooms);
|
||||
}
|
||||
this.loadSuggestedRooms(space);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadSuggestedRooms(space) {
|
||||
const suggestedRooms = await this.fetchSuggestedRooms(space);
|
||||
if (this._activeSpace === space) {
|
||||
this._suggestedRooms = suggestedRooms;
|
||||
this.emit(SUGGESTED_ROOMS, this._suggestedRooms);
|
||||
}
|
||||
}
|
||||
|
||||
public fetchSuggestedRooms = async (space: Room, limit = MAX_SUGGESTED_ROOMS): Promise<ISuggestedRoom[]> => {
|
||||
try {
|
||||
const data = await this.matrixClient.getSpaceSummary(space.roomId, 0, true, false, limit);
|
||||
const { rooms } = await this.matrixClient.getRoomHierarchy(space.roomId, limit, 1, true);
|
||||
|
||||
const viaMap = new EnhancedMap<string, Set<string>>();
|
||||
data.events.forEach(ev => {
|
||||
if (ev.type === EventType.SpaceChild && ev.content.via?.length) {
|
||||
ev.content.via.forEach(via => {
|
||||
viaMap.getOrCreate(ev.state_key, new Set()).add(via);
|
||||
});
|
||||
}
|
||||
rooms.forEach(room => {
|
||||
room.children_state.forEach(ev => {
|
||||
if (ev.type === EventType.SpaceChild && ev.content.via?.length) {
|
||||
ev.content.via.forEach(via => {
|
||||
viaMap.getOrCreate(ev.state_key, new Set()).add(via);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return data.rooms.filter(roomInfo => {
|
||||
return rooms.filter(roomInfo => {
|
||||
return roomInfo.room_type !== RoomType.Space
|
||||
&& this.matrixClient.getRoom(roomInfo.room_id)?.getMyMembership() !== "join";
|
||||
}).map(roomInfo => ({
|
||||
|
@ -664,6 +670,14 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
this.onSpaceUpdate();
|
||||
this.emit(room.roomId);
|
||||
}
|
||||
|
||||
if (room === this.activeSpace && // current space
|
||||
this.matrixClient.getRoom(ev.getStateKey())?.getMyMembership() !== "join" && // target not joined
|
||||
ev.getPrevContent().suggested !== ev.getContent().suggested // suggested flag changed
|
||||
) {
|
||||
this.loadSuggestedRooms(room);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case EventType.SpaceParent:
|
||||
|
@ -676,12 +690,14 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
}
|
||||
this.emit(room.roomId);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
case EventType.RoomMember:
|
||||
if (room.isSpaceRoom()) {
|
||||
this.onSpaceMembersChange(ev);
|
||||
}
|
||||
break;
|
||||
// listening for m.room.member events in onRoomState above doesn't work as the Member object isn't updated by then
|
||||
private onRoomStateMembers = (ev: MatrixEvent) => {
|
||||
const room = this.matrixClient.getRoom(ev.getRoomId());
|
||||
if (room?.isSpaceRoom()) {
|
||||
this.onSpaceMembersChange(ev);
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -741,6 +757,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
this.matrixClient.removeListener("Room.myMembership", this.onRoom);
|
||||
this.matrixClient.removeListener("Room.accountData", this.onRoomAccountData);
|
||||
this.matrixClient.removeListener("RoomState.events", this.onRoomState);
|
||||
this.matrixClient.removeListener("RoomState.members", this.onRoomStateMembers);
|
||||
this.matrixClient.removeListener("accountData", this.onAccountData);
|
||||
}
|
||||
await this.reset();
|
||||
|
@ -752,6 +769,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
this.matrixClient.on("Room.myMembership", this.onRoom);
|
||||
this.matrixClient.on("Room.accountData", this.onRoomAccountData);
|
||||
this.matrixClient.on("RoomState.events", this.onRoomState);
|
||||
this.matrixClient.on("RoomState.members", this.onRoomStateMembers);
|
||||
this.matrixClient.on("accountData", this.onAccountData);
|
||||
|
||||
this.matrixClient.getCapabilities().then(capabilities => {
|
||||
|
@ -764,8 +782,8 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
|
|||
// restore selected state from last session if any and still valid
|
||||
const lastSpaceId = window.localStorage.getItem(ACTIVE_SPACE_LS_KEY);
|
||||
if (lastSpaceId) {
|
||||
// only context switch if our view is looking at a room, rather than e.g a community
|
||||
this.setActiveSpace(this.matrixClient.getRoom(lastSpaceId), !!RoomViewStore.getRoomId());
|
||||
// don't context switch here as it may break permalinks
|
||||
this.setActiveSpace(this.matrixClient.getRoom(lastSpaceId), false);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -137,6 +137,20 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
|
|||
if (edited && !this.roomMap.has(room.roomId)) {
|
||||
this.roomMap.set(room.roomId, roomInfo);
|
||||
}
|
||||
|
||||
// If a persistent widget is active, check to see if it's just been removed.
|
||||
// If it has, it needs to destroyed otherwise unmounting the node won't kill it
|
||||
const persistentWidgetId = ActiveWidgetStore.getPersistentWidgetId();
|
||||
if (persistentWidgetId) {
|
||||
if (
|
||||
ActiveWidgetStore.getRoomId(persistentWidgetId) === room.roomId &&
|
||||
!roomInfo.widgets.some(w => w.id === persistentWidgetId)
|
||||
) {
|
||||
console.log(`Persistent widget ${persistentWidgetId} removed from room ${room.roomId}: destroying.`);
|
||||
ActiveWidgetStore.destroyPersistentWidget(persistentWidgetId);
|
||||
}
|
||||
}
|
||||
|
||||
this.emit(room.roomId);
|
||||
}
|
||||
|
||||
|
|
|
@ -71,7 +71,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
|
||||
private readonly watchedSettings = [
|
||||
'feature_custom_tags',
|
||||
'advancedRoomListLogging', // TODO: Remove watch: https://github.com/vector-im/element-web/issues/14602
|
||||
];
|
||||
|
||||
constructor() {
|
||||
|
@ -122,8 +121,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
this.readyStore.useUnitTestClient(forcedClient);
|
||||
}
|
||||
|
||||
this.checkLoggingEnabled();
|
||||
|
||||
for (const settingName of this.watchedSettings) SettingsStore.monitorSetting(settingName, null);
|
||||
RoomViewStore.addListener(() => this.handleRVSUpdate({}));
|
||||
this.algorithm.on(LIST_UPDATED_EVENT, this.onAlgorithmListUpdated);
|
||||
|
@ -141,12 +138,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
this.updateFn.trigger();
|
||||
}
|
||||
|
||||
private checkLoggingEnabled() {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
console.warn("Advanced room list logging is enabled");
|
||||
}
|
||||
}
|
||||
|
||||
private async readAndCacheSettingsFromStore() {
|
||||
const tagsEnabled = SettingsStore.getValue("feature_custom_tags");
|
||||
await this.updateState({
|
||||
|
@ -172,10 +163,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
console.warn(`${activeRoomId} is current in RVS but missing from client - clearing sticky room`);
|
||||
this.algorithm.setStickyRoom(null);
|
||||
} else if (activeRoom !== this.algorithm.stickyRoom) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Changing sticky room to ${activeRoomId}`);
|
||||
}
|
||||
this.algorithm.setStickyRoom(activeRoom);
|
||||
}
|
||||
}
|
||||
|
@ -218,14 +205,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
if (payload.action === Action.SettingUpdated) {
|
||||
const settingUpdatedPayload = payload as SettingUpdatedPayload;
|
||||
if (this.watchedSettings.includes(settingUpdatedPayload.settingName)) {
|
||||
// TODO: Remove with https://github.com/vector-im/element-web/issues/14602
|
||||
if (settingUpdatedPayload.settingName === "advancedRoomListLogging") {
|
||||
// Log when the setting changes so we know when it was turned on in the rageshake
|
||||
const enabled = SettingsStore.getValue("advancedRoomListLogging");
|
||||
console.warn("Advanced room list logging is enabled? " + enabled);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Regenerating room lists: Settings changed");
|
||||
await this.readAndCacheSettingsFromStore();
|
||||
|
||||
|
@ -248,20 +227,12 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
console.warn(`Own read receipt was in unknown room ${room.roomId}`);
|
||||
return;
|
||||
}
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Got own read receipt in ${room.roomId}`);
|
||||
}
|
||||
await this.handleRoomUpdate(room, RoomUpdateCause.ReadReceipt);
|
||||
this.updateFn.trigger();
|
||||
return;
|
||||
}
|
||||
} else if (payload.action === 'MatrixActions.Room.tags') {
|
||||
const roomPayload = (<any>payload); // TODO: Type out the dispatcher types
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Got tag change in ${roomPayload.room.roomId}`);
|
||||
}
|
||||
await this.handleRoomUpdate(roomPayload.room, RoomUpdateCause.PossibleTagChange);
|
||||
this.updateFn.trigger();
|
||||
} else if (payload.action === 'MatrixActions.Room.timeline') {
|
||||
|
@ -273,16 +244,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
const roomId = eventPayload.event.getRoomId();
|
||||
const room = this.matrixClient.getRoom(roomId);
|
||||
const tryUpdate = async (updatedRoom: Room) => {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Live timeline event ${eventPayload.event.getId()}` +
|
||||
` in ${updatedRoom.roomId}`);
|
||||
}
|
||||
if (eventPayload.event.getType() === 'm.room.tombstone' && eventPayload.event.getStateKey() === '') {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Got tombstone event - trying to remove now-dead room`);
|
||||
}
|
||||
const newRoom = this.matrixClient.getRoom(eventPayload.event.getContent()['replacement_room']);
|
||||
if (newRoom) {
|
||||
// If we have the new room, then the new room check will have seen the predecessor
|
||||
|
@ -315,18 +277,10 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
console.warn(`Event ${eventPayload.event.getId()} was decrypted in an unknown room ${roomId}`);
|
||||
return;
|
||||
}
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Decrypted timeline event ${eventPayload.event.getId()} in ${roomId}`);
|
||||
}
|
||||
await this.handleRoomUpdate(room, RoomUpdateCause.Timeline);
|
||||
this.updateFn.trigger();
|
||||
} else if (payload.action === 'MatrixActions.accountData' && payload.event_type === 'm.direct') {
|
||||
const eventPayload = (<any>payload); // TODO: Type out the dispatcher types
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Received updated DM map`);
|
||||
}
|
||||
const dmMap = eventPayload.event.getContent();
|
||||
for (const userId of Object.keys(dmMap)) {
|
||||
const roomIds = dmMap[userId];
|
||||
|
@ -350,54 +304,29 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
const oldMembership = getEffectiveMembership(membershipPayload.oldMembership);
|
||||
const newMembership = getEffectiveMembership(membershipPayload.membership);
|
||||
if (oldMembership !== EffectiveMembership.Join && newMembership === EffectiveMembership.Join) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Handling new room ${membershipPayload.room.roomId}`);
|
||||
}
|
||||
|
||||
// If we're joining an upgraded room, we'll want to make sure we don't proliferate
|
||||
// the dead room in the list.
|
||||
const createEvent = membershipPayload.room.currentState.getStateEvents("m.room.create", "");
|
||||
if (createEvent && createEvent.getContent()['predecessor']) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Room has a predecessor`);
|
||||
}
|
||||
const prevRoom = this.matrixClient.getRoom(createEvent.getContent()['predecessor']['room_id']);
|
||||
if (prevRoom) {
|
||||
const isSticky = this.algorithm.stickyRoom === prevRoom;
|
||||
if (isSticky) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Clearing sticky room due to room upgrade`);
|
||||
}
|
||||
this.algorithm.setStickyRoom(null);
|
||||
}
|
||||
|
||||
// Note: we hit the algorithm instead of our handleRoomUpdate() function to
|
||||
// avoid redundant updates.
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Removing previous room from room list`);
|
||||
}
|
||||
this.algorithm.handleRoomUpdate(prevRoom, RoomUpdateCause.RoomRemoved);
|
||||
}
|
||||
}
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Adding new room to room list`);
|
||||
}
|
||||
await this.handleRoomUpdate(membershipPayload.room, RoomUpdateCause.NewRoom);
|
||||
this.updateFn.trigger();
|
||||
return;
|
||||
}
|
||||
|
||||
if (oldMembership !== EffectiveMembership.Invite && newMembership === EffectiveMembership.Invite) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Handling invite to ${membershipPayload.room.roomId}`);
|
||||
}
|
||||
await this.handleRoomUpdate(membershipPayload.room, RoomUpdateCause.NewRoom);
|
||||
this.updateFn.trigger();
|
||||
return;
|
||||
|
@ -405,10 +334,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
|
||||
// If it's not a join, it's transitioning into a different list (possibly historical)
|
||||
if (oldMembership !== newMembership) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Handling membership change in ${membershipPayload.room.roomId}`);
|
||||
}
|
||||
await this.handleRoomUpdate(membershipPayload.room, RoomUpdateCause.PossibleTagChange);
|
||||
this.updateFn.trigger();
|
||||
return;
|
||||
|
@ -438,10 +363,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
|
||||
const shouldUpdate = this.algorithm.handleRoomUpdate(room, cause);
|
||||
if (shouldUpdate) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[DEBUG] Room "${room.name}" (${room.roomId}) triggered by ${cause} requires list update`);
|
||||
}
|
||||
this.updateFn.mark();
|
||||
}
|
||||
}
|
||||
|
@ -450,11 +371,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
if (!this.algorithm) return;
|
||||
if (!this.algorithm.hasTagSortingMap) return; // we're still loading
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log("Calculating new prefiltered room list");
|
||||
}
|
||||
|
||||
// Inhibit updates because we're about to lie heavily to the algorithm
|
||||
this.algorithm.updatesInhibited = true;
|
||||
|
||||
|
@ -588,10 +504,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
}
|
||||
|
||||
private onAlgorithmListUpdated = () => {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log("Underlying algorithm has triggered a list update - marking");
|
||||
}
|
||||
this.updateFn.mark();
|
||||
};
|
||||
|
||||
|
@ -673,10 +585,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
* @param {IFilterCondition} filter The filter condition to add.
|
||||
*/
|
||||
public async addFilter(filter: IFilterCondition): Promise<void> {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log("Adding filter condition:", filter);
|
||||
}
|
||||
let promise = Promise.resolve();
|
||||
if (filter.kind === FilterKind.Prefilter) {
|
||||
filter.on(FILTER_CHANGED, this.onPrefilterUpdated);
|
||||
|
@ -705,10 +613,6 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
|
|||
* @param {IFilterCondition} filter The filter condition to remove.
|
||||
*/
|
||||
public removeFilter(filter: IFilterCondition): void {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log("Removing filter condition:", filter);
|
||||
}
|
||||
let promise = Promise.resolve();
|
||||
let idx = this.filterConditions.indexOf(filter);
|
||||
let removed = false;
|
||||
|
|
|
@ -33,7 +33,6 @@ import { FILTER_CHANGED, IFilterCondition } from "../filters/IFilterCondition";
|
|||
import { EffectiveMembership, getEffectiveMembership, splitRoomsByMembership } from "../../../utils/membership";
|
||||
import { OrderingAlgorithm } from "./list-ordering/OrderingAlgorithm";
|
||||
import { getListAlgorithmInstance } from "./list-ordering";
|
||||
import SettingsStore from "../../../settings/SettingsStore";
|
||||
import { VisibilityProvider } from "../filters/VisibilityProvider";
|
||||
import SpaceStore from "../../SpaceStore";
|
||||
|
||||
|
@ -343,11 +342,6 @@ export class Algorithm extends EventEmitter {
|
|||
}
|
||||
}
|
||||
newMap[tagId] = allowedRoomsInThisTag;
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[DEBUG] ${newMap[tagId].length}/${rooms.length} rooms filtered into ${tagId}`);
|
||||
}
|
||||
}
|
||||
|
||||
const allowedRooms = Object.values(newMap).reduce((rv, v) => { rv.push(...v); return rv; }, <Room[]>[]);
|
||||
|
@ -360,10 +354,6 @@ export class Algorithm extends EventEmitter {
|
|||
protected recalculateFilteredRoomsForTag(tagId: TagID): void {
|
||||
if (!this.hasFilters) return; // don't bother doing work if there's nothing to do
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Recalculating filtered rooms for ${tagId}`);
|
||||
}
|
||||
delete this.filteredRooms[tagId];
|
||||
const rooms = this.cachedRooms[tagId].map(r => r); // cheap clone
|
||||
this.tryInsertStickyRoomToFilterSet(rooms, tagId);
|
||||
|
@ -371,11 +361,6 @@ export class Algorithm extends EventEmitter {
|
|||
if (filteredRooms.length > 0) {
|
||||
this.filteredRooms[tagId] = filteredRooms;
|
||||
}
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[DEBUG] ${filteredRooms.length}/${rooms.length} rooms filtered into ${tagId}`);
|
||||
}
|
||||
}
|
||||
|
||||
protected tryInsertStickyRoomToFilterSet(rooms: Room[], tagId: TagID) {
|
||||
|
@ -415,10 +400,6 @@ export class Algorithm extends EventEmitter {
|
|||
}
|
||||
|
||||
if (!this._cachedStickyRooms || !updatedTag) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Generating clone of cached rooms for sticky room handling`);
|
||||
}
|
||||
const stickiedTagMap: ITagMap = {};
|
||||
for (const tagId of Object.keys(this.cachedRooms)) {
|
||||
stickiedTagMap[tagId] = this.cachedRooms[tagId].map(r => r); // shallow clone
|
||||
|
@ -429,10 +410,6 @@ export class Algorithm extends EventEmitter {
|
|||
if (updatedTag) {
|
||||
// Update the tag indicated by the caller, if possible. This is mostly to ensure
|
||||
// our cache is up to date.
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Replacing cached sticky rooms for ${updatedTag}`);
|
||||
}
|
||||
this._cachedStickyRooms[updatedTag] = this.cachedRooms[updatedTag].map(r => r); // shallow clone
|
||||
}
|
||||
|
||||
|
@ -441,12 +418,6 @@ export class Algorithm extends EventEmitter {
|
|||
// we might have updated from the cache is also our sticky room.
|
||||
const sticky = this._stickyRoom;
|
||||
if (!updatedTag || updatedTag === sticky.tag) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(
|
||||
`Inserting sticky room ${sticky.room.roomId} at position ${sticky.position} in ${sticky.tag}`,
|
||||
);
|
||||
}
|
||||
this._cachedStickyRooms[sticky.tag].splice(sticky.position, 0, sticky.room);
|
||||
}
|
||||
|
||||
|
@ -673,10 +644,6 @@ export class Algorithm extends EventEmitter {
|
|||
* should be called after processing.
|
||||
*/
|
||||
public handleRoomUpdate(room: Room, cause: RoomUpdateCause): boolean {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Handle room update for ${room.roomId} called with cause ${cause}`);
|
||||
}
|
||||
if (!this.algorithms) throw new Error("Not ready: no algorithms to determine tags from");
|
||||
|
||||
// Note: check the isSticky against the room ID just in case the reference is wrong
|
||||
|
@ -733,10 +700,6 @@ export class Algorithm extends EventEmitter {
|
|||
const diff = arrayDiff(oldTags, newTags);
|
||||
if (diff.removed.length > 0 || diff.added.length > 0) {
|
||||
for (const rmTag of diff.removed) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Removing ${room.roomId} from ${rmTag}`);
|
||||
}
|
||||
const algorithm: OrderingAlgorithm = this.algorithms[rmTag];
|
||||
if (!algorithm) throw new Error(`No algorithm for ${rmTag}`);
|
||||
algorithm.handleRoomUpdate(room, RoomUpdateCause.RoomRemoved);
|
||||
|
@ -745,10 +708,6 @@ export class Algorithm extends EventEmitter {
|
|||
this.recalculateStickyRoom(rmTag); // update sticky room to make sure it moves if needed
|
||||
}
|
||||
for (const addTag of diff.added) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Adding ${room.roomId} to ${addTag}`);
|
||||
}
|
||||
const algorithm: OrderingAlgorithm = this.algorithms[addTag];
|
||||
if (!algorithm) throw new Error(`No algorithm for ${addTag}`);
|
||||
algorithm.handleRoomUpdate(room, RoomUpdateCause.NewRoom);
|
||||
|
@ -758,17 +717,9 @@ export class Algorithm extends EventEmitter {
|
|||
// Update the tag map so we don't regen it in a moment
|
||||
this.roomIdsToTags[room.roomId] = newTags;
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Changing update cause for ${room.roomId} to Timeline to sort rooms`);
|
||||
}
|
||||
cause = RoomUpdateCause.Timeline;
|
||||
didTagChange = true;
|
||||
} else {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`Received no-op update for ${room.roomId} - changing to Timeline update`);
|
||||
}
|
||||
cause = RoomUpdateCause.Timeline;
|
||||
}
|
||||
|
||||
|
@ -794,28 +745,15 @@ export class Algorithm extends EventEmitter {
|
|||
// as the sticky room relies on this.
|
||||
if (cause !== RoomUpdateCause.NewRoom && cause !== RoomUpdateCause.RoomRemoved) {
|
||||
if (this.stickyRoom === room) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.warn(`[RoomListDebug] Received ${cause} update for sticky room ${room.roomId} - ignoring`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.roomIdsToTags[room.roomId]) {
|
||||
if (CAUSES_REQUIRING_ROOM.includes(cause)) {
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.warn(`Skipping tag update for ${room.roomId} because we don't know about the room`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Updating tags for room ${room.roomId} (${room.name})`);
|
||||
}
|
||||
|
||||
// Get the tags for the room and populate the cache
|
||||
const roomTags = this.getTagsForRoom(room).filter(t => !isNullOrUndefined(this.cachedRooms[t]));
|
||||
|
||||
|
@ -824,16 +762,6 @@ export class Algorithm extends EventEmitter {
|
|||
if (!roomTags.length) throw new Error(`Tags cannot be determined for ${room.roomId}`);
|
||||
|
||||
this.roomIdsToTags[room.roomId] = roomTags;
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Updated tags for ${room.roomId}:`, roomTags);
|
||||
}
|
||||
}
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Reached algorithmic handling for ${room.roomId} and cause ${cause}`);
|
||||
}
|
||||
|
||||
const tags = this.roomIdsToTags[room.roomId];
|
||||
|
@ -856,10 +784,6 @@ export class Algorithm extends EventEmitter {
|
|||
changed = true;
|
||||
}
|
||||
|
||||
if (SettingsStore.getValue("advancedRoomListLogging")) {
|
||||
// TODO: Remove debug: https://github.com/vector-im/element-web/issues/14602
|
||||
console.log(`[RoomListDebug] Finished handling ${room.roomId} with cause ${cause} (changed=${changed})`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,6 +20,27 @@ import { IAlgorithm } from "./IAlgorithm";
|
|||
import { MatrixClientPeg } from "../../../../MatrixClientPeg";
|
||||
import * as Unread from "../../../../Unread";
|
||||
import { EffectiveMembership, getEffectiveMembership } from "../../../../utils/membership";
|
||||
import { EventType } from "matrix-js-sdk/src/@types/event";
|
||||
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
|
||||
|
||||
export function shouldCauseReorder(event: MatrixEvent): boolean {
|
||||
const type = event.getType();
|
||||
const content = event.getContent();
|
||||
const prevContent = event.getPrevContent();
|
||||
|
||||
// Never ignore membership changes
|
||||
if (type === EventType.RoomMember && prevContent.membership !== content.membership) return true;
|
||||
|
||||
// Ignore status changes
|
||||
// XXX: This should be an enum
|
||||
if (type === "im.vector.user_status") return false;
|
||||
// Ignore display name changes
|
||||
if (type === EventType.RoomMember && prevContent.displayname !== content.displayname) return false;
|
||||
// Ignore avatar changes
|
||||
if (type === EventType.RoomMember && prevContent.avatar_url !== content.avatar_url) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export const sortRooms = (rooms: Room[]): Room[] => {
|
||||
// We cache the timestamp lookup to avoid iterating forever on the timeline
|
||||
|
@ -68,7 +89,10 @@ export const sortRooms = (rooms: Room[]): Room[] => {
|
|||
const ev = r.timeline[i];
|
||||
if (!ev.getTs()) continue; // skip events that don't have timestamps (tests only?)
|
||||
|
||||
if (ev.getSender() === myUserId || Unread.eventTriggersUnreadCount(ev)) {
|
||||
if (
|
||||
(ev.getSender() === myUserId && shouldCauseReorder(ev)) ||
|
||||
Unread.eventTriggersUnreadCount(ev)
|
||||
) {
|
||||
return ev.getTs();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2020, 2021 The Matrix.org Foundation C.I.C.
|
||||
* Copyright 2020 - 2021 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.
|
||||
|
@ -55,6 +55,7 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event";
|
|||
import { ELEMENT_CLIENT_ID } from "../../identifiers";
|
||||
import { getUserLanguage } from "../../languageHandler";
|
||||
import { WidgetVariableCustomisations } from "../../customisations/WidgetVariables";
|
||||
import { arrayFastClone } from "../../utils/arrays";
|
||||
|
||||
// TODO: Destroy all of this code
|
||||
|
||||
|
@ -146,6 +147,7 @@ export class StopGapWidget extends EventEmitter {
|
|||
private scalarToken: string;
|
||||
private roomId?: string;
|
||||
private kind: WidgetKind;
|
||||
private readUpToMap: {[roomId: string]: string} = {}; // room ID to event ID
|
||||
|
||||
constructor(private appTileProps: IAppTileProps) {
|
||||
super();
|
||||
|
@ -294,6 +296,17 @@ export class StopGapWidget extends EventEmitter {
|
|||
this.messaging.transport.reply(ev.detail, <IWidgetApiRequestEmptyData>{});
|
||||
});
|
||||
|
||||
// Populate the map of "read up to" events for this widget with the current event in every room.
|
||||
// This is a bit inefficient, but should be okay. We do this for all rooms in case the widget
|
||||
// requests timeline capabilities in other rooms down the road. It's just easier to manage here.
|
||||
for (const room of MatrixClientPeg.get().getRooms()) {
|
||||
// Timelines are most recent last
|
||||
const events = room.getLiveTimeline()?.getEvents() || [];
|
||||
const roomEvent = events[events.length - 1];
|
||||
if (!roomEvent) continue; // force later code to think the room is fresh
|
||||
this.readUpToMap[room.roomId] = roomEvent.getId();
|
||||
}
|
||||
|
||||
// Attach listeners for feeding events - the underlying widget classes handle permissions for us
|
||||
MatrixClientPeg.get().on('event', this.onEvent);
|
||||
MatrixClientPeg.get().on('Event.decrypted', this.onEventDecrypted);
|
||||
|
@ -408,21 +421,56 @@ export class StopGapWidget extends EventEmitter {
|
|||
private onEvent = (ev: MatrixEvent) => {
|
||||
MatrixClientPeg.get().decryptEventIfNeeded(ev);
|
||||
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) return;
|
||||
if (ev.getRoomId() !== this.eventListenerRoomId) return;
|
||||
this.feedEvent(ev);
|
||||
};
|
||||
|
||||
private onEventDecrypted = (ev: MatrixEvent) => {
|
||||
if (ev.isDecryptionFailure()) return;
|
||||
if (ev.getRoomId() !== this.eventListenerRoomId) return;
|
||||
this.feedEvent(ev);
|
||||
};
|
||||
|
||||
private feedEvent(ev: MatrixEvent) {
|
||||
if (!this.messaging) return;
|
||||
|
||||
// Check to see if this event would be before or after our "read up to" marker. If it's
|
||||
// before, or we can't decide, then we assume the widget will have already seen the event.
|
||||
// If the event is after, or we don't have a marker for the room, then we'll send it through.
|
||||
//
|
||||
// This approach of "read up to" prevents widgets receiving decryption spam from startup or
|
||||
// receiving out-of-order events from backfill and such.
|
||||
const upToEventId = this.readUpToMap[ev.getRoomId()];
|
||||
if (upToEventId) {
|
||||
// Small optimization for exact match (prevent search)
|
||||
if (upToEventId === ev.getId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let isBeforeMark = true;
|
||||
|
||||
// Timelines are most recent last, so reverse the order and limit ourselves to 100 events
|
||||
// to avoid overusing the CPU.
|
||||
const timeline = MatrixClientPeg.get().getRoom(ev.getRoomId()).getLiveTimeline();
|
||||
const events = arrayFastClone(timeline.getEvents()).reverse().slice(0, 100);
|
||||
|
||||
for (const timelineEvent of events) {
|
||||
if (timelineEvent.getId() === upToEventId) {
|
||||
break;
|
||||
} else if (timelineEvent.getId() === ev.getId()) {
|
||||
isBeforeMark = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isBeforeMark) {
|
||||
// Ignore the event: it is before our interest.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.readUpToMap[ev.getRoomId()] = ev.getId();
|
||||
|
||||
const raw = ev.getEffectiveEvent();
|
||||
this.messaging.feedEvent(raw).catch(e => {
|
||||
this.messaging.feedEvent(raw, this.eventListenerRoomId).catch(e => {
|
||||
console.error("Error sending event to widget: ", e);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2020 The Matrix.org Foundation C.I.C.
|
||||
* Copyright 2020 - 2021 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.
|
||||
|
@ -23,6 +23,7 @@ import {
|
|||
MatrixCapabilities,
|
||||
OpenIDRequestState,
|
||||
SimpleObservable,
|
||||
Symbols,
|
||||
Widget,
|
||||
WidgetDriver,
|
||||
WidgetEventCapability,
|
||||
|
@ -33,9 +34,7 @@ import { MatrixClientPeg } from "../../MatrixClientPeg";
|
|||
import ActiveRoomObserver from "../../ActiveRoomObserver";
|
||||
import Modal from "../../Modal";
|
||||
import WidgetOpenIDPermissionsDialog from "../../components/views/dialogs/WidgetOpenIDPermissionsDialog";
|
||||
import WidgetCapabilitiesPromptDialog, {
|
||||
getRememberedCapabilitiesForWidget,
|
||||
} from "../../components/views/dialogs/WidgetCapabilitiesPromptDialog";
|
||||
import WidgetCapabilitiesPromptDialog from "../../components/views/dialogs/WidgetCapabilitiesPromptDialog";
|
||||
import { WidgetPermissionCustomisations } from "../../customisations/WidgetPermissions";
|
||||
import { OIDCState, WidgetPermissionStore } from "./WidgetPermissionStore";
|
||||
import { WidgetType } from "../../widgets/WidgetType";
|
||||
|
@ -44,10 +43,19 @@ import { CHAT_EFFECTS } from "../../effects";
|
|||
import { containsEmoji } from "../../effects/utils";
|
||||
import dis from "../../dispatcher/dispatcher";
|
||||
import { tryTransformPermalinkToLocalHref } from "../../utils/permalinks/Permalinks";
|
||||
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
|
||||
import { IEvent, MatrixEvent } from "matrix-js-sdk/src/models/event";
|
||||
import { Room } from "matrix-js-sdk";
|
||||
|
||||
// TODO: Purge this from the universe
|
||||
|
||||
function getRememberedCapabilitiesForWidget(widget: Widget): Capability[] {
|
||||
return JSON.parse(localStorage.getItem(`widget_${widget.id}_approved_caps`) || "[]");
|
||||
}
|
||||
|
||||
function setRememberedCapabilitiesForWidget(widget: Widget, caps: Capability[]) {
|
||||
localStorage.setItem(`widget_${widget.id}_approved_caps`, JSON.stringify(caps));
|
||||
}
|
||||
|
||||
export class StopGapWidgetDriver extends WidgetDriver {
|
||||
private allowedCapabilities: Set<Capability>;
|
||||
|
||||
|
@ -100,6 +108,7 @@ export class StopGapWidgetDriver extends WidgetDriver {
|
|||
}
|
||||
}
|
||||
// TODO: Do something when the widget requests new capabilities not yet asked for
|
||||
let rememberApproved = false;
|
||||
if (missing.size > 0) {
|
||||
try {
|
||||
const [result] = await Modal.createTrackedDialog(
|
||||
|
@ -111,17 +120,29 @@ export class StopGapWidgetDriver extends WidgetDriver {
|
|||
widgetKind: this.forWidgetKind,
|
||||
}).finished;
|
||||
(result.approved || []).forEach(cap => allowedSoFar.add(cap));
|
||||
rememberApproved = result.remember;
|
||||
} catch (e) {
|
||||
console.error("Non-fatal error getting capabilities: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
return new Set(iterableUnion(allowedSoFar, requested));
|
||||
const allAllowed = new Set(iterableUnion(allowedSoFar, requested));
|
||||
|
||||
if (rememberApproved) {
|
||||
setRememberedCapabilitiesForWidget(this.forWidget, Array.from(allAllowed));
|
||||
}
|
||||
|
||||
return allAllowed;
|
||||
}
|
||||
|
||||
public async sendEvent(eventType: string, content: any, stateKey: string = null): Promise<ISendEventDetails> {
|
||||
public async sendEvent(
|
||||
eventType: string,
|
||||
content: any,
|
||||
stateKey: string = null,
|
||||
targetRoomId: string = null,
|
||||
): Promise<ISendEventDetails> {
|
||||
const client = MatrixClientPeg.get();
|
||||
const roomId = ActiveRoomObserver.activeRoomId;
|
||||
const roomId = targetRoomId || ActiveRoomObserver.activeRoomId;
|
||||
|
||||
if (!client || !roomId) throw new Error("Not in a room or not attached to a client");
|
||||
|
||||
|
@ -129,6 +150,9 @@ export class StopGapWidgetDriver extends WidgetDriver {
|
|||
if (stateKey !== null) {
|
||||
// state event
|
||||
r = await client.sendStateEvent(roomId, eventType, content, stateKey);
|
||||
} else if (eventType === EventType.RoomRedaction) {
|
||||
// special case: extract the `redacts` property and call redact
|
||||
r = await client.redactEvent(roomId, content['redacts']);
|
||||
} else {
|
||||
// message event
|
||||
r = await client.sendEvent(roomId, eventType, content);
|
||||
|
@ -145,48 +169,68 @@ export class StopGapWidgetDriver extends WidgetDriver {
|
|||
return { roomId, eventId: r.event_id };
|
||||
}
|
||||
|
||||
public async readRoomEvents(eventType: string, msgtype: string | undefined, limit: number): Promise<object[]> {
|
||||
limit = limit > 0 ? Math.min(limit, 25) : 25; // arbitrary choice
|
||||
|
||||
private pickRooms(roomIds: (string | Symbols.AnyRoom)[] = null): Room[] {
|
||||
const client = MatrixClientPeg.get();
|
||||
const roomId = ActiveRoomObserver.activeRoomId;
|
||||
const room = client.getRoom(roomId);
|
||||
if (!client || !roomId || !room) throw new Error("Not in a room or not attached to a client");
|
||||
if (!client) throw new Error("Not attached to a client");
|
||||
|
||||
const results: MatrixEvent[] = [];
|
||||
const events = room.getLiveTimeline().getEvents(); // timelines are most recent last
|
||||
for (let i = events.length - 1; i > 0; i--) {
|
||||
if (results.length >= limit) break;
|
||||
|
||||
const ev = events[i];
|
||||
if (ev.getType() !== eventType || ev.isState()) continue;
|
||||
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()['msgtype']) continue;
|
||||
results.push(ev);
|
||||
}
|
||||
|
||||
return results.map(e => e.getEffectiveEvent());
|
||||
const targetRooms = roomIds
|
||||
? (roomIds.includes(Symbols.AnyRoom) ? client.getVisibleRooms() : roomIds.map(r => client.getRoom(r)))
|
||||
: [client.getRoom(ActiveRoomObserver.activeRoomId)];
|
||||
return targetRooms.filter(r => !!r);
|
||||
}
|
||||
|
||||
public async readStateEvents(eventType: string, stateKey: string | undefined, limit: number): Promise<object[]> {
|
||||
limit = limit > 0 ? Math.min(limit, 100) : 100; // arbitrary choice
|
||||
public async readRoomEvents(
|
||||
eventType: string,
|
||||
msgtype: string | undefined,
|
||||
limitPerRoom: number,
|
||||
roomIds: (string | Symbols.AnyRoom)[] = null,
|
||||
): Promise<object[]> {
|
||||
limitPerRoom = limitPerRoom > 0 ? Math.min(limitPerRoom, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary
|
||||
|
||||
const client = MatrixClientPeg.get();
|
||||
const roomId = ActiveRoomObserver.activeRoomId;
|
||||
const room = client.getRoom(roomId);
|
||||
if (!client || !roomId || !room) throw new Error("Not in a room or not attached to a client");
|
||||
const rooms = this.pickRooms(roomIds);
|
||||
const allResults: IEvent[] = [];
|
||||
for (const room of rooms) {
|
||||
const results: MatrixEvent[] = [];
|
||||
const events = room.getLiveTimeline().getEvents(); // timelines are most recent last
|
||||
for (let i = events.length - 1; i > 0; i--) {
|
||||
if (results.length >= limitPerRoom) break;
|
||||
|
||||
const results: MatrixEvent[] = [];
|
||||
const state: Map<string, MatrixEvent> = room.currentState.events.get(eventType);
|
||||
if (state) {
|
||||
if (stateKey === "" || !!stateKey) {
|
||||
const forKey = state.get(stateKey);
|
||||
if (forKey) results.push(forKey);
|
||||
} else {
|
||||
results.push(...Array.from(state.values()));
|
||||
const ev = events[i];
|
||||
if (ev.getType() !== eventType || ev.isState()) continue;
|
||||
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()['msgtype']) continue;
|
||||
results.push(ev);
|
||||
}
|
||||
}
|
||||
|
||||
return results.slice(0, limit).map(e => e.event);
|
||||
results.forEach(e => allResults.push(e.getEffectiveEvent()));
|
||||
}
|
||||
return allResults;
|
||||
}
|
||||
|
||||
public async readStateEvents(
|
||||
eventType: string,
|
||||
stateKey: string | undefined,
|
||||
limitPerRoom: number,
|
||||
roomIds: (string | Symbols.AnyRoom)[] = null,
|
||||
): Promise<object[]> {
|
||||
limitPerRoom = limitPerRoom > 0 ? Math.min(limitPerRoom, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary
|
||||
|
||||
const rooms = this.pickRooms(roomIds);
|
||||
const allResults: IEvent[] = [];
|
||||
for (const room of rooms) {
|
||||
const results: MatrixEvent[] = [];
|
||||
const state: Map<string, MatrixEvent> = room.currentState.events.get(eventType);
|
||||
if (state) {
|
||||
if (stateKey === "" || !!stateKey) {
|
||||
const forKey = state.get(stateKey);
|
||||
if (forKey) results.push(forKey);
|
||||
} else {
|
||||
results.push(...Array.from(state.values()));
|
||||
}
|
||||
}
|
||||
|
||||
results.slice(0, limitPerRoom).forEach(e => allResults.push(e.getEffectiveEvent()));
|
||||
}
|
||||
return allResults;
|
||||
}
|
||||
|
||||
public async askOpenID(observer: SimpleObservable<IOpenIDUpdate>) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue