Skip to content

Commit

Permalink
Eliminate the use of MatrixClientPeg in utils (#10910)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy committed May 23, 2023
1 parent a0c2676 commit 30429df
Show file tree
Hide file tree
Showing 108 changed files with 409 additions and 325 deletions.
21 changes: 12 additions & 9 deletions src/ContentMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,15 +436,18 @@ export default class ContentMessages {
}
}

promBefore = doMaybeLocalRoomAction(roomId, (actualRoomId) =>
this.sendContentToRoom(
file,
actualRoomId,
relation,
matrixClient,
replyToEvent ?? undefined,
loopPromiseBefore,
),
promBefore = doMaybeLocalRoomAction(
roomId,
(actualRoomId) =>
this.sendContentToRoom(
file,
actualRoomId,
relation,
matrixClient,
replyToEvent ?? undefined,
loopPromiseBefore,
),
matrixClient,
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/DeviceListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ export default class DeviceListener {
} else {
// No cross-signing or key backup on account (set up encryption)
await cli.waitForClientWellKnown();
if (isSecureBackupRequired() && isLoggedIn()) {
if (isSecureBackupRequired(cli) && isLoggedIn()) {
// If we're meant to set up, and Secure Backup is required,
// trigger the flow directly without a toast once logged in.
hideSetupEncryptionToast();
Expand Down
6 changes: 3 additions & 3 deletions src/IdentityAuthClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ export default class IdentityAuthClient {

if (
!this.tempClient &&
!doesAccountDataHaveIdentityServer() &&
!(await doesIdentityServerHaveTerms(identityServerUrl))
!doesAccountDataHaveIdentityServer(this.matrixClient) &&
!(await doesIdentityServerHaveTerms(this.matrixClient, identityServerUrl))
) {
const { finished } = Modal.createDialog(QuestionDialog, {
title: _t("Identity server has no terms of service"),
Expand All @@ -158,7 +158,7 @@ export default class IdentityAuthClient {
});
const [confirmed] = await finished;
if (confirmed) {
setToDefaultIdentityServer();
setToDefaultIdentityServer(this.matrixClient);
} else {
throw new AbortedIdentityActionError("User aborted identity server action without terms");
}
Expand Down
2 changes: 1 addition & 1 deletion src/LegacyCallHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

try {
await WidgetUtils.addJitsiWidget(roomId, type, "Jitsi", false);
await WidgetUtils.addJitsiWidget(client, roomId, type, "Jitsi", false);
logger.log("Jitsi widget added");
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_FORBIDDEN") {
Expand Down
9 changes: 5 additions & 4 deletions src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable
}

dis.fire(Action.OnLoggedIn);
await startMatrixClient(/*startSyncing=*/ !softLogout);
await startMatrixClient(client, /*startSyncing=*/ !softLogout);

return client;
}
Expand Down Expand Up @@ -780,10 +780,11 @@ export function isLoggingOut(): boolean {
/**
* Starts the matrix client and all other react-sdk services that
* listen for events while a session is logged in.
* @param client the matrix client to start
* @param {boolean} startSyncing True (default) to actually start
* syncing the client.
*/
async function startMatrixClient(startSyncing = true): Promise<void> {
async function startMatrixClient(client: MatrixClient, startSyncing = true): Promise<void> {
logger.log(`Lifecycle: Starting MatrixClient`);

// dispatch this before starting the matrix client: it's used
Expand All @@ -796,10 +797,10 @@ async function startMatrixClient(startSyncing = true): Promise<void> {
SdkContextClass.instance.typingStore.reset();
ToastStore.sharedInstance().reset();

DialogOpener.instance.prepare();
DialogOpener.instance.prepare(client);
Notifier.start();
UserActivity.sharedInstance().start();
DMRoomMap.makeShared().start();
DMRoomMap.makeShared(client).start();
IntegrationManagers.sharedInstance().startWatching();
ActiveWidgetStore.instance.start();
LegacyCallHandler.instance.start();
Expand Down
7 changes: 5 additions & 2 deletions src/RoomInvite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { User } from "matrix-js-sdk/src/models/user";
import { logger } from "matrix-js-sdk/src/logger";
import { EventType } from "matrix-js-sdk/src/@types/event";
import { MatrixClient } from "matrix-js-sdk/src/matrix";

import { MatrixClientPeg } from "./MatrixClientPeg";
import MultiInviter, { CompletionStates } from "./utils/MultiInviter";
Expand Down Expand Up @@ -49,12 +50,13 @@ export interface IInviteResult {
* @returns {Promise} Promise
*/
export function inviteMultipleToRoom(
client: MatrixClient,
roomId: string,
addresses: string[],
sendSharedHistoryKeys = false,
progressCallback?: () => void,
): Promise<IInviteResult> {
const inviter = new MultiInviter(roomId, progressCallback);
const inviter = new MultiInviter(client, roomId, progressCallback);
return inviter
.invite(addresses, undefined, sendSharedHistoryKeys)
.then((states) => Promise.resolve({ states, inviter }));
Expand Down Expand Up @@ -105,12 +107,13 @@ export function isValid3pidInvite(event: MatrixEvent): boolean {
}

export function inviteUsersToRoom(
client: MatrixClient,
roomId: string,
userIds: string[],
sendSharedHistoryKeys = false,
progressCallback?: () => void,
): Promise<void> {
return inviteMultipleToRoom(roomId, userIds, sendSharedHistoryKeys, progressCallback)
return inviteMultipleToRoom(client, roomId, userIds, sendSharedHistoryKeys, progressCallback)
.then((result) => {
const room = MatrixClientPeg.get().getRoom(roomId)!;
showAnyInviteErrors(result.states, room, result.inviter);
Expand Down
6 changes: 4 additions & 2 deletions src/ScalarMessaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ function kickUser(event: MessageEvent<any>, roomId: string, userId: string): voi
}

function setWidget(event: MessageEvent<any>, roomId: string | null): void {
const client = MatrixClientPeg.get();
const widgetId = event.data.widget_id;
let widgetType = event.data.type;
const widgetUrl = event.data.url;
Expand Down Expand Up @@ -458,7 +459,7 @@ function setWidget(event: MessageEvent<any>, roomId: string | null): void {
widgetType = WidgetType.fromString(widgetType);

if (userWidget) {
WidgetUtils.setUserWidget(widgetId, widgetType, widgetUrl, widgetName, widgetData)
WidgetUtils.setUserWidget(client, widgetId, widgetType, widgetUrl, widgetName, widgetData)
.then(() => {
sendResponse(event, {
success: true,
Expand All @@ -476,6 +477,7 @@ function setWidget(event: MessageEvent<any>, roomId: string | null): void {
return;
}
WidgetUtils.setRoomWidget(
client,
roomId,
widgetId,
widgetType,
Expand Down Expand Up @@ -516,7 +518,7 @@ function getWidgets(event: MessageEvent<any>, roomId: string | null): void {
}

// Add user widgets (not linked to a specific room)
const userWidgets = WidgetUtils.getUserWidgetsArray();
const userWidgets = WidgetUtils.getUserWidgetsArray(client);
widgetStateEvents = widgetStateEvents.concat(userWidgets);

sendResponse(event, widgetStateEvents);
Expand Down
2 changes: 1 addition & 1 deletion src/SecurityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ export async function accessSecretStorage(func = async (): Promise<void> => {},
onBeforeClose: async (reason): Promise<boolean> => {
// If Secure Backup is required, you cannot leave the modal.
if (reason === "backgroundClick") {
return !isSecureBackupRequired();
return !isSecureBackupRequired(cli);
}
return true;
},
Expand Down
12 changes: 7 additions & 5 deletions src/SlashCommands.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ export const Commands = [

prom = finished.then(([useDefault]) => {
if (useDefault) {
setToDefaultIdentityServer();
setToDefaultIdentityServer(MatrixClientPeg.get());
return;
}
throw new UserFriendlyError(
Expand All @@ -589,7 +589,7 @@ export const Commands = [
);
}
}
const inviter = new MultiInviter(roomId);
const inviter = new MultiInviter(MatrixClientPeg.get(), roomId);
return success(
prom
.then(() => {
Expand Down Expand Up @@ -765,7 +765,7 @@ export const Commands = [
}

if (!targetRoomId) targetRoomId = roomId;
return success(leaveRoomBehaviour(targetRoomId));
return success(leaveRoomBehaviour(cli, targetRoomId));
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
Expand Down Expand Up @@ -1018,7 +1018,7 @@ export const Commands = [
if (!widgetUrl.startsWith("https://") && !widgetUrl.startsWith("http://")) {
return reject(new UserFriendlyError("Please supply a https:// or http:// widget URL"));
}
if (WidgetUtils.canUserModifyWidgets(roomId)) {
if (WidgetUtils.canUserModifyWidgets(MatrixClientPeg.get(), roomId)) {
const userId = MatrixClientPeg.get().getUserId();
const nowMs = new Date().getTime();
const widgetId = encodeURIComponent(`${roomId}_${userId}_${nowMs}`);
Expand All @@ -1036,7 +1036,9 @@ export const Commands = [
widgetUrl = WidgetUtils.getLocalJitsiWrapperUrl();
}

return success(WidgetUtils.setRoomWidget(roomId, widgetId, type, widgetUrl, name, data));
return success(
WidgetUtils.setRoomWidget(MatrixClientPeg.get(), roomId, widgetId, type, widgetUrl, name, data),
);
} else {
return reject(new UserFriendlyError("You cannot modify widgets in this room."));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ export default class CreateSecretStorageDialog extends React.PureComponent<IProp
public constructor(props: IProps) {
super(props);

let passPhraseKeySelected;
const setupMethods = getSecureBackupSetupMethods();
const cli = MatrixClientPeg.get();

let passPhraseKeySelected: SecureBackupSetupMethod;
const setupMethods = getSecureBackupSetupMethods(cli);
if (setupMethods.includes(SecureBackupSetupMethod.Key)) {
passPhraseKeySelected = SecureBackupSetupMethod.Key;
} else {
Expand Down Expand Up @@ -143,13 +145,13 @@ export default class CreateSecretStorageDialog extends React.PureComponent<IProp
// does the server offer a UI auth flow with just m.login.password
// for /keys/device_signing/upload?
accountPasswordCorrect: null,
canSkip: !isSecureBackupRequired(),
canSkip: !isSecureBackupRequired(cli),
canUploadKeysWithPasswordOnly,
passPhraseKeySelected,
accountPassword,
};

MatrixClientPeg.get().on(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatusChange);
cli.on(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatusChange);

this.getInitialPhase();
}
Expand Down Expand Up @@ -542,7 +544,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent<IProp
}

private renderPhaseChooseKeyPassphrase(): JSX.Element {
const setupMethods = getSecureBackupSetupMethods();
const setupMethods = getSecureBackupSetupMethods(MatrixClientPeg.get());
const optionKey = setupMethods.includes(SecureBackupSetupMethod.Key) ? this.renderOptionKey() : null;
const optionPassphrase = setupMethods.includes(SecureBackupSetupMethod.Passphrase)
? this.renderOptionPassphrase()
Expand Down
4 changes: 2 additions & 2 deletions src/autocomplete/RoomProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function matcherObject(
export default class RoomProvider extends AutocompleteProvider {
protected matcher: QueryMatcher<ReturnType<typeof matcherObject>>;

public constructor(room: Room, renderingType?: TimelineRenderingType) {
public constructor(private readonly room: Room, renderingType?: TimelineRenderingType) {
super({ commandRegex: ROOM_REGEX, renderingType });
this.matcher = new QueryMatcher<ReturnType<typeof matcherObject>>([], {
keys: ["displayedAlias", "matchName"],
Expand Down Expand Up @@ -119,7 +119,7 @@ export default class RoomProvider extends AutocompleteProvider {
completionId: room.room.roomId,
type: "room",
suffix: " ",
href: makeRoomPermalink(room.displayedAlias),
href: makeRoomPermalink(this.room.client, room.displayedAlias),
component: (
<PillCompletion title={room.room.name} description={room.displayedAlias}>
<RoomAvatar width={24} height={24} room={room.room} />
Expand Down
5 changes: 3 additions & 2 deletions src/components/structures/HomePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { OwnProfileStore } from "../../stores/OwnProfileStore";
import AccessibleButton, { ButtonEvent } from "../views/elements/AccessibleButton";
import { UPDATE_EVENT } from "../../stores/AsyncStore";
import { useEventEmitter } from "../../hooks/useEventEmitter";
import MatrixClientContext from "../../contexts/MatrixClientContext";
import MatrixClientContext, { useMatrixClientContext } from "../../contexts/MatrixClientContext";
import MiniAvatarUploader, { AVATAR_SIZE } from "../views/elements/MiniAvatarUploader";
import PosthogTrackers from "../../PosthogTrackers";
import EmbeddedPage from "./EmbeddedPage";
Expand Down Expand Up @@ -97,8 +97,9 @@ const UserWelcomeTop: React.FC = () => {
};

const HomePage: React.FC<IProps> = ({ justRegistered = false }) => {
const cli = useMatrixClientContext();
const config = SdkConfig.get();
const pageUrl = getHomePageUrl(config);
const pageUrl = getHomePageUrl(config, cli);

if (pageUrl) {
return <EmbeddedPage className="mx_HomePage" url={pageUrl} scrollbar={true} />;
Expand Down
9 changes: 5 additions & 4 deletions src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1154,7 +1154,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}

private leaveRoom(roomId: string): void {
const roomToLeave = MatrixClientPeg.get().getRoom(roomId);
const cli = MatrixClientPeg.get();
const roomToLeave = cli.getRoom(roomId);
const warnings = this.leaveRoomWarnings(roomId);

const isSpace = roomToLeave?.isSpaceRoom();
Expand All @@ -1173,9 +1174,9 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
</span>
),
button: _t("Leave"),
onFinished: (shouldLeave) => {
onFinished: async (shouldLeave) => {
if (shouldLeave) {
leaveRoomBehaviour(roomId);
await leaveRoomBehaviour(cli, roomId);

dis.dispatch<AfterLeaveRoomPayload>({
action: Action.AfterLeaveRoom,
Expand Down Expand Up @@ -1211,7 +1212,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}

private async copyRoom(roomId: string): Promise<void> {
const roomLink = makeRoomPermalink(roomId);
const roomLink = makeRoomPermalink(MatrixClientPeg.get(), roomId);
const success = await copyPlaintext(roomLink);
if (!success) {
Modal.createDialog(ErrorDialog, {
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/MessagePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
lastInSection =
willWantDateSeparator ||
mxEv.getSender() !== nextEv.getSender() ||
getEventDisplayInfo(nextEv, this.showHiddenEvents).isInfoMessage ||
getEventDisplayInfo(MatrixClientPeg.get(), nextEv, this.showHiddenEvents).isInfoMessage ||
!shouldFormContinuation(mxEv, nextEv, this.showHiddenEvents, this.context.timelineRenderingType);
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/RoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
createdByCurrentUserTs - lastCreatedByOtherTs < PREVENT_MULTIPLE_JITSI_WITHIN
) {
// more than one Jitsi widget with the last one from the current user → remove it
WidgetUtils.setRoomWidget(this.state.roomId, createdByCurrentUser.id);
WidgetUtils.setRoomWidget(this.context.client, this.state.roomId, createdByCurrentUser.id);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/SpaceRoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ const SpaceSetupPrivateInvite: React.FC<{
setBusy(true);
const targetIds = emailAddresses.map((name) => name.trim()).filter(Boolean);
try {
const result = await inviteMultipleToRoom(space.roomId, targetIds);
const result = await inviteMultipleToRoom(space.client, space.roomId, targetIds);

const failedUsers = Object.keys(result.states).filter((a) => result.states[a] === "error");
if (failedUsers.length > 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/UserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
}

private get hasHomePage(): boolean {
return !!getHomePageUrl(SdkConfig.get());
return !!getHomePageUrl(SdkConfig.get(), this.context.client!);
}

private onCurrentVoiceBroadcastRecordingChanged = (recording: VoiceBroadcastRecording | null): void => {
Expand Down
4 changes: 3 additions & 1 deletion src/components/structures/ViewSource.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ export default class ViewSource extends React.Component<IProps, IState> {
const isEditing = this.state.isEditing;
const roomId = mxEvent.getRoomId()!;
const eventId = mxEvent.getId()!;
const canEdit = mxEvent.isState() ? this.canSendStateEvent(mxEvent) : canEditContent(this.props.mxEvent);
const canEdit = mxEvent.isState()
? this.canSendStateEvent(mxEvent)
: canEditContent(MatrixClientPeg.get(), this.props.mxEvent);
return (
<BaseDialog className="mx_ViewSource" onFinished={this.props.onFinished} title={_t("View Source")}>
<div className="mx_ViewSource_header">
Expand Down
3 changes: 2 additions & 1 deletion src/components/views/auth/PassphraseField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import SdkConfig from "../../../SdkConfig";
import withValidation, { IFieldState, IValidationResult } from "../elements/Validation";
import { _t, _td } from "../../../languageHandler";
import Field, { IInputProps } from "../elements/Field";
import { MatrixClientPeg } from "../../../MatrixClientPeg";

interface IProps extends Omit<IInputProps, "onValidate" | "element"> {
autoFocus?: boolean;
Expand Down Expand Up @@ -56,7 +57,7 @@ class PassphraseField extends PureComponent<IProps> {
deriveData: async ({ value }): Promise<zxcvbn.ZXCVBNResult | null> => {
if (!value) return null;
const { scorePassword } = await import("../../../utils/PasswordScorer");
return scorePassword(value);
return scorePassword(MatrixClientPeg.get(), value);
},
rules: [
{
Expand Down
Loading

0 comments on commit 30429df

Please sign in to comment.