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

Avoid using deprecated exports, fields, and duplicate code #12555

Merged
merged 4 commits into from
May 28, 2024
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
17 changes: 0 additions & 17 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,6 @@ export interface IMatrixClientPeg {
*/
opts: IStartClientOpts;

/**
* Return the server name of the user's homeserver
* Throws an error if unable to deduce the homeserver name
* (e.g. if the user is not logged in)
*
* @returns {string} The homeserver name, if present.
*/
getHomeserverName(): string;

/**
* Get the current MatrixClient, if any
*/
Expand Down Expand Up @@ -384,14 +375,6 @@ class MatrixClientPegClass implements IMatrixClientPeg {
logger.log(`MatrixClientPeg: MatrixClient started`);
}

public getHomeserverName(): string {
const matches = /^@[^:]+:(.+)$/.exec(this.safeGet().getSafeUserId());
if (matches === null || matches.length < 1) {
throw new Error("Failed to derive homeserver name from user ID!");
}
return matches[1];
}

private namesToRoomName(names: string[], count: number): string | undefined {
const countWithoutMe = count - 1;
if (!names.length) {
Expand Down
10 changes: 2 additions & 8 deletions src/SecurityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import {
DeviceVerificationStatus,
ICryptoCallbacks,
MatrixClient,
encodeBase64,
SecretStorage,
} from "matrix-js-sdk/src/matrix";
import { Crypto, ICryptoCallbacks, MatrixClient, encodeBase64, SecretStorage } from "matrix-js-sdk/src/matrix";
import { deriveKey } from "matrix-js-sdk/src/crypto/key_passphrase";
import { decodeRecoveryKey } from "matrix-js-sdk/src/crypto/recoverykey";
import { logger } from "matrix-js-sdk/src/logger";
Expand Down Expand Up @@ -249,7 +243,7 @@ async function onSecretRequested(
deviceId: string,
requestId: string,
name: string,
deviceTrust: DeviceVerificationStatus,
deviceTrust: Crypto.DeviceVerificationStatus,
): Promise<string | undefined> {
logger.log("onSecretRequested", userId, deviceId, requestId, name, deviceTrust);
const client = MatrixClientPeg.safeGet();
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/dialogs/CreateRoomDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
</summary>
<LabelledToggleSwitch
label={_t("create_room|unfederated", {
serverName: MatrixClientPeg.getHomeserverName(),
serverName: MatrixClientPeg.safeGet().getDomain(),
})}
onChange={this.onNoFederateChange}
value={this.state.noFederate}
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/dialogs/ServerOfflineDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export default class ServerOfflineDialog extends React.PureComponent<IProps> {
timeline = [<div key={1}>{_t("server_offline|empty_timeline")}</div>];
}

const serverName = MatrixClientPeg.getHomeserverName();
const serverName = MatrixClientPeg.safeGet().getDomain();
return (
<BaseDialog
title={_t("server_offline|title")}
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/dialogs/devtools/ServerInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export async function getServerVersionFromFederationApi(client: MatrixClient): P
let baseUrl = client.getHomeserverUrl();

try {
const hsName = MatrixClientPeg.getHomeserverName();
const hsName = MatrixClientPeg.safeGet().getDomain();
// We don't use the js-sdk Autodiscovery module here as it only support client well-known, not server ones.
const response = await fetch(`https://${hsName}/.well-known/matrix/server`);
const json = await response.json();
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/directory/NetworkDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ function useServers(): ServerList {
SettingLevel.ACCOUNT,
);

const homeServer = MatrixClientPeg.getHomeserverName();
const homeServer = MatrixClientPeg.safeGet().getDomain()!;
const configServers = new Set<string>(SdkConfig.getObject("room_directory")?.get("servers") ?? []);
removeAll(configServers, homeServer);
// configured servers take preference over user-defined ones, if one occurs in both ignore the latter one.
Expand Down
4 changes: 1 addition & 3 deletions src/components/views/right_panel/UserInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ import DMRoomMap from "../../../utils/DMRoomMap";
import AccessibleButton, { ButtonEvent } from "../elements/AccessibleButton";
import SdkConfig from "../../../SdkConfig";
import MultiInviter from "../../../utils/MultiInviter";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import E2EIcon from "../rooms/E2EIcon";
import { useTypedEventEmitter } from "../../../hooks/useEventEmitter";
import { textualPowerLevel } from "../../../Roles";
Expand Down Expand Up @@ -1413,8 +1412,7 @@ const BasicUserInfo: React.FC<{

// We don't need a perfect check here, just something to pass as "probably not our homeserver". If
// someone does figure out how to bypass this check the worst that happens is an error.
// FIXME this should be using cli instead of MatrixClientPeg.matrixClient
if (isSynapseAdmin && member.userId.endsWith(`:${MatrixClientPeg.getHomeserverName()}`)) {
if (isSynapseAdmin && member.userId.endsWith(`:${cli.getDomain()}`)) {
synapseDeactivateButton = (
<AccessibleButton
kind="link"
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/usePublicRoomDirectory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const usePublicRoomDirectory = (): {
async ({ limit = 20, query, roomTypes }: IPublicRoomsOpts): Promise<boolean> => {
const opts: IRoomDirectoryOptions = { limit };

if (config?.roomServer != MatrixClientPeg.getHomeserverName()) {
if (config?.roomServer != MatrixClientPeg.safeGet().getDomain()) {
opts.server = config?.roomServer;
}

Expand Down Expand Up @@ -139,7 +139,7 @@ export const usePublicRoomDirectory = (): {
return;
}

const myHomeserver = MatrixClientPeg.getHomeserverName();
const myHomeserver = MatrixClientPeg.safeGet().getDomain()!;
const lsRoomServer = localStorage.getItem(LAST_SERVER_KEY);
const lsInstanceId: string | undefined = localStorage.getItem(LAST_INSTANCE_KEY) ?? undefined;

Expand Down
6 changes: 3 additions & 3 deletions src/rageshake/submit-rageshake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
*/

import { logger } from "matrix-js-sdk/src/logger";
import { Method, MatrixClient, CryptoApi } from "matrix-js-sdk/src/matrix";
import { Method, MatrixClient, Crypto } from "matrix-js-sdk/src/matrix";

import type * as Pako from "pako";
import { MatrixClientPeg } from "../MatrixClientPeg";
Expand Down Expand Up @@ -177,7 +177,7 @@ async function collectSynapseSpecific(client: MatrixClient, body: FormData): Pro
/**
* Collects crypto related information.
*/
async function collectCryptoInfo(cryptoApi: CryptoApi, body: FormData): Promise<void> {
async function collectCryptoInfo(cryptoApi: Crypto.CryptoApi, body: FormData): Promise<void> {
body.append("crypto_version", cryptoApi.getVersion());

const ownDeviceKeys = await cryptoApi.getOwnDeviceKeys();
Expand Down Expand Up @@ -206,7 +206,7 @@ async function collectCryptoInfo(cryptoApi: CryptoApi, body: FormData): Promise<
/**
* Collects information about secret storage and backup.
*/
async function collectRecoveryInfo(client: MatrixClient, cryptoApi: CryptoApi, body: FormData): Promise<void> {
async function collectRecoveryInfo(client: MatrixClient, cryptoApi: Crypto.CryptoApi, body: FormData): Promise<void> {
const secretStorage = client.secretStorage;
body.append("secret_storage_ready", String(await cryptoApi.isSecretStorageReady()));
body.append("secret_storage_key_in_account", String(await secretStorage.hasKey()));
Expand Down
2 changes: 1 addition & 1 deletion src/utils/AutoDiscoveryUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const mapAutoDiscoveryErrorTranslation = (err: AutoDiscoveryError): TranslationK
return _td("auth|autodiscovery_no_well_known");
case AutoDiscoveryError.InvalidJson:
return _td("auth|autodiscovery_invalid_json");
case AutoDiscoveryError.HomeserverTooOld:
case AutoDiscoveryError.UnsupportedHomeserverSpecVersion:
return _td("auth|autodiscovery_hs_incompatible");
}
};
Expand Down
13 changes: 6 additions & 7 deletions src/utils/PasswordScorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import * as zxcvbnEnPackage from "@zxcvbn-ts/language-en";
import { MatrixClient } from "matrix-js-sdk/src/matrix";

import { _t } from "../languageHandler";
import { MatrixClientPeg } from "../MatrixClientPeg";
import SdkConfig from "../SdkConfig";

zxcvbnOptions.setOptions({
Expand Down Expand Up @@ -96,13 +95,13 @@ export function scorePassword(

if (matrixClient) {
inputs.push(matrixClient.getUserIdLocalpart()!);
}

try {
const domain = MatrixClientPeg.getHomeserverName();
inputs.push(domain);
} catch {
// This is fine
try {
const domain = matrixClient.getDomain()!;
inputs.push(domain);
} catch {
// This is fine
}
}

zxcvbnOptions.setTranslations(getTranslations());
Expand Down
4 changes: 2 additions & 2 deletions src/utils/device/dehydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { logger } from "matrix-js-sdk/src/logger";
import { CryptoApi } from "matrix-js-sdk/src/matrix";
import { Crypto } from "matrix-js-sdk/src/matrix";

import { MatrixClientPeg } from "../../MatrixClientPeg";

Expand All @@ -29,7 +29,7 @@ import { MatrixClientPeg } from "../../MatrixClientPeg";
*
* Dehydration can currently only be enabled by setting a flag in the .well-known file.
*/
async function deviceDehydrationEnabled(crypto: CryptoApi | undefined): Promise<boolean> {
async function deviceDehydrationEnabled(crypto: Crypto.CryptoApi | undefined): Promise<boolean> {
if (!crypto) {
return false;
}
Expand Down
3 changes: 0 additions & 3 deletions src/utils/dm/createDmLocalRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export async function createDmLocalRoom(client: MatrixClient, targets: Member[])
room_version: KNOWN_SAFE_ROOM_VERSION,
},
state_key: "",
user_id: userId,
sender: userId,
room_id: localRoom.roomId,
origin_server_ts: Date.now(),
Expand All @@ -62,7 +61,6 @@ export async function createDmLocalRoom(client: MatrixClient, targets: Member[])
content: {
algorithm: MEGOLM_ALGORITHM,
},
user_id: userId,
sender: userId,
state_key: "",
room_id: localRoom.roomId,
Expand All @@ -80,7 +78,6 @@ export async function createDmLocalRoom(client: MatrixClient, targets: Member[])
membership: KnownMembership.Join,
},
state_key: userId,
user_id: userId,
sender: userId,
room_id: localRoom.roomId,
}),
Expand Down
12 changes: 2 additions & 10 deletions test/DeviceListener-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,12 @@ limitations under the License.
*/

import { Mocked, mocked } from "jest-mock";
import {
MatrixEvent,
Room,
MatrixClient,
DeviceVerificationStatus,
CryptoApi,
Device,
ClientStoppedError,
} from "matrix-js-sdk/src/matrix";
import { MatrixEvent, Room, MatrixClient, Device, ClientStoppedError } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import { CryptoEvent } from "matrix-js-sdk/src/crypto";
import { IKeyBackupInfo } from "matrix-js-sdk/src/crypto/keybackup";
import { CryptoSessionStateChange } from "@matrix-org/analytics-events/types/typescript/CryptoSessionStateChange";
import { CrossSigningStatus, KeyBackupInfo } from "matrix-js-sdk/src/crypto-api";
import { CrossSigningStatus, CryptoApi, DeviceVerificationStatus, KeyBackupInfo } from "matrix-js-sdk/src/crypto-api";

import DeviceListener from "../src/DeviceListener";
import { MatrixClientPeg } from "../src/MatrixClientPeg";
Expand Down
3 changes: 2 additions & 1 deletion test/PosthogAnalytics-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ limitations under the License.

import { mocked } from "jest-mock";
import { PostHog } from "posthog-js";
import { CryptoApi, MatrixClient } from "matrix-js-sdk/src/matrix";
import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { CryptoApi } from "matrix-js-sdk/src/crypto-api";

import { Anonymity, getRedactedCurrentLocation, IPosthogEvent, PosthogAnalytics } from "../src/PosthogAnalytics";
import SdkConfig from "../src/SdkConfig";
Expand Down
32 changes: 20 additions & 12 deletions test/TextForEvent-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ function mockPinnedEvent(pinnedMessageIds?: string[], prevPinnedMessageIds?: str
content: {
pinned: pinnedMessageIds,
},
prev_content: {
pinned: prevPinnedMessageIds,
unsigned: {
prev_content: {
pinned: prevPinnedMessageIds,
},
},
});
}
Expand Down Expand Up @@ -183,9 +185,11 @@ describe("TextForEvent", () => {
users_default: usersDefault,
users,
},
prev_content: {
users: prevUsers,
users_default: prevDefault,
unsigned: {
prev_content: {
users: prevUsers,
users_default: prevDefault,
},
},
});
mxEvent.sender = { name: userA.name } as RoomMember;
Expand Down Expand Up @@ -315,9 +319,11 @@ describe("TextForEvent", () => {
alias,
alt_aliases: altAliases,
},
prev_content: {
alias: prevAlias,
alt_aliases: prevAltAliases,
unsigned: {
prev_content: {
alias: prevAlias,
alt_aliases: prevAltAliases,
},
},
});

Expand Down Expand Up @@ -512,10 +518,12 @@ describe("TextForEvent", () => {
avatar_url: "b",
displayname: "Bob",
},
prev_content: {
membership: KnownMembership.Join,
avatar_url: "a",
displayname: "Andy",
unsigned: {
prev_content: {
membership: KnownMembership.Join,
avatar_url: "a",
displayname: "Andy",
},
},
state_key: "@a:foo",
}),
Expand Down
1 change: 0 additions & 1 deletion test/components/structures/RoomView-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,6 @@ describe("RoomView", () => {
content: {
algorithm: MEGOLM_ALGORITHM,
},
user_id: cli.getUserId()!,
sender: cli.getUserId()!,
state_key: "",
room_id: localRoom.roomId,
Expand Down
2 changes: 1 addition & 1 deletion test/components/views/dialogs/SpotlightDialog-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ function mockClient({
}: MockClientOptions = {}): MatrixClient {
stubClient();
const cli = MatrixClientPeg.safeGet();
MatrixClientPeg.getHomeserverName = jest.fn(() => homeserver);
cli.getUserId = jest.fn(() => userId);
cli.getDomain = jest.fn(() => homeserver);
cli.getHomeserverUrl = jest.fn(() => homeserver);
cli.getThirdpartyProtocols = jest.fn(() => Promise.resolve(thirdPartyProtocols));
cli.publicRooms = jest.fn((options) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { render, RenderResult, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import React from "react";
import { mocked, MockedObject } from "jest-mock";
import { CryptoApi, MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
import { Crypto, MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
import { defer, IDeferred, sleep } from "matrix-js-sdk/src/utils";
import { BackupTrustInfo, KeyBackupInfo } from "matrix-js-sdk/src/crypto-api";

Expand All @@ -35,7 +35,7 @@ import RestoreKeyBackupDialog from "../../../../../src/components/views/dialogs/

describe("CreateSecretStorageDialog", () => {
let mockClient: MockedObject<MatrixClient>;
let mockCrypto: MockedObject<CryptoApi>;
let mockCrypto: MockedObject<Crypto.CryptoApi>;

beforeEach(() => {
mockClient = getMockClientWithEventEmitter({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
import React from "react";
import { screen, fireEvent, render, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CryptoApi, IMegolmSessionData } from "matrix-js-sdk/src/matrix";
import { Crypto, IMegolmSessionData } from "matrix-js-sdk/src/matrix";

import * as MegolmExportEncryption from "../../../../../src/utils/MegolmExportEncryption";
import ExportE2eKeysDialog from "../../../../../src/async-components/views/dialogs/security/ExportE2eKeysDialog";
Expand Down Expand Up @@ -70,7 +70,7 @@ describe("ExportE2eKeysDialog", () => {
cli.getCrypto = () => {
return {
exportRoomKeysAsJson,
} as unknown as CryptoApi;
} as unknown as Crypto.CryptoApi;
};

// Mock the result of encrypting the sessions. If we don't do this, the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
import React from "react";
import { fireEvent, render, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CryptoApi } from "matrix-js-sdk/src/matrix";
import { Crypto } from "matrix-js-sdk/src/matrix";

import ImportE2eKeysDialog from "../../../../../src/async-components/views/dialogs/security/ImportE2eKeysDialog";
import * as MegolmExportEncryption from "../../../../../src/utils/MegolmExportEncryption";
Expand Down Expand Up @@ -75,7 +75,7 @@ describe("ImportE2eKeysDialog", () => {
cli.getCrypto = () => {
return {
importRoomKeysAsJson,
} as unknown as CryptoApi;
} as unknown as Crypto.CryptoApi;
};

// Mock the result of decrypting the sessions, to avoid needing to
Expand Down
Loading
Loading