Show a tile for an unloaded predecessor room if it has via_servers (#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>
This commit is contained in:
Andy Balaam 2023-04-12 16:26:45 +01:00 committed by GitHub
parent 075cb9e622
commit c496985ff3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 320 additions and 89 deletions

View file

@ -18,6 +18,7 @@ limitations under the License.
import React, { useCallback, useContext } from "react"; import React, { useCallback, useContext } from "react";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { Room } from "matrix-js-sdk/src/matrix";
import dis from "../../../dispatcher/dispatcher"; import dis from "../../../dispatcher/dispatcher";
import { Action } from "../../../dispatcher/actions"; import { Action } from "../../../dispatcher/actions";
@ -29,6 +30,7 @@ import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
import RoomContext from "../../../contexts/RoomContext"; import RoomContext from "../../../contexts/RoomContext";
import { useRoomState } from "../../../hooks/useRoomState"; import { useRoomState } from "../../../hooks/useRoomState";
import SettingsStore from "../../../settings/SettingsStore"; import SettingsStore from "../../../settings/SettingsStore";
import MatrixToPermalinkConstructor from "../../../utils/permalinks/MatrixToPermalinkConstructor";
interface IProps { interface IProps {
/** The m.room.create MatrixEvent that this tile represents */ /** The m.room.create MatrixEvent that this tile represents */
@ -86,18 +88,56 @@ export const RoomPredecessorTile: React.FC<IProps> = ({ mxEvent, timestamp }) =>
} }
const prevRoom = MatrixClientPeg.get().getRoom(predecessor.roomId); 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}`); logger.warn(`Failed to find predecessor room with id ${predecessor.roomId}`);
return <></>;
} const guessedLink = guessLinkForRoomId(predecessor.roomId);
const permalinkCreator = new RoomPermalinkCreator(prevRoom, predecessor.roomId);
permalinkCreator.load(); return (
let predecessorPermalink: string; <EventTileBubble
if (predecessor.eventId) { className="mx_CreateEvent"
predecessorPermalink = permalinkCreator.forEvent(predecessor.eventId); title={_t("This room is a continuation of another conversation.")}
} else { timestamp={timestamp}
predecessorPermalink = permalinkCreator.forRoom(); >
<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 = ( const link = (
<a href={predecessorPermalink} onClick={onLinkClicked}> <a href={predecessorPermalink} onClick={onLinkClicked}>
{_t("Click here to see older messages.")} {_t("Click here to see older messages.")}
@ -112,4 +152,59 @@ export const RoomPredecessorTile: React.FC<IProps> = ({ mxEvent, timestamp }) =>
timestamp={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;
}
}

View file

@ -42,8 +42,16 @@ interface IRecommendedVersion {
interface IState { interface IState {
// This is eventually set to the value of room.getRecommendedVersion() // This is eventually set to the value of room.getRecommendedVersion()
upgradeRecommendation?: IRecommendedVersion; upgradeRecommendation?: IRecommendedVersion;
/** The room ID of this room's predecessor, if it exists. */
oldRoomId?: string; oldRoomId?: string;
/** The ID of tombstone event in this room's predecessor, if it exists. */
oldEventId?: string; oldEventId?: string;
/** The via servers to use to find this room's predecessor, if it exists. */
oldViaServers?: string[];
upgraded?: boolean; upgraded?: boolean;
} }
@ -65,6 +73,7 @@ export default class AdvancedRoomSettingsTab extends React.Component<IProps, ISt
if (predecessor) { if (predecessor) {
additionalStateChanges.oldRoomId = predecessor.roomId; additionalStateChanges.oldRoomId = predecessor.roomId;
additionalStateChanges.oldEventId = predecessor.eventId; additionalStateChanges.oldEventId = predecessor.eventId;
additionalStateChanges.oldViaServers = predecessor.viaServers;
} }
this.setState({ this.setState({
@ -88,6 +97,7 @@ export default class AdvancedRoomSettingsTab extends React.Component<IProps, ISt
action: Action.ViewRoom, action: Action.ViewRoom,
room_id: this.state.oldRoomId, room_id: this.state.oldRoomId,
event_id: this.state.oldEventId, event_id: this.state.oldEventId,
via_servers: this.state.oldViaServers,
metricsTrigger: "WebPredecessorSettings", metricsTrigger: "WebPredecessorSettings",
metricsViaKeyboard: e.type !== "click", metricsViaKeyboard: e.type !== "click",
}); });

View file

@ -2458,8 +2458,10 @@
"%(senderDisplayName)s changed the avatar for %(roomName)s": "%(senderDisplayName)s changed the avatar for %(roomName)s", "%(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 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/>", "%(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.", "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", "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?", "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", "Edited at %(date)s": "Edited at %(date)s",

View file

@ -96,7 +96,7 @@ export class RoomPermalinkCreator {
// Some of the tests done by this class are relatively expensive, so normally // 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 // throttled to not happen on every update. Pass false as the shouldThrottle
// param to disable this behaviour, eg. for tests. // 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!; this.roomId = room ? room.roomId : roomId!;
if (!this.roomId) { if (!this.roomId) {
@ -118,12 +118,12 @@ export class RoomPermalinkCreator {
public start(): void { public start(): void {
this.load(); this.load();
this.room.currentState.on(RoomStateEvent.Update, this.onRoomStateUpdate); this.room?.currentState.on(RoomStateEvent.Update, this.onRoomStateUpdate);
this.started = true; this.started = true;
} }
public stop(): void { public stop(): void {
this.room.currentState.removeListener(RoomStateEvent.Update, this.onRoomStateUpdate); this.room?.currentState.removeListener(RoomStateEvent.Update, this.onRoomStateUpdate);
this.started = false; this.started = false;
} }
@ -171,7 +171,7 @@ export class RoomPermalinkCreator {
} }
private updateHighestPlUser(): void { 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) { if (plEvent) {
const content = plEvent.getContent(); const content = plEvent.getContent();
if (content) { if (content) {
@ -179,7 +179,7 @@ export class RoomPermalinkCreator {
if (users) { if (users) {
const entries = Object.entries(users); const entries = Object.entries(users);
const allowedEntries = entries.filter(([userId]) => { const allowedEntries = entries.filter(([userId]) => {
const member = this.room.getMember(userId); const member = this.room?.getMember(userId);
if (!member || member.membership !== "join") { if (!member || member.membership !== "join") {
return false; return false;
} }
@ -213,8 +213,8 @@ export class RoomPermalinkCreator {
private updateAllowedServers(): void { private updateAllowedServers(): void {
const bannedHostsRegexps: RegExp[] = []; const bannedHostsRegexps: RegExp[] = [];
let allowedHostsRegexps = [ANY_REGEX]; // default allow everyone let allowedHostsRegexps = [ANY_REGEX]; // default allow everyone
if (this.room.currentState) { if (this.room?.currentState) {
const aclEvent = this.room.currentState.getStateEvents(EventType.RoomServerAcl, ""); const aclEvent = this.room?.currentState.getStateEvents(EventType.RoomServerAcl, "");
if (aclEvent && aclEvent.getContent()) { if (aclEvent && aclEvent.getContent()) {
const getRegex = (hostname: string): RegExp => const getRegex = (hostname: string): RegExp =>
new RegExp("^" + utils.globToRegexp(hostname, false) + "$"); new RegExp("^" + utils.globToRegexp(hostname, false) + "$");
@ -237,6 +237,7 @@ export class RoomPermalinkCreator {
private updatePopulationMap(): void { private updatePopulationMap(): void {
const populationMap: { [server: string]: number } = {}; const populationMap: { [server: string]: number } = {};
if (this.room) {
for (const member of this.room.getJoinedMembers()) { for (const member of this.room.getJoinedMembers()) {
const serverName = getServerName(member.userId); const serverName = getServerName(member.userId);
if (!populationMap[serverName]) { if (!populationMap[serverName]) {
@ -244,6 +245,7 @@ export class RoomPermalinkCreator {
} }
populationMap[serverName]++; populationMap[serverName]++;
} }
}
this.populationMap = populationMap; this.populationMap = populationMap;
} }

View file

@ -22,11 +22,14 @@ import { EventType, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import dis from "../../../../src/dispatcher/dispatcher"; import dis from "../../../../src/dispatcher/dispatcher";
import SettingsStore from "../../../../src/settings/SettingsStore"; import SettingsStore from "../../../../src/settings/SettingsStore";
import { RoomPredecessorTile } from "../../../../src/components/views/messages/RoomPredecessorTile"; import {
guessServerNameFromRoomId,
RoomPredecessorTile,
} from "../../../../src/components/views/messages/RoomPredecessorTile";
import { stubClient, upsertRoomStateEvents } from "../../../test-utils/test-utils"; import { stubClient, upsertRoomStateEvents } from "../../../test-utils/test-utils";
import { Action } from "../../../../src/dispatcher/actions"; import { Action } from "../../../../src/dispatcher/actions";
import RoomContext from "../../../../src/contexts/RoomContext"; import RoomContext from "../../../../src/contexts/RoomContext";
import { getRoomContext } from "../../../test-utils"; import { filterConsole, getRoomContext } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg"; import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
jest.mock("../../../../src/dispatcher/dispatcher"); jest.mock("../../../../src/dispatcher/dispatcher");
@ -34,55 +37,56 @@ jest.mock("../../../../src/dispatcher/dispatcher");
describe("<RoomPredecessorTile />", () => { describe("<RoomPredecessorTile />", () => {
const userId = "@alice:server.org"; const userId = "@alice:server.org";
const roomId = "!room:server.org"; const roomId = "!room:server.org";
const createEvent = new MatrixEvent({ stubClient();
type: EventType.RoomCreate, const client = mocked(MatrixClientPeg.get());
state_key: "",
sender: userId, function makeRoom({
room_id: roomId, createEventHasPredecessor = false,
content: { predecessorEventExists = false,
predecessor: { room_id: "old_room_id", event_id: "tombstone_event_id" }, predecessorEventHasEventId = false,
}, predecessorEventHasViaServers = false,
event_id: "$create", }): Room {
}); const room = new Room(roomId, client, userId);
const createEventWithoutPredecessor = new MatrixEvent({
const createInfo = {
type: EventType.RoomCreate, type: EventType.RoomCreate,
state_key: "", state_key: "",
sender: userId, sender: userId,
room_id: roomId, room_id: roomId,
content: {}, content: {},
event_id: "$create", event_id: "$create",
}); };
const predecessorEvent = new MatrixEvent({
if (createEventHasPredecessor) {
createInfo.content = {
predecessor: { room_id: "old_room_id", event_id: "$tombstone_event_id" },
};
}
const createEvent = new MatrixEvent(createInfo);
upsertRoomStateEvents(room, [createEvent]);
if (predecessorEventExists) {
const predecessorInfo = {
type: EventType.RoomPredecessor, type: EventType.RoomPredecessor,
state_key: "", state_key: "",
sender: userId, sender: userId,
room_id: roomId, room_id: roomId,
content: { content: {
predecessor_room_id: "old_room_id_from_predecessor", predecessor_room_id: "old_room_id_from_predecessor",
last_known_event_id: predecessorEventHasEventId
? "$tombstone_event_id_from_predecessor"
: undefined,
via_servers: predecessorEventHasViaServers ? ["a.example.com", "b.example.com"] : undefined,
}, },
event_id: "$create", event_id: "$predecessor",
}); };
const predecessorEventWithEventId = new MatrixEvent({
type: EventType.RoomPredecessor, const predecessorEvent = new MatrixEvent(predecessorInfo);
state_key: "", upsertRoomStateEvents(room, [predecessorEvent]);
sender: userId, }
room_id: roomId, return room;
content: { }
predecessor_room_id: "old_room_id_from_predecessor",
last_known_event_id: "tombstone_event_id_from_predecessor",
},
event_id: "$create",
});
stubClient();
const client = mocked(MatrixClientPeg.get());
const roomJustCreate = new Room(roomId, client, userId);
upsertRoomStateEvents(roomJustCreate, [createEvent]);
const roomCreateAndPredecessor = new Room(roomId, client, userId);
upsertRoomStateEvents(roomCreateAndPredecessor, [createEvent, predecessorEvent]);
const roomCreateAndPredecessorWithEventId = new Room(roomId, client, userId);
upsertRoomStateEvents(roomCreateAndPredecessorWithEventId, [createEvent, predecessorEventWithEventId]);
const roomNoPredecessors = new Room(roomId, client, userId);
upsertRoomStateEvents(roomNoPredecessors, [createEventWithoutPredecessor]);
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
@ -98,6 +102,10 @@ describe("<RoomPredecessorTile />", () => {
}); });
function renderTile(room: Room) { function renderTile(room: Room) {
// Find this room's create event (it should have one!)
const createEvent = room.currentState.getStateEvents("m.room.create")[0];
expect(createEvent).toBeTruthy();
return render( return render(
<RoomContext.Provider value={getRoomContext(room, {})}> <RoomContext.Provider value={getRoomContext(room, {})}>
<RoomPredecessorTile mxEvent={createEvent} /> <RoomPredecessorTile mxEvent={createEvent} />
@ -106,25 +114,29 @@ describe("<RoomPredecessorTile />", () => {
} }
it("Renders as expected", () => { it("Renders as expected", () => {
const roomCreate = renderTile(roomJustCreate); const roomCreate = renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(roomCreate.asFragment()).toMatchSnapshot(); expect(roomCreate.asFragment()).toMatchSnapshot();
}); });
it("Links to the old version of the room", () => { it("Links to the old version of the room", () => {
renderTile(roomJustCreate); renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute( expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href", "href",
"https://matrix.to/#/old_room_id/tombstone_event_id", "https://matrix.to/#/old_room_id/$tombstone_event_id",
); );
}); });
describe("(filtering warnings about no predecessor)", () => {
filterConsole("RoomPredecessorTile unexpectedly used in a room with no predecessor.");
it("Shows an empty div if there is no predecessor", () => { it("Shows an empty div if there is no predecessor", () => {
renderTile(roomNoPredecessors); renderTile(makeRoom({}));
expect(screen.queryByText("Click here to see older messages.", { exact: false })).toBeNull(); expect(screen.queryByText("Click here to see older messages.", { exact: false })).toBeNull();
}); });
});
it("Opens the old room on click", async () => { it("Opens the old room on click", async () => {
renderTile(roomJustCreate); renderTile(makeRoom({ createEventHasPredecessor: true }));
const link = screen.getByText("Click here to see older messages."); const link = screen.getByText("Click here to see older messages.");
await act(() => userEvent.click(link)); await act(() => userEvent.click(link));
@ -132,7 +144,7 @@ describe("<RoomPredecessorTile />", () => {
await waitFor(() => await waitFor(() =>
expect(dis.dispatch).toHaveBeenCalledWith({ expect(dis.dispatch).toHaveBeenCalledWith({
action: Action.ViewRoom, action: Action.ViewRoom,
event_id: "tombstone_event_id", event_id: "$tombstone_event_id",
highlighted: true, highlighted: true,
room_id: "old_room_id", room_id: "old_room_id",
metricsTrigger: "Predecessor", metricsTrigger: "Predecessor",
@ -142,13 +154,26 @@ describe("<RoomPredecessorTile />", () => {
}); });
it("Ignores m.predecessor if labs flag is off", () => { it("Ignores m.predecessor if labs flag is off", () => {
renderTile(roomCreateAndPredecessor); renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute( expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href", "href",
"https://matrix.to/#/old_room_id/tombstone_event_id", "https://matrix.to/#/old_room_id/$tombstone_event_id",
); );
}); });
describe("If the predecessor room is not found", () => {
filterConsole("Failed to find predecessor room with id old_room_id");
beforeEach(() => {
mocked(MatrixClientPeg.get().getRoom).mockReturnValue(null);
});
it("Shows an error if there are no via servers", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Can't find the old version of this room", { exact: false })).toBeInTheDocument();
});
});
describe("When feature_dynamic_room_predecessors = true", () => { describe("When feature_dynamic_room_predecessors = true", () => {
beforeEach(() => { beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockImplementation( jest.spyOn(SettingsStore, "getValue").mockImplementation(
@ -161,15 +186,15 @@ describe("<RoomPredecessorTile />", () => {
}); });
it("Uses the create event if there is no m.predecessor", () => { it("Uses the create event if there is no m.predecessor", () => {
renderTile(roomJustCreate); renderTile(makeRoom({ createEventHasPredecessor: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute( expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href", "href",
"https://matrix.to/#/old_room_id/tombstone_event_id", "https://matrix.to/#/old_room_id/$tombstone_event_id",
); );
}); });
it("Uses m.predecessor when it's there", () => { it("Uses m.predecessor when it's there", () => {
renderTile(roomCreateAndPredecessor); renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute( expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href", "href",
"https://matrix.to/#/old_room_id_from_predecessor", "https://matrix.to/#/old_room_id_from_predecessor",
@ -177,11 +202,91 @@ describe("<RoomPredecessorTile />", () => {
}); });
it("Links to the event in the room if event ID is provided", () => { it("Links to the event in the room if event ID is provided", () => {
renderTile(roomCreateAndPredecessorWithEventId); renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasEventId: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute( expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href", "href",
"https://matrix.to/#/old_room_id_from_predecessor/tombstone_event_id_from_predecessor", "https://matrix.to/#/old_room_id_from_predecessor/$tombstone_event_id_from_predecessor",
);
});
describe("If the predecessor room is not found", () => {
filterConsole("Failed to find predecessor room with id old_room_id");
beforeEach(() => {
mocked(MatrixClientPeg.get().getRoom).mockReturnValue(null);
});
it("Shows an error if there are no via servers", () => {
renderTile(makeRoom({ createEventHasPredecessor: true, predecessorEventExists: true }));
expect(
screen.getByText("Can't find the old version of this room", { exact: false }),
).toBeInTheDocument();
});
it("Shows a tile if there are via servers", () => {
renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasViaServers: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor?via=a.example.com&via=b.example.com",
);
});
it("Shows a tile linking to an event if there are via servers", () => {
renderTile(
makeRoom({
createEventHasPredecessor: true,
predecessorEventExists: true,
predecessorEventHasEventId: true,
predecessorEventHasViaServers: true,
}),
);
expect(screen.getByText("Click here to see older messages.")).toHaveAttribute(
"href",
"https://matrix.to/#/old_room_id_from_predecessor/$tombstone_event_id_from_predecessor?via=a.example.com&via=b.example.com",
); );
}); });
}); });
});
});
describe("guessServerNameFromRoomId", () => {
it("Extracts the domain name from a standard room ID", () => {
expect(guessServerNameFromRoomId("!436456:example.com")).toEqual("example.com");
});
it("Extracts the domain name and port when included", () => {
expect(guessServerNameFromRoomId("!436456:example.com:8888")).toEqual("example.com:8888");
});
it("Handles an IPv4 address for server name", () => {
expect(guessServerNameFromRoomId("!436456:127.0.0.1")).toEqual("127.0.0.1");
});
it("Handles an IPv4 address and port", () => {
expect(guessServerNameFromRoomId("!436456:127.0.0.1:81")).toEqual("127.0.0.1:81");
});
it("Handles an IPv6 address for server name", () => {
expect(guessServerNameFromRoomId("!436456:::1")).toEqual("::1");
});
it("Handles an IPv6 address and port", () => {
expect(guessServerNameFromRoomId("!436456:::1:8080")).toEqual("::1:8080");
});
it("Returns null when the room ID contains no colon", () => {
expect(guessServerNameFromRoomId("!436456")).toBeNull();
});
}); });

View file

@ -14,7 +14,7 @@ exports[`<RoomPredecessorTile /> Renders as expected 1`] = `
class="mx_EventTileBubble_subtitle" class="mx_EventTileBubble_subtitle"
> >
<a <a
href="https://matrix.to/#/old_room_id/tombstone_event_id" href="https://matrix.to/#/old_room_id/$tombstone_event_id"
> >
Click here to see older messages. Click here to see older messages.
</a> </a>

