Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions spec/unit/room.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2527,4 +2527,16 @@ describe("Room", function() {
});
});
});

describe("roomNameGenerator", () => {
const client = new TestClient(userA).client;
client.roomNameGenerator = jest.fn().mockReturnValue(null);
const room = new Room(roomId, client, userA);

it("should call fn when recalculating room name", () => {
(client.roomNameGenerator as jest.Mock).mockClear();
room.recalculate();
expect(client.roomNameGenerator).toHaveBeenCalled();
});
});
});
10 changes: 9 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ import { VerificationRequest } from "./crypto/verification/request/VerificationR
import { VerificationBase as Verification } from "./crypto/verification/Base";
import * as ContentHelpers from "./content-helpers";
import { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from "./crypto/CrossSigning";
import { Room } from "./models/room";
import { Room, RoomNameState } from "./models/room";
import {
IAddThreePidOnlyBody,
IBindThreePidBody,
Expand Down Expand Up @@ -344,6 +344,12 @@ export interface ICreateClientOpts {
fallbackICEServerAllowed?: boolean;

cryptoCallbacks?: ICryptoCallbacks;

/**
* Method to generate room names for empty rooms and rooms names based on membership.
* Defaults to a built-in English handler with basic pluralisation.
*/
roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;
}

export interface IMatrixClientCreateOpts extends ICreateClientOpts {
Expand Down Expand Up @@ -918,6 +924,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
protected fallbackICEServerAllowed = false;
protected roomList: RoomList;
protected syncApi: SlidingSyncSdk | SyncApi;
public roomNameGenerator?: ICreateClientOpts["roomNameGenerator"];
public pushRules: IPushRules;
protected syncLeftRoomsPromise: Promise<Room[]>;
protected syncedLeftRooms = false;
Expand Down Expand Up @@ -1041,6 +1048,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
// we still want to know which rooms are encrypted even if crypto is disabled:
// we don't want to start sending unencrypted events to them.
this.roomList = new RoomList(this.cryptoStore);
this.roomNameGenerator = opts.roomNameGenerator;

this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);

Expand Down
105 changes: 90 additions & 15 deletions src/models/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2914,6 +2914,33 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
return this.getType() === RoomType.ElementVideo;
}

private roomNameGenerator(state: RoomNameState): string {
if (this.client.roomNameGenerator) {
const name = this.client.roomNameGenerator(this.roomId, state);
if (name !== null) {
return name;
}
}

switch (state.type) {
case RoomNameType.Actual:
return state.name;
case RoomNameType.Generated:
switch (state.subtype) {
case "Inviting":
return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;
default:
return memberNamesToRoomName(state.names, state.count);
}
case RoomNameType.EmptyRoom:
if (state.oldName) {
return `Empty room (was ${state.oldName})`;
} else {
return "Empty room";
}
}
}

/**
* This is an internal method. Calculates the name of the room from the current
* room state.
Expand All @@ -2928,14 +2955,20 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
// check for an alias, if any. for now, assume first alias is the
// official one.
const mRoomName = this.currentState.getStateEvents(EventType.RoomName, "");
if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {
return mRoomName.getContent().name;
if (mRoomName?.getContent().name) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous code did the equivalent of

Suggested change
if (mRoomName?.getContent().name) {
if (mRoomName?.getContent()?.name) {

are you sure that getContent() always returns an object? We don’t have strict null checking yet in js-sdk.

Copy link
Member Author

@t3chguy t3chguy Aug 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
image

It doesn't always return an object, content or m.new_content could be a boolean etc, because we don't do runtime type checking on incoming events, but it does the || {} that this was effectively doing already

return this.roomNameGenerator({
type: RoomNameType.Actual,
name: mRoomName.getContent().name,
});
}
}

const alias = this.getCanonicalAlias();
if (alias) {
return alias;
return this.roomNameGenerator({
type: RoomNameType.Actual,
name: alias,
});
}

const joinedMemberCount = this.currentState.getJoinedMemberCount();
Expand Down Expand Up @@ -2967,8 +3000,7 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
});
} else {
let otherMembers = this.currentState.getMembers().filter((m) => {
return m.userId !== userId &&
(m.membership === "invite" || m.membership === "join");
return m.userId !== userId && (m.membership === "invite" || m.membership === "join");
});
otherMembers = otherMembers.filter(({ userId }) => {
// filter service members
Expand All @@ -2986,24 +3018,33 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
}

if (inviteJoinCount) {
return memberNamesToRoomName(otherNames, inviteJoinCount);
return this.roomNameGenerator({
type: RoomNameType.Generated,
names: otherNames,
count: inviteJoinCount,
});
}

const myMembership = this.getMyMembership();
// if I have created a room and invited people through
// 3rd party invites
if (myMembership == 'join') {
const thirdPartyInvites =
this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);
const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);

if (thirdPartyInvites && thirdPartyInvites.length) {
if (thirdPartyInvites?.length) {
const thirdPartyNames = thirdPartyInvites.map((i) => {
return i.getContent().display_name;
});

return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`;
return this.roomNameGenerator({
type: RoomNameType.Generated,
subtype: "Inviting",
names: thirdPartyNames,
count: thirdPartyNames.length + 1,
});
}
}

// let's try to figure out who was here before
let leftNames = otherNames;
// if we didn't have heroes, try finding them in the room state
Expand All @@ -3014,11 +3055,20 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
m.membership !== "join";
}).map((m) => m.name);
}

let oldName: string;
if (leftNames.length) {
return `Empty room (was ${memberNamesToRoomName(leftNames)})`;
} else {
return "Empty room";
oldName = this.roomNameGenerator({
type: RoomNameType.Generated,
names: leftNames,
count: leftNames.length + 1,
});
}

return this.roomNameGenerator({
type: RoomNameType.EmptyRoom,
oldName,
});
}

/**
Expand Down Expand Up @@ -3203,8 +3253,33 @@ const ALLOWED_TRANSITIONS: Record<EventStatus, EventStatus[]> = {
[EventStatus.CANCELLED]: [],
};

// TODO i18n
function memberNamesToRoomName(names: string[], count = (names.length + 1)) {
export enum RoomNameType {
EmptyRoom,
Generated,
Actual,
}

export interface EmptyRoomNameState {
type: RoomNameType.EmptyRoom;
oldName?: string;
}

export interface GeneratedRoomNameState {
type: RoomNameType.Generated;
subtype?: "Inviting";
names: string[];
count: number;
}

export interface ActualRoomNameState {
type: RoomNameType.Actual;
name: string;
}

export type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;

// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn
function memberNamesToRoomName(names: string[], count: number): string {
const countWithoutMe = count - 1;
if (!names.length) {
return "Empty room";
Expand Down