Skip to content

Commit 9b5b053

Browse files
authored
Use MatrixClientPeg::safeGet for strict typing (matrix-org#10989)
1 parent d64018c commit 9b5b053

File tree

60 files changed

+225
-203
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+225
-203
lines changed

src/IdentityAuthClient.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ export default class IdentityAuthClient {
5959
}
6060

6161
private get matrixClient(): MatrixClient {
62-
return this.tempClient ? this.tempClient : MatrixClientPeg.get();
62+
return this.tempClient ? this.tempClient : MatrixClientPeg.safeGet();
6363
}
6464

6565
private writeToken(): void {
@@ -176,7 +176,7 @@ export default class IdentityAuthClient {
176176
}
177177

178178
public async registerForToken(check = true): Promise<string> {
179-
const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken();
179+
const hsOpenIdToken = await MatrixClientPeg.safeGet().getOpenIdToken();
180180
// XXX: The spec is `token`, but we used `access_token` for a Sydent release.
181181
const { access_token: accessToken, token } = await this.matrixClient.registerWithIdentityServer(hsOpenIdToken);
182182
const identityAccessToken = token ? token : accessToken;

src/LegacyCallHandler.tsx

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ export default class LegacyCallHandler extends EventEmitter {
192192
if (this.shouldObeyAssertedfIdentity()) {
193193
const nativeUser = this.assertedIdentityNativeUsers.get(call.callId);
194194
if (nativeUser) {
195-
const room = findDMForUser(MatrixClientPeg.get(), nativeUser);
195+
const room = findDMForUser(MatrixClientPeg.safeGet(), nativeUser);
196196
if (room) return room.roomId;
197197
}
198198
}
@@ -214,7 +214,7 @@ export default class LegacyCallHandler extends EventEmitter {
214214
}
215215

216216
if (SettingsStore.getValue(UIFeature.Voip)) {
217-
MatrixClientPeg.get().on(CallEventHandlerEvent.Incoming, this.onCallIncoming);
217+
MatrixClientPeg.safeGet().on(CallEventHandlerEvent.Incoming, this.onCallIncoming);
218218
}
219219

220220
this.checkProtocols(CHECK_PROTOCOLS_ATTEMPTS);
@@ -271,7 +271,7 @@ export default class LegacyCallHandler extends EventEmitter {
271271
}
272272

273273
public isForcedSilent(): boolean {
274-
const cli = MatrixClientPeg.get();
274+
const cli = MatrixClientPeg.safeGet();
275275
return localNotificationsAreSilenced(cli);
276276
}
277277

@@ -311,7 +311,7 @@ export default class LegacyCallHandler extends EventEmitter {
311311

312312
private async checkProtocols(maxTries: number): Promise<void> {
313313
try {
314-
const protocols = await MatrixClientPeg.get().getThirdpartyProtocols();
314+
const protocols = await MatrixClientPeg.safeGet().getThirdpartyProtocols();
315315

316316
if (protocols[PROTOCOL_PSTN] !== undefined) {
317317
this.supportsPstnProtocol = Boolean(protocols[PROTOCOL_PSTN]);
@@ -358,7 +358,7 @@ export default class LegacyCallHandler extends EventEmitter {
358358

359359
public async pstnLookup(phoneNumber: string): Promise<ThirdpartyLookupResponse[]> {
360360
try {
361-
return await MatrixClientPeg.get().getThirdpartyUser(
361+
return await MatrixClientPeg.safeGet().getThirdpartyUser(
362362
this.pstnSupportPrefixed ? PROTOCOL_PSTN_PREFIXED : PROTOCOL_PSTN,
363363
{
364364
"m.id.phone": phoneNumber,
@@ -372,7 +372,7 @@ export default class LegacyCallHandler extends EventEmitter {
372372

373373
public async sipVirtualLookup(nativeMxid: string): Promise<ThirdpartyLookupResponse[]> {
374374
try {
375-
return await MatrixClientPeg.get().getThirdpartyUser(PROTOCOL_SIP_VIRTUAL, {
375+
return await MatrixClientPeg.safeGet().getThirdpartyUser(PROTOCOL_SIP_VIRTUAL, {
376376
native_mxid: nativeMxid,
377377
});
378378
} catch (e) {
@@ -383,7 +383,7 @@ export default class LegacyCallHandler extends EventEmitter {
383383

384384
public async sipNativeLookup(virtualMxid: string): Promise<ThirdpartyLookupResponse[]> {
385385
try {
386-
return await MatrixClientPeg.get().getThirdpartyUser(PROTOCOL_SIP_NATIVE, {
386+
return await MatrixClientPeg.safeGet().getThirdpartyUser(PROTOCOL_SIP_NATIVE, {
387387
virtual_mxid: virtualMxid,
388388
});
389389
} catch (e) {
@@ -394,7 +394,7 @@ export default class LegacyCallHandler extends EventEmitter {
394394

395395
private onCallIncoming = (call: MatrixCall): void => {
396396
// if the runtime env doesn't do VoIP, stop here.
397-
if (!MatrixClientPeg.get().supportsVoip()) {
397+
if (!MatrixClientPeg.get()?.supportsVoip()) {
398398
return;
399399
}
400400

@@ -415,7 +415,7 @@ export default class LegacyCallHandler extends EventEmitter {
415415
// get ready to send encrypted events in the room, so if the user does answer
416416
// the call, we'll be ready to send. NB. This is the protocol-level room ID not
417417
// the mapped one: that's where we'll send the events.
418-
const cli = MatrixClientPeg.get();
418+
const cli = MatrixClientPeg.safeGet();
419419
const room = cli.getRoom(call.roomId);
420420
if (room) cli.prepareToEncrypt(room);
421421
};
@@ -463,7 +463,7 @@ export default class LegacyCallHandler extends EventEmitter {
463463
}
464464

465465
public getAllActiveCallsForPip(roomId: string): MatrixCall[] {
466-
const room = MatrixClientPeg.get().getRoom(roomId);
466+
const room = MatrixClientPeg.safeGet().getRoom(roomId);
467467
if (room && WidgetLayoutStore.instance.hasMaximisedWidget(room)) {
468468
// This checks if there is space for the call view in the aux panel
469469
// If there is no space any call should be displayed in PiP
@@ -570,7 +570,7 @@ export default class LegacyCallHandler extends EventEmitter {
570570
}
571571

572572
if (
573-
MatrixClientPeg.get().getTurnServers().length === 0 &&
573+
MatrixClientPeg.safeGet().getTurnServers().length === 0 &&
574574
SettingsStore.getValue("fallbackICEServerAllowed") === null
575575
) {
576576
this.showICEFallbackPrompt();
@@ -638,7 +638,7 @@ export default class LegacyCallHandler extends EventEmitter {
638638
// this if we want the actual, native room to exist (which we do). This is why it's
639639
// important to only obey asserted identity in trusted environments, since anyone you're
640640
// on a call with can cause you to send a room invite to someone.
641-
await ensureDMExists(MatrixClientPeg.get(), newNativeAssertedIdentity);
641+
await ensureDMExists(MatrixClientPeg.safeGet(), newNativeAssertedIdentity);
642642

643643
const newMappedRoomId = this.roomIdForCall(call);
644644
logger.log(`Old room ID: ${mappedRoomId}, new room ID: ${newMappedRoomId}`);
@@ -678,7 +678,7 @@ export default class LegacyCallHandler extends EventEmitter {
678678

679679
switch (newState) {
680680
case CallState.Ringing: {
681-
const incomingCallPushRule = new PushProcessor(MatrixClientPeg.get()).getPushRuleById(
681+
const incomingCallPushRule = new PushProcessor(MatrixClientPeg.safeGet()).getPushRuleById(
682682
RuleId.IncomingCall,
683683
);
684684
const pushRuleEnabled = incomingCallPushRule?.enabled;
@@ -825,7 +825,7 @@ export default class LegacyCallHandler extends EventEmitter {
825825
}
826826

827827
private showICEFallbackPrompt(): void {
828-
const cli = MatrixClientPeg.get();
828+
const cli = MatrixClientPeg.safeGet();
829829
Modal.createDialog(
830830
QuestionDialog,
831831
{
@@ -907,6 +907,7 @@ export default class LegacyCallHandler extends EventEmitter {
907907
}
908908

909909
private async placeMatrixCall(roomId: string, type: CallType, transferee?: MatrixCall): Promise<void> {
910+
const cli = MatrixClientPeg.safeGet();
910911
const mappedRoomId = (await VoipUserMapper.sharedInstance().getOrCreateVirtualRoomForRoom(roomId)) || roomId;
911912
logger.debug("Mapped real room " + roomId + " to room ID " + mappedRoomId);
912913

@@ -916,15 +917,15 @@ export default class LegacyCallHandler extends EventEmitter {
916917
// in this queue, and since we're about to place a new call, they can only be events from
917918
// previous calls that are probably stale by now, so just cancel them.
918919
if (mappedRoomId !== roomId) {
919-
const mappedRoom = MatrixClientPeg.get().getRoom(mappedRoomId);
920+
const mappedRoom = cli.getRoom(mappedRoomId);
920921
if (mappedRoom?.getPendingEvents().length) {
921922
Resend.cancelUnsentEvents(mappedRoom);
922923
}
923924
}
924925

925-
const timeUntilTurnCresExpire = MatrixClientPeg.get().getTurnServersExpiry() - Date.now();
926+
const timeUntilTurnCresExpire = cli.getTurnServersExpiry() - Date.now();
926927
logger.log("Current turn creds expire in " + timeUntilTurnCresExpire + " ms");
927-
const call = MatrixClientPeg.get().createCall(mappedRoomId)!;
928+
const call = cli.createCall(mappedRoomId)!;
928929

929930
try {
930931
this.addCallForRoom(roomId, call);
@@ -953,6 +954,7 @@ export default class LegacyCallHandler extends EventEmitter {
953954
}
954955

955956
public async placeCall(roomId: string, type: CallType, transferee?: MatrixCall): Promise<void> {
957+
const cli = MatrixClientPeg.safeGet();
956958
// Pause current broadcast, if any
957959
SdkContextClass.instance.voiceBroadcastPlaybacksStore.getCurrent()?.pause();
958960

@@ -969,15 +971,15 @@ export default class LegacyCallHandler extends EventEmitter {
969971
}
970972

971973
// if the runtime env doesn't do VoIP, whine.
972-
if (!MatrixClientPeg.get().supportsVoip()) {
974+
if (!cli.supportsVoip()) {
973975
Modal.createDialog(ErrorDialog, {
974976
title: _t("Calls are unsupported"),
975977
description: _t("You cannot place calls in this browser."),
976978
});
977979
return;
978980
}
979981

980-
if (MatrixClientPeg.get().getSyncState() === SyncState.Error) {
982+
if (cli.getSyncState() === SyncState.Error) {
981983
Modal.createDialog(ErrorDialog, {
982984
title: _t("Connectivity to the server has been lost"),
983985
description: _t("You cannot place calls without a connection to the server."),
@@ -994,7 +996,7 @@ export default class LegacyCallHandler extends EventEmitter {
994996
return;
995997
}
996998

997-
const room = MatrixClientPeg.get().getRoom(roomId);
999+
const room = cli.getRoom(roomId);
9981000
if (!room) {
9991001
logger.error(`Room ${roomId} does not exist.`);
10001002
return;
@@ -1095,7 +1097,7 @@ export default class LegacyCallHandler extends EventEmitter {
10951097
nativeUserId = userId;
10961098
}
10971099

1098-
const roomId = await ensureDMExists(MatrixClientPeg.get(), nativeUserId);
1100+
const roomId = await ensureDMExists(MatrixClientPeg.safeGet(), nativeUserId);
10991101
if (!roomId) {
11001102
throw new Error("Failed to ensure DM exists for dialing number");
11011103
}
@@ -1135,7 +1137,7 @@ export default class LegacyCallHandler extends EventEmitter {
11351137

11361138
public async startTransferToMatrixID(call: MatrixCall, destination: string, consultFirst: boolean): Promise<void> {
11371139
if (consultFirst) {
1138-
const dmRoomId = await ensureDMExists(MatrixClientPeg.get(), destination);
1140+
const dmRoomId = await ensureDMExists(MatrixClientPeg.safeGet(), destination);
11391141
if (!dmRoomId) {
11401142
logger.log("Failed to transfer call, could not ensure dm exists");
11411143
Modal.createDialog(ErrorDialog, {
@@ -1194,7 +1196,7 @@ export default class LegacyCallHandler extends EventEmitter {
11941196
}
11951197

11961198
private async placeJitsiCall(roomId: string, type: CallType): Promise<void> {
1197-
const client = MatrixClientPeg.get();
1199+
const client = MatrixClientPeg.safeGet();
11981200
logger.info(`Place conference call in ${roomId}`);
11991201

12001202
dis.dispatch({ action: "appsDrawer", show: true });

src/Lifecycle.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ export function handleInvalidStoreError(e: InvalidStoreError): Promise<void> | v
278278
}
279279
})
280280
.then(() => {
281-
return MatrixClientPeg.get().store.deleteAllData();
281+
return MatrixClientPeg.safeGet().store.deleteAllData();
282282
})
283283
.then(() => {
284284
PlatformPeg.get()?.reload();
@@ -541,8 +541,8 @@ export async function setLoggedIn(credentials: IMatrixClientCreds): Promise<Matr
541541
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
542542
*/
543543
export async function hydrateSession(credentials: IMatrixClientCreds): Promise<MatrixClient> {
544-
const oldUserId = MatrixClientPeg.get().getUserId();
545-
const oldDeviceId = MatrixClientPeg.get().getDeviceId();
544+
const oldUserId = MatrixClientPeg.safeGet().getUserId();
545+
const oldDeviceId = MatrixClientPeg.safeGet().getDeviceId();
546546

547547
stopMatrixClient(); // unsets MatrixClientPeg.get()
548548
localStorage.removeItem("mx_soft_logout");
@@ -603,7 +603,7 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable
603603
}
604604

605605
MatrixClientPeg.replaceUsingCreds(credentials);
606-
const client = MatrixClientPeg.get();
606+
const client = MatrixClientPeg.safeGet();
607607

608608
setSentryUser(credentials.userId);
609609

@@ -724,7 +724,7 @@ export function logout(): void {
724724

725725
PosthogAnalytics.instance.logout();
726726

727-
if (MatrixClientPeg.get().isGuest()) {
727+
if (MatrixClientPeg.get()!.isGuest()) {
728728
// logout doesn't work for guest sessions
729729
// Also we sometimes want to re-log in a guest session if we abort the login.
730730
// defer until next tick because it calls a synchronous dispatch, and we are likely here from a dispatch.
@@ -733,7 +733,7 @@ export function logout(): void {
733733
}
734734

735735
_isLoggingOut = true;
736-
const client = MatrixClientPeg.get();
736+
const client = MatrixClientPeg.get()!;
737737
PlatformPeg.get()?.destroyPickleKey(client.getSafeUserId(), client.getDeviceId() ?? "");
738738
client.logout(true).then(onLoggedOut, (err) => {
739739
// Just throwing an error here is going to be very unhelpful

src/MatrixClientPeg.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ export interface IMatrixClientPeg {
7373
*/
7474
getHomeserverName(): string | null;
7575

76-
get(): MatrixClient;
76+
get(): MatrixClient | null;
7777
safeGet(): MatrixClient;
7878
unset(): void;
7979
assign(): Promise<any>;
@@ -142,7 +142,7 @@ class MatrixClientPegClass implements IMatrixClientPeg {
142142
// used if we tear it down & recreate it with a different store
143143
private currentClientCreds: IMatrixClientCreds | null = null;
144144

145-
public get(): MatrixClient {
145+
public get(): MatrixClient | null {
146146
return this.matrixClient;
147147
}
148148

src/MediaDeviceHandler.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,14 @@ export default class MediaDeviceHandler extends EventEmitter {
9999
const audioDeviceId = SettingsStore.getValue("webrtc_audioinput");
100100
const videoDeviceId = SettingsStore.getValue("webrtc_videoinput");
101101

102-
await MatrixClientPeg.get().getMediaHandler().setAudioInput(audioDeviceId);
103-
await MatrixClientPeg.get().getMediaHandler().setVideoInput(videoDeviceId);
102+
await MatrixClientPeg.safeGet().getMediaHandler().setAudioInput(audioDeviceId);
103+
await MatrixClientPeg.safeGet().getMediaHandler().setVideoInput(videoDeviceId);
104104

105105
await MediaDeviceHandler.updateAudioSettings();
106106
}
107107

108108
private static async updateAudioSettings(): Promise<void> {
109-
await MatrixClientPeg.get().getMediaHandler().setAudioSettings({
109+
await MatrixClientPeg.safeGet().getMediaHandler().setAudioSettings({
110110
autoGainControl: MediaDeviceHandler.getAudioAutoGainControl(),
111111
echoCancellation: MediaDeviceHandler.getAudioEchoCancellation(),
112112
noiseSuppression: MediaDeviceHandler.getAudioNoiseSuppression(),
@@ -125,7 +125,7 @@ export default class MediaDeviceHandler extends EventEmitter {
125125
*/
126126
public async setAudioInput(deviceId: string): Promise<void> {
127127
SettingsStore.setValue("webrtc_audioinput", null, SettingLevel.DEVICE, deviceId);
128-
return MatrixClientPeg.get().getMediaHandler().setAudioInput(deviceId);
128+
return MatrixClientPeg.safeGet().getMediaHandler().setAudioInput(deviceId);
129129
}
130130

131131
/**
@@ -135,7 +135,7 @@ export default class MediaDeviceHandler extends EventEmitter {
135135
*/
136136
public async setVideoInput(deviceId: string): Promise<void> {
137137
SettingsStore.setValue("webrtc_videoinput", null, SettingLevel.DEVICE, deviceId);
138-
return MatrixClientPeg.get().getMediaHandler().setVideoInput(deviceId);
138+
return MatrixClientPeg.safeGet().getMediaHandler().setVideoInput(deviceId);
139139
}
140140

141141
public async setDevice(deviceId: string, kind: MediaDeviceKindEnum): Promise<void> {

0 commit comments

Comments
 (0)