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

Commit

Permalink
Use MatrixClientPeg::safeGet for strict typing (#10989)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy authored Jun 21, 2023
1 parent d64018c commit 9b5b053
Show file tree
Hide file tree
Showing 60 changed files with 225 additions and 203 deletions.
4 changes: 2 additions & 2 deletions src/IdentityAuthClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default class IdentityAuthClient {
}

private get matrixClient(): MatrixClient {
return this.tempClient ? this.tempClient : MatrixClientPeg.get();
return this.tempClient ? this.tempClient : MatrixClientPeg.safeGet();
}

private writeToken(): void {
Expand Down Expand Up @@ -176,7 +176,7 @@ export default class IdentityAuthClient {
}

public async registerForToken(check = true): Promise<string> {
const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken();
const hsOpenIdToken = await MatrixClientPeg.safeGet().getOpenIdToken();
// XXX: The spec is `token`, but we used `access_token` for a Sydent release.
const { access_token: accessToken, token } = await this.matrixClient.registerWithIdentityServer(hsOpenIdToken);
const identityAccessToken = token ? token : accessToken;
Expand Down
48 changes: 25 additions & 23 deletions src/LegacyCallHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export default class LegacyCallHandler extends EventEmitter {
if (this.shouldObeyAssertedfIdentity()) {
const nativeUser = this.assertedIdentityNativeUsers.get(call.callId);
if (nativeUser) {
const room = findDMForUser(MatrixClientPeg.get(), nativeUser);
const room = findDMForUser(MatrixClientPeg.safeGet(), nativeUser);
if (room) return room.roomId;
}
}
Expand All @@ -214,7 +214,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

if (SettingsStore.getValue(UIFeature.Voip)) {
MatrixClientPeg.get().on(CallEventHandlerEvent.Incoming, this.onCallIncoming);
MatrixClientPeg.safeGet().on(CallEventHandlerEvent.Incoming, this.onCallIncoming);
}

this.checkProtocols(CHECK_PROTOCOLS_ATTEMPTS);
Expand Down Expand Up @@ -271,7 +271,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

public isForcedSilent(): boolean {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
return localNotificationsAreSilenced(cli);
}

Expand Down Expand Up @@ -311,7 +311,7 @@ export default class LegacyCallHandler extends EventEmitter {

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

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

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

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

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

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

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

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

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

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

switch (newState) {
case CallState.Ringing: {
const incomingCallPushRule = new PushProcessor(MatrixClientPeg.get()).getPushRuleById(
const incomingCallPushRule = new PushProcessor(MatrixClientPeg.safeGet()).getPushRuleById(
RuleId.IncomingCall,
);
const pushRuleEnabled = incomingCallPushRule?.enabled;
Expand Down Expand Up @@ -825,7 +825,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

private showICEFallbackPrompt(): void {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
Modal.createDialog(
QuestionDialog,
{
Expand Down Expand Up @@ -907,6 +907,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

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

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

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

try {
this.addCallForRoom(roomId, call);
Expand Down Expand Up @@ -953,6 +954,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

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

Expand All @@ -969,15 +971,15 @@ export default class LegacyCallHandler extends EventEmitter {
}

// if the runtime env doesn't do VoIP, whine.
if (!MatrixClientPeg.get().supportsVoip()) {
if (!cli.supportsVoip()) {
Modal.createDialog(ErrorDialog, {
title: _t("Calls are unsupported"),
description: _t("You cannot place calls in this browser."),
});
return;
}

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

const room = MatrixClientPeg.get().getRoom(roomId);
const room = cli.getRoom(roomId);
if (!room) {
logger.error(`Room ${roomId} does not exist.`);
return;
Expand Down Expand Up @@ -1095,7 +1097,7 @@ export default class LegacyCallHandler extends EventEmitter {
nativeUserId = userId;
}

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

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

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

dis.dispatch({ action: "appsDrawer", show: true });
Expand Down
12 changes: 6 additions & 6 deletions src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ export function handleInvalidStoreError(e: InvalidStoreError): Promise<void> | v
}
})
.then(() => {
return MatrixClientPeg.get().store.deleteAllData();
return MatrixClientPeg.safeGet().store.deleteAllData();
})
.then(() => {
PlatformPeg.get()?.reload();
Expand Down Expand Up @@ -541,8 +541,8 @@ export async function setLoggedIn(credentials: IMatrixClientCreds): Promise<Matr
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
*/
export async function hydrateSession(credentials: IMatrixClientCreds): Promise<MatrixClient> {
const oldUserId = MatrixClientPeg.get().getUserId();
const oldDeviceId = MatrixClientPeg.get().getDeviceId();
const oldUserId = MatrixClientPeg.safeGet().getUserId();
const oldDeviceId = MatrixClientPeg.safeGet().getDeviceId();

stopMatrixClient(); // unsets MatrixClientPeg.get()
localStorage.removeItem("mx_soft_logout");
Expand Down Expand Up @@ -603,7 +603,7 @@ async function doSetLoggedIn(credentials: IMatrixClientCreds, clearStorageEnable
}

MatrixClientPeg.replaceUsingCreds(credentials);
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();

setSentryUser(credentials.userId);

Expand Down Expand Up @@ -724,7 +724,7 @@ export function logout(): void {

PosthogAnalytics.instance.logout();

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

_isLoggingOut = true;
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.get()!;
PlatformPeg.get()?.destroyPickleKey(client.getSafeUserId(), client.getDeviceId() ?? "");
client.logout(true).then(onLoggedOut, (err) => {
// Just throwing an error here is going to be very unhelpful
Expand Down
4 changes: 2 additions & 2 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export interface IMatrixClientPeg {
*/
getHomeserverName(): string | null;

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

public get(): MatrixClient {
public get(): MatrixClient | null {
return this.matrixClient;
}

Expand Down
10 changes: 5 additions & 5 deletions src/MediaDeviceHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ export default class MediaDeviceHandler extends EventEmitter {
const audioDeviceId = SettingsStore.getValue("webrtc_audioinput");
const videoDeviceId = SettingsStore.getValue("webrtc_videoinput");

await MatrixClientPeg.get().getMediaHandler().setAudioInput(audioDeviceId);
await MatrixClientPeg.get().getMediaHandler().setVideoInput(videoDeviceId);
await MatrixClientPeg.safeGet().getMediaHandler().setAudioInput(audioDeviceId);
await MatrixClientPeg.safeGet().getMediaHandler().setVideoInput(videoDeviceId);

await MediaDeviceHandler.updateAudioSettings();
}

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

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

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

0 comments on commit 9b5b053

Please sign in to comment.