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

Commit dd46db4

Browse files
authored
Use MatrixClientPeg::safeGet in src/{stores,hooks,components/structures}/* (#10988)
1 parent 707fd9c commit dd46db4

34 files changed

+139
-130
lines changed

src/components/structures/FilePanel.tsx

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ class FilePanel extends React.Component<IProps, IState> {
7474
if (room?.roomId !== this.props.roomId) return;
7575
if (toStartOfTimeline || !data || !data.liveEvent || ev.isRedacted()) return;
7676

77-
const client = MatrixClientPeg.get();
77+
const client = MatrixClientPeg.safeGet();
7878
client.decryptEventIfNeeded(ev);
7979

8080
if (ev.isBeingDecrypted()) {
@@ -109,11 +109,11 @@ class FilePanel extends React.Component<IProps, IState> {
109109
}
110110

111111
public async componentDidMount(): Promise<void> {
112-
const client = MatrixClientPeg.get();
112+
const client = MatrixClientPeg.safeGet();
113113

114114
await this.updateTimelineSet(this.props.roomId);
115115

116-
if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;
116+
if (!client.isRoomEncrypted(this.props.roomId)) return;
117117

118118
// The timelineSets filter makes sure that encrypted events that contain
119119
// URLs never get added to the timeline, even if they are live events.
@@ -133,7 +133,7 @@ class FilePanel extends React.Component<IProps, IState> {
133133
const client = MatrixClientPeg.get();
134134
if (client === null) return;
135135

136-
if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;
136+
if (!client.isRoomEncrypted(this.props.roomId)) return;
137137

138138
if (EventIndexPeg.get() !== null) {
139139
client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);
@@ -142,9 +142,9 @@ class FilePanel extends React.Component<IProps, IState> {
142142
}
143143

144144
public async fetchFileEventsServer(room: Room): Promise<EventTimelineSet> {
145-
const client = MatrixClientPeg.get();
145+
const client = MatrixClientPeg.safeGet();
146146

147-
const filter = new Filter(client.credentials.userId);
147+
const filter = new Filter(client.getSafeUserId());
148148
filter.setDefinition({
149149
room: {
150150
timeline: {
@@ -163,7 +163,7 @@ class FilePanel extends React.Component<IProps, IState> {
163163
direction: Direction,
164164
limit: number,
165165
): Promise<boolean> => {
166-
const client = MatrixClientPeg.get();
166+
const client = MatrixClientPeg.safeGet();
167167
const eventIndex = EventIndexPeg.get();
168168
const roomId = this.props.roomId;
169169

@@ -185,7 +185,7 @@ class FilePanel extends React.Component<IProps, IState> {
185185
};
186186

187187
public async updateTimelineSet(roomId: string): Promise<void> {
188-
const client = MatrixClientPeg.get();
188+
const client = MatrixClientPeg.safeGet();
189189
const room = client.getRoom(roomId);
190190
const eventIndex = EventIndexPeg.get();
191191

@@ -221,7 +221,7 @@ class FilePanel extends React.Component<IProps, IState> {
221221
}
222222

223223
public render(): React.ReactNode {
224-
if (MatrixClientPeg.get().isGuest()) {
224+
if (MatrixClientPeg.safeGet().isGuest()) {
225225
return (
226226
<BaseCard className="mx_FilePanel mx_RoomView_messageListWrapper" onClose={this.props.onClose}>
227227
<div className="mx_RoomView_empty">
@@ -256,7 +256,7 @@ class FilePanel extends React.Component<IProps, IState> {
256256
</div>
257257
);
258258

259-
const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.get().isRoomEncrypted(this.props.roomId);
259+
const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.safeGet().isRoomEncrypted(this.props.roomId);
260260

261261
if (this.state.timelineSet) {
262262
return (

src/components/structures/LegacyCallEventGrouper.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ export default class LegacyCallEventGrouper extends EventEmitter {
129129
public get callWasMissed(): boolean {
130130
return (
131131
this.state === CallState.Ended &&
132-
![...this.events].some((event) => event.sender?.userId === MatrixClientPeg.get().getUserId())
132+
![...this.events].some((event) => event.sender?.userId === MatrixClientPeg.safeGet().getUserId())
133133
);
134134
}
135135

src/components/structures/MatrixChat.tsx

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { throttle } from "lodash";
3232
import { CryptoEvent } from "matrix-js-sdk/src/crypto";
3333
import { RoomType } from "matrix-js-sdk/src/@types/event";
3434
import { DecryptionError } from "matrix-js-sdk/src/crypto/algorithms";
35+
import { IKeyBackupInfo } from "matrix-js-sdk/src/crypto/keybackup";
3536

3637
// focus-visible is a Polyfill for the :focus-visible CSS pseudo-attribute used by various components
3738
import "focus-visible";
@@ -355,7 +356,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
355356
}
356357

357358
private async postLoginSetup(): Promise<void> {
358-
const cli = MatrixClientPeg.get();
359+
const cli = MatrixClientPeg.safeGet();
359360
const cryptoEnabled = cli.isCryptoEnabled();
360361
if (!cryptoEnabled) {
361362
this.onLoggedIn();
@@ -574,11 +575,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
574575
if (payload.event_type === "m.identity_server") {
575576
const fullUrl = payload.event_content ? payload.event_content["base_url"] : null;
576577
if (!fullUrl) {
577-
MatrixClientPeg.get().setIdentityServerUrl(undefined);
578+
MatrixClientPeg.safeGet().setIdentityServerUrl(undefined);
578579
localStorage.removeItem("mx_is_access_token");
579580
localStorage.removeItem("mx_is_url");
580581
} else {
581-
MatrixClientPeg.get().setIdentityServerUrl(fullUrl);
582+
MatrixClientPeg.safeGet().setIdentityServerUrl(fullUrl);
582583
localStorage.removeItem("mx_is_access_token"); // clear token
583584
localStorage.setItem("mx_is_url", fullUrl); // XXX: Do we still need this?
584585
}
@@ -625,7 +626,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
625626
this.notifyNewScreen("forgot_password");
626627
break;
627628
case "start_chat":
628-
createRoom(MatrixClientPeg.get(), {
629+
createRoom(MatrixClientPeg.safeGet(), {
629630
dmUserId: payload.user_id,
630631
});
631632
break;
@@ -647,7 +648,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
647648
// FIXME: controller shouldn't be loading a view :(
648649
const modal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
649650

650-
MatrixClientPeg.get()
651+
MatrixClientPeg.safeGet()
651652
.leave(payload.room_id)
652653
.then(
653654
() => {
@@ -755,7 +756,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
755756
this.viewSomethingBehindModal();
756757
break;
757758
case "view_invite": {
758-
const room = MatrixClientPeg.get().getRoom(payload.roomId);
759+
const room = MatrixClientPeg.safeGet().getRoom(payload.roomId);
759760
if (room?.isSpaceRoom()) {
760761
showSpaceInvite(room);
761762
} else {
@@ -794,7 +795,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
794795
Modal.createDialog(DialPadModal, {}, "mx_Dialog_dialPadWrapper");
795796
break;
796797
case Action.OnLoggedIn:
797-
this.stores.client = MatrixClientPeg.get();
798+
this.stores.client = MatrixClientPeg.safeGet();
798799
if (
799800
// Skip this handling for token login as that always calls onLoggedIn itself
800801
!this.tokenLogin &&
@@ -935,7 +936,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
935936
}
936937

937938
let presentedId = roomInfo.room_alias || roomInfo.room_id!;
938-
const room = MatrixClientPeg.get().getRoom(roomInfo.room_id);
939+
const room = MatrixClientPeg.safeGet().getRoom(roomInfo.room_id);
939940
if (room) {
940941
// Not all timeline events are decrypted ahead of time anymore
941942
// Only the critical ones for a typical UI are
@@ -1062,14 +1063,14 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
10621063

10631064
const [shouldCreate, opts] = await modal.finished;
10641065
if (shouldCreate) {
1065-
createRoom(MatrixClientPeg.get(), opts!);
1066+
createRoom(MatrixClientPeg.safeGet(), opts!);
10661067
}
10671068
}
10681069

10691070
private chatCreateOrReuse(userId: string): void {
10701071
const snakedConfig = new SnakedObject<IConfigOptions>(this.props.config);
10711072
// Use a deferred action to reshow the dialog once the user has registered
1072-
if (MatrixClientPeg.get().isGuest()) {
1073+
if (MatrixClientPeg.safeGet().isGuest()) {
10731074
// No point in making 2 DMs with welcome bot. This assumes view_set_mxid will
10741075
// result in a new DM with the welcome user.
10751076
if (userId !== snakedConfig.get("welcome_user_id")) {
@@ -1098,7 +1099,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
10981099

10991100
// TODO: Immutable DMs replaces this
11001101

1101-
const client = MatrixClientPeg.get();
1102+
const client = MatrixClientPeg.safeGet();
11021103
const dmRoom = findDMForUser(client, userId);
11031104

11041105
if (dmRoom) {
@@ -1116,7 +1117,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
11161117
}
11171118

11181119
private leaveRoomWarnings(roomId: string): JSX.Element[] {
1119-
const roomToLeave = MatrixClientPeg.get().getRoom(roomId);
1120+
const roomToLeave = MatrixClientPeg.safeGet().getRoom(roomId);
11201121
const isSpace = roomToLeave?.isSpaceRoom();
11211122
// Show a warning if there are additional complications.
11221123
const warnings: JSX.Element[] = [];
@@ -1154,7 +1155,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
11541155
}
11551156

11561157
private leaveRoom(roomId: string): void {
1157-
const cli = MatrixClientPeg.get();
1158+
const cli = MatrixClientPeg.safeGet();
11581159
const roomToLeave = cli.getRoom(roomId);
11591160
const warnings = this.leaveRoomWarnings(roomId);
11601161

@@ -1188,8 +1189,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
11881189
}
11891190

11901191
private forgetRoom(roomId: string): void {
1191-
const room = MatrixClientPeg.get().getRoom(roomId);
1192-
MatrixClientPeg.get()
1192+
const room = MatrixClientPeg.safeGet().getRoom(roomId);
1193+
MatrixClientPeg.safeGet()
11931194
.forget(roomId)
11941195
.then(() => {
11951196
// Switch to home page if we're currently viewing the forgotten room
@@ -1212,7 +1213,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
12121213
}
12131214

12141215
private async copyRoom(roomId: string): Promise<void> {
1215-
const roomLink = makeRoomPermalink(MatrixClientPeg.get(), roomId);
1216+
const roomLink = makeRoomPermalink(MatrixClientPeg.safeGet(), roomId);
12161217
const success = await copyPlaintext(roomLink);
12171218
if (!success) {
12181219
Modal.createDialog(ErrorDialog, {
@@ -1246,7 +1247,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
12461247

12471248
const welcomeUserRooms = DMRoomMap.shared().getDMRoomsForUserId(welcomeUserId);
12481249
if (welcomeUserRooms.length === 0) {
1249-
const roomId = await createRoom(MatrixClientPeg.get(), {
1250+
const roomId = await createRoom(MatrixClientPeg.safeGet(), {
12501251
dmUserId: snakedConfig.get("welcome_user_id"),
12511252
// Only view the welcome user if we're NOT looking at a room
12521253
andView: !this.state.currentRoomId,
@@ -1262,11 +1263,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
12621263
// the saved sync to be loaded).
12631264
const saveWelcomeUser = (ev: MatrixEvent): void => {
12641265
if (ev.getType() === EventType.Direct && ev.getContent()[welcomeUserId]) {
1265-
MatrixClientPeg.get().store.save(true);
1266-
MatrixClientPeg.get().removeListener(ClientEvent.AccountData, saveWelcomeUser);
1266+
MatrixClientPeg.safeGet().store.save(true);
1267+
MatrixClientPeg.safeGet().removeListener(ClientEvent.AccountData, saveWelcomeUser);
12671268
}
12681269
};
1269-
MatrixClientPeg.get().on(ClientEvent.AccountData, saveWelcomeUser);
1270+
MatrixClientPeg.safeGet().on(ClientEvent.AccountData, saveWelcomeUser);
12701271

12711272
return roomId;
12721273
}
@@ -1413,7 +1414,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
14131414
// Before defaulting to directory, show the last viewed room
14141415
this.viewLastRoom();
14151416
} else {
1416-
if (MatrixClientPeg.get().isGuest()) {
1417+
if (MatrixClientPeg.safeGet().isGuest()) {
14171418
dis.dispatch({ action: "view_welcome_page" });
14181419
} else {
14191420
dis.dispatch({ action: Action.ViewHomePage });
@@ -1468,7 +1469,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
14681469
// to do the first sync
14691470
this.firstSyncComplete = false;
14701471
this.firstSyncPromise = defer();
1471-
const cli = MatrixClientPeg.get();
1472+
const cli = MatrixClientPeg.safeGet();
14721473

14731474
// Allow the JS SDK to reap timeline events. This reduces the amount of
14741475
// memory consumed as the JS SDK stores multiple distinct copies of room
@@ -1588,7 +1589,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
15881589
cli.on(MatrixEventEvent.Decrypted, (e, err) => dft.eventDecrypted(e, err as DecryptionError));
15891590

15901591
cli.on(ClientEvent.Room, (room) => {
1591-
if (MatrixClientPeg.get().isCryptoEnabled()) {
1592+
if (cli.isCryptoEnabled()) {
15921593
const blacklistEnabled = SettingsStore.getValueAt(
15931594
SettingLevel.ROOM_DEVICE,
15941595
"blacklistUnverifiedDevices",
@@ -1618,15 +1619,15 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
16181619
}
16191620
});
16201621
cli.on(CryptoEvent.KeyBackupFailed, async (errcode): Promise<void> => {
1621-
let haveNewVersion;
1622-
let newVersionInfo;
1622+
let haveNewVersion: boolean | undefined;
1623+
let newVersionInfo: IKeyBackupInfo | null = null;
16231624
// if key backup is still enabled, there must be a new backup in place
1624-
if (MatrixClientPeg.get().getKeyBackupEnabled()) {
1625+
if (cli.getKeyBackupEnabled()) {
16251626
haveNewVersion = true;
16261627
} else {
16271628
// otherwise check the server to see if there's a new one
16281629
try {
1629-
newVersionInfo = await MatrixClientPeg.get().getKeyBackupVersion();
1630+
newVersionInfo = await cli.getKeyBackupVersion();
16301631
if (newVersionInfo !== null) haveNewVersion = true;
16311632
} catch (e) {
16321633
logger.error("Saw key backup error but failed to check backup version!", e);
@@ -1639,7 +1640,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
16391640
import(
16401641
"../../async-components/views/dialogs/security/NewRecoveryMethodDialog"
16411642
) as unknown as Promise<typeof NewRecoveryMethodDialog>,
1642-
{ newVersionInfo },
1643+
{ newVersionInfo: newVersionInfo! },
16431644
);
16441645
} else {
16451646
Modal.createDialogAsync(
@@ -1686,7 +1687,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
16861687
* @private
16871688
*/
16881689
private onClientStarted(): void {
1689-
const cli = MatrixClientPeg.get();
1690+
const cli = MatrixClientPeg.safeGet();
16901691

16911692
if (cli.isCryptoEnabled()) {
16921693
const blacklistEnabled = SettingsStore.getValueAt(SettingLevel.DEVICE, "blacklistUnverifiedDevices");
@@ -1734,7 +1735,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
17341735
params: params,
17351736
});
17361737
} else if (screen === "soft_logout") {
1737-
if (cli.getUserId() && !Lifecycle.isSoftLogout()) {
1738+
if (!!cli?.getUserId() && !Lifecycle.isSoftLogout()) {
17381739
// Logged in - visit a room
17391740
this.viewLastRoom();
17401741
} else {
@@ -2057,7 +2058,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
20572058
{...this.props}
20582059
{...this.state}
20592060
ref={this.loggedInView}
2060-
matrixClient={MatrixClientPeg.get()}
2061+
matrixClient={MatrixClientPeg.safeGet()}
20612062
onRegistered={this.onRegistered}
20622063
currentRoomId={this.state.currentRoomId}
20632064
/>

src/components/structures/MessagePanel.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
473473
}
474474
}
475475

476-
if (MatrixClientPeg.get().isUserIgnored(mxEv.getSender()!)) {
476+
if (MatrixClientPeg.safeGet().isUserIgnored(mxEv.getSender()!)) {
477477
return false; // ignored = no show (only happens if the ignore happens after an event was received)
478478
}
479479

@@ -743,7 +743,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
743743
lastInSection =
744744
willWantDateSeparator ||
745745
mxEv.getSender() !== nextEv.getSender() ||
746-
getEventDisplayInfo(MatrixClientPeg.get(), nextEv, this.showHiddenEvents).isInfoMessage ||
746+
getEventDisplayInfo(MatrixClientPeg.safeGet(), nextEv, this.showHiddenEvents).isInfoMessage ||
747747
!shouldFormContinuation(mxEv, nextEv, this.showHiddenEvents, this.context.timelineRenderingType);
748748
}
749749

@@ -779,7 +779,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
779779

780780
// We only want to consider "last successful" if the event is sent by us, otherwise of course
781781
// it's successful: we received it.
782-
isLastSuccessful = isLastSuccessful && mxEv.getSender() === MatrixClientPeg.get().getUserId();
782+
isLastSuccessful = isLastSuccessful && mxEv.getSender() === MatrixClientPeg.safeGet().getUserId();
783783

784784
const callEventGrouper = this.props.callEventGroupers.get(mxEv.getContent().call_id);
785785
// use txnId as key if available so that we don't remount during sending
@@ -833,7 +833,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
833833
// Get a list of read receipts that should be shown next to this event
834834
// Receipts are objects which have a 'userId', 'roomMember' and 'ts'.
835835
private getReadReceiptsForEvent(event: MatrixEvent): IReadReceiptProps[] | null {
836-
const myUserId = MatrixClientPeg.get().credentials.userId;
836+
const myUserId = MatrixClientPeg.safeGet().credentials.userId;
837837

838838
// get list of read receipts, sorted most recent first
839839
const { room } = this.props;
@@ -856,7 +856,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
856856
if (!r.userId || !isSupportedReceiptType(r.type) || r.userId === myUserId) {
857857
return; // ignore non-read receipts and receipts from self.
858858
}
859-
if (MatrixClientPeg.get().isUserIgnored(r.userId)) {
859+
if (MatrixClientPeg.safeGet().isUserIgnored(r.userId)) {
860860
return; // ignore ignored users
861861
}
862862
const member = room.getMember(r.userId);
@@ -1301,7 +1301,7 @@ class MainGrouper extends BaseGrouper {
13011301
public add({ event: ev, shouldShow }: EventAndShouldShow): void {
13021302
if (ev.getType() === EventType.RoomMember) {
13031303
// We can ignore any events that don't actually have a message to display
1304-
if (!hasText(ev, MatrixClientPeg.get(), this.panel.showHiddenEvents)) return;
1304+
if (!hasText(ev, MatrixClientPeg.safeGet(), this.panel.showHiddenEvents)) return;
13051305
}
13061306
this.readMarker = this.readMarker || this.panel.readMarkerForEvent(ev.getId()!, ev === this.lastShownEvent);
13071307
if (!this.panel.showHiddenEvents && !shouldShow) {

0 commit comments

Comments
 (0)