Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Show a tile for an unloaded predecessor room if it has via_servers (#…
Browse files Browse the repository at this point in the history
…10483)

* Improve typing in constructor of RoomPermalinkCreator

* Provide via servers if present when navigating to predecessor room from Advanced Room Settings

* Show an error tile when the predecessor room is not found

* Test for MatrixToPermalinkConstructor.forRoom

* Test for MatrixToPermalinkConstructor.forEvent

* Display a tile for predecessor event if it contains via servers

* Fix missing case where event id is provided as well as via servers

* Refactor RoomPredecessor tests

* Return lost filterConsole to its home

* Comments for IState in AdvancedRoomSettingsTab

* Explain why we might render a tile even without prevRoom

* Guess the old room's via servers if they are not provided

* Fix TypeScript errors

* Adjust regular expression (hopefully) to avoid potential catastrophic backtracking

* Another attempt at avoiding super-liner regex performance

* Tests for guessServerNameFromRoomId and better implementation

* Further attempt to prevent backtracking

---------

Co-authored-by: Michael Telatynski <7t3chguy@gmail.com>
  • Loading branch information
andybalaam and t3chguy authored Apr 12, 2023
1 parent 075cb9e commit c496985
Show file tree
Hide file tree
Showing 8 changed files with 320 additions and 89 deletions.
115 changes: 105 additions & 10 deletions src/components/views/messages/RoomPredecessorTile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ limitations under the License.
import React, { useCallback, useContext } from "react";
import { logger } from "matrix-js-sdk/src/logger";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { Room } from "matrix-js-sdk/src/matrix";

import dis from "../../../dispatcher/dispatcher";
import { Action } from "../../../dispatcher/actions";
Expand All @@ -29,6 +30,7 @@ import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
import RoomContext from "../../../contexts/RoomContext";
import { useRoomState } from "../../../hooks/useRoomState";
import SettingsStore from "../../../settings/SettingsStore";
import MatrixToPermalinkConstructor from "../../../utils/permalinks/MatrixToPermalinkConstructor";

interface IProps {
/** The m.room.create MatrixEvent that this tile represents */
Expand Down Expand Up @@ -86,18 +88,56 @@ export const RoomPredecessorTile: React.FC<IProps> = ({ mxEvent, timestamp }) =>
}

const prevRoom = MatrixClientPeg.get().getRoom(predecessor.roomId);
if (!prevRoom) {

// We need either the previous room, or some servers to find it with.
// Otherwise, we must bail out here
if (!prevRoom && !predecessor.viaServers) {
logger.warn(`Failed to find predecessor room with id ${predecessor.roomId}`);
return <></>;
}
const permalinkCreator = new RoomPermalinkCreator(prevRoom, predecessor.roomId);
permalinkCreator.load();
let predecessorPermalink: string;
if (predecessor.eventId) {
predecessorPermalink = permalinkCreator.forEvent(predecessor.eventId);
} else {
predecessorPermalink = permalinkCreator.forRoom();

const guessedLink = guessLinkForRoomId(predecessor.roomId);

return (
<EventTileBubble
className="mx_CreateEvent"
title={_t("This room is a continuation of another conversation.")}
timestamp={timestamp}
>
<div className="mx_EventTile_body">
<span className="mx_EventTile_tileError">
{!!guessedLink ? (
<>
{_t(
"Can't find the old version of this room (room ID: %(roomId)s), and we have not been " +
"provided with 'via_servers' to look for it. It's possible that guessing the " +
"server from the room ID will work. If you want to try, click this link:",
{
roomId: predecessor.roomId,
},
)}
<a href={guessedLink}>{guessedLink}</a>
</>
) : (
_t(
"Can't find the old version of this room (room ID: %(roomId)s), and we have not been " +
"provided with 'via_servers' to look for it.",
{
roomId: predecessor.roomId,
},
)
)}
</span>
</div>
</EventTileBubble>
);
}
// Otherwise, we expect to be able to find this room either because it is
// already loaded, or because we have via_servers that we can use.
// So we go ahead with rendering the tile.

const predecessorPermalink = prevRoom
? createLinkWithRoom(prevRoom, predecessor.roomId, predecessor.eventId)
: createLinkWithoutRoom(predecessor.roomId, predecessor.viaServers, predecessor.eventId);

const link = (
<a href={predecessorPermalink} onClick={onLinkClicked}>
{_t("Click here to see older messages.")}
Expand All @@ -112,4 +152,59 @@ export const RoomPredecessorTile: React.FC<IProps> = ({ mxEvent, timestamp }) =>
timestamp={timestamp}
/>
);

function createLinkWithRoom(room: Room, roomId: string, eventId?: string): string {
const permalinkCreator = new RoomPermalinkCreator(room, roomId);
permalinkCreator.load();
if (eventId) {
return permalinkCreator.forEvent(eventId);
} else {
return permalinkCreator.forRoom();
}
}

function createLinkWithoutRoom(roomId: string, viaServers: string[], eventId?: string): string {
const matrixToPermalinkConstructor = new MatrixToPermalinkConstructor();
if (eventId) {
return matrixToPermalinkConstructor.forEvent(roomId, eventId, viaServers);
} else {
return matrixToPermalinkConstructor.forRoom(roomId, viaServers);
}
}

/**
* Guess the permalink for a room based on its room ID.
*
* The spec says that Room IDs are opaque [1] so this can only ever be a
* guess. There is no guarantee that this room exists on this server.
*
* [1] https://spec.matrix.org/v1.5/appendices/#room-ids-and-event-ids
*/
function guessLinkForRoomId(roomId: string): string | null {
const serverName = guessServerNameFromRoomId(roomId);
if (serverName) {
return new MatrixToPermalinkConstructor().forRoom(roomId, [serverName]);
} else {
return null;
}
}
};