View file

@ -47,7 +47,7 @@ describe("AdvancedRoomSettingsTab", () => {
mocked(dis.dispatch).mockReset(); mocked(dis.dispatch).mockReset();
mocked(room.findPredecessor).mockImplementation((msc3946: boolean) => mocked(room.findPredecessor).mockImplementation((msc3946: boolean) =>
msc3946 msc3946
? { roomId: "old_room_id_via_predecessor" } ? { roomId: "old_room_id_via_predecessor", viaServers: ["one.example.com", "two.example.com"] }
: { roomId: "old_room_id", eventId: "tombstone_event_id" }, : { roomId: "old_room_id", eventId: "tombstone_event_id" },
); );
}); });
@ -138,6 +138,7 @@ describe("AdvancedRoomSettingsTab", () => {
action: Action.ViewRoom, action: Action.ViewRoom,
event_id: undefined, event_id: undefined,
room_id: "old_room_id_via_predecessor", room_id: "old_room_id_via_predecessor",
via_servers: ["one.example.com", "two.example.com"],
metricsTrigger: "WebPredecessorSettings", metricsTrigger: "WebPredecessorSettings",
metricsViaKeyboard: false, metricsViaKeyboard: false,
}); });

View file

@ -41,4 +41,20 @@ describe("MatrixToPermalinkConstructor", () => {
); );
}); });
}); });
describe("forRoom", () => {
it("constructs a link given a room ID and via servers", () => {
expect(peramlinkConstructor.forRoom("!myroom:example.com", ["one.example.com", "two.example.com"])).toEqual(
"https://matrix.to/#/!myroom:example.com?via=one.example.com&via=two.example.com",
);
});
});
describe("forEvent", () => {
it("constructs a link given an event ID, room ID and via servers", () => {
expect(
peramlinkConstructor.forEvent("!myroom:example.com", "$event4", ["one.example.com", "two.example.com"]),
).toEqual("https://matrix.to/#/!myroom:example.com/$event4?via=one.example.com&via=two.example.com");
});
});
}); });