/**
* @internal Public for test only
*
* Guess the server name for a room based on its room ID.
*
* The spec says that Room IDs are opaque [1] so this can only ever be a
* guess. There is no guarantee that this room exists on this server.
*
* [1] https://spec.matrix.org/v1.5/appendices/#room-ids-and-event-ids
*/
export function guessServerNameFromRoomId(roomId: string): string | null {
const m = roomId.match(/^[^:]*:(.*)/);
if (m) {
return m[1];
} else {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,16 @@ interface IRecommendedVersion {
interface IState {
// This is eventually set to the value of room.getRecommendedVersion()
upgradeRecommendation?: IRecommendedVersion;

/** The room ID of this room's predecessor, if it exists. */
oldRoomId?: string;

/** The ID of tombstone event in this room's predecessor, if it exists. */
oldEventId?: string;

/** The via servers to use to find this room's predecessor, if it exists. */
oldViaServers?: string[];

upgraded?: boolean;
}

Expand All @@ -65,6 +73,7 @@ export default class AdvancedRoomSettingsTab extends React.Component<IProps, ISt
if (predecessor) {
additionalStateChanges.oldRoomId = predecessor.roomId;
additionalStateChanges.oldEventId = predecessor.eventId;
additionalStateChanges.oldViaServers = predecessor.viaServers;
}

this.setState({
Expand All @@ -88,6 +97,7 @@ export default class AdvancedRoomSettingsTab extends React.Component<IProps, ISt
action: Action.ViewRoom,
room_id: this.state.oldRoomId,
event_id: this.state.oldEventId,
via_servers: this.state.oldViaServers,
metricsTrigger: "WebPredecessorSettings",
metricsViaKeyboard: e.type !== "click",
});
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/strings/en_EN.json
Original file line number Diff line number Diff line change
Expand Up @@ -2458,8 +2458,10 @@
"%(senderDisplayName)s changed the avatar for %(roomName)s": "%(senderDisplayName)s changed the avatar for %(roomName)s",
"%(senderDisplayName)s removed the room avatar.": "%(senderDisplayName)s removed the room avatar.",
"%(senderDisplayName)s changed the room avatar to <img/>": "%(senderDisplayName)s changed the room avatar to <img/>",
"Click here to see older messages.": "Click here to see older messages.",
"This room is a continuation of another conversation.": "This room is a continuation of another conversation.",
"Can't find the old version of this room (room ID: %(roomId)s), and we have not been provided with 'via_servers' to look for it. It's possible that guessing the server from the room ID will work. If you want to try, click this link:": "Can't find the old version of this room (room ID: %(roomId)s), and we have not been provided with 'via_servers' to look for it. It's possible that guessing the server from the room ID will work. If you want to try, click this link:",
"Can't find the old version of this room (room ID: %(roomId)s), and we have not been provided with 'via_servers' to look for it.": "Can't find the old version of this room (room ID: %(roomId)s), and we have not been provided with 'via_servers' to look for it.",
"Click here to see older messages.": "Click here to see older messages.",
"Add an Integration": "Add an Integration",
"You are about to be taken to a third-party site so you can authenticate your account for use with %(integrationsUrl)s. Do you wish to continue?": "You are about to be taken to a third-party site so you can authenticate your account for use with %(integrationsUrl)s. Do you wish to continue?",
"Edited at %(date)s": "Edited at %(date)s",
Expand Down
26 changes: 14 additions & 12 deletions src/utils/permalinks/Permalinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export class RoomPermalinkCreator {
// Some of the tests done by this class are relatively expensive, so normally
// throttled to not happen on every update. Pass false as the shouldThrottle
// param to disable this behaviour, eg. for tests.
public constructor(private room: Room, roomId: string | null = null, shouldThrottle = true) {
public constructor(private room: Room | null, roomId: string | null = null, shouldThrottle = true) {
this.roomId = room ? room.roomId : roomId!;

if (!this.roomId) {
Expand All @@ -118,12 +118,12 @@ export class RoomPermalinkCreator {

public start(): void {
this.load();
this.room.currentState.on(RoomStateEvent.Update, this.onRoomStateUpdate);
this.room?.currentState.on(RoomStateEvent.Update, this.onRoomStateUpdate);
this.started = true;
}

public stop(): void {
this.room.currentState.removeListener(RoomStateEvent.Update, this.onRoomStateUpdate);
this.room?.currentState.removeListener(RoomStateEvent.Update, this.onRoomStateUpdate);
this.started = false;
}

Expand Down Expand Up @@ -171,15 +171,15 @@ export class RoomPermalinkCreator {
}

private updateHighestPlUser(): void {
const plEvent = this.room.currentState.getStateEvents("m.room.power_levels", "");
const plEvent = this.room?.currentState.getStateEvents("m.room.power_levels", "");
if (plEvent) {
const content = plEvent.getContent();
if (content) {
const users: Record<string, number> = content.users;
if (users) {
const entries = Object.entries(users);
const allowedEntries = entries.filter(([userId]) => {
const member = this.room.getMember(userId);
const member = this.room?.getMember(userId);
if (!member || member.membership !== "join") {
return false;
}
Expand Down Expand Up @@ -213,8 +213,8 @@ export class RoomPermalinkCreator {
private updateAllowedServers(): void {
const bannedHostsRegexps: RegExp[] = [];
let allowedHostsRegexps = [ANY_REGEX]; // default allow everyone
if (this.room.currentState) {
const aclEvent = this.room.currentState.getStateEvents(EventType.RoomServerAcl, "");
if (this.room?.currentState) {
const aclEvent = this.room?.currentState.getStateEvents(EventType.RoomServerAcl, "");
if (aclEvent && aclEvent.getContent()) {
const getRegex = (hostname: string): RegExp =>
new RegExp("^" + utils.globToRegexp(hostname, false) + "$");
Expand All @@ -237,12 +237,14 @@ export class RoomPermalinkCreator {

private updatePopulationMap(): void {
const populationMap: { [server: string]: number } = {};
for (const member of this.room.getJoinedMembers()) {
const serverName = getServerName(member.userId);
if (!populationMap[serverName]) {
populationMap[serverName] = 0;
if (this.room) {
for (const member of this.room.getJoinedMembers()) {
const serverName = getServerName(member.userId);
if (!populationMap[serverName]) {
populationMap[serverName] = 0;
}
populationMap[serverName]++;
}
populationMap[serverName]++;
}
this.populationMap = populationMap;
}
Expand Down
Loading

0 comments on commit c496985

Please sign in to comment.