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

Commit

Permalink
Conform more code to strict null checking (#10167)
Browse files Browse the repository at this point in the history
* Conform more code to strict null checking

* Delint

* Iterate PR based on feedback
  • Loading branch information
t3chguy authored Feb 16, 2023
1 parent f7bea2c commit 4574c66
Show file tree
Hide file tree
Showing 103 changed files with 518 additions and 496 deletions.
27 changes: 17 additions & 10 deletions src/ContentMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ async function loadImageElement(imageFile: File): Promise<{

// check for hi-dpi PNGs and fudge display resolution as needed.
// this is mainly needed for macOS screencaps
let parsePromise: Promise<boolean>;
let parsePromise = Promise.resolve(false);
if (imageFile.type === "image/png") {
// in practice macOS happens to order the chunks so they fall in
// the first 0x1000 bytes (thanks to a massive ICC header).
Expand All @@ -101,7 +101,7 @@ async function loadImageElement(imageFile: File): Promise<{
const chunks = extractPngChunks(buffer);
for (const chunk of chunks) {
if (chunk.name === "pHYs") {
if (chunk.data.byteLength !== PHYS_HIDPI.length) return;
if (chunk.data.byteLength !== PHYS_HIDPI.length) return false;
return chunk.data.every((val, i) => val === PHYS_HIDPI[i]);
}
}
Expand Down Expand Up @@ -199,10 +199,10 @@ function loadVideoElement(videoFile: File): Promise<HTMLVideoElement> {
reject(e);
};

let dataUrl = ev.target.result as string;
let dataUrl = ev.target?.result as string;
// Chrome chokes on quicktime but likes mp4, and `file.type` is
// read only, so do this horrible hack to unbreak quicktime
if (dataUrl.startsWith("data:video/quicktime;")) {
if (dataUrl?.startsWith("data:video/quicktime;")) {
dataUrl = dataUrl.replace("data:video/quicktime;", "data:video/mp4;");
}

Expand Down Expand Up @@ -258,7 +258,7 @@ function readFileAsArrayBuffer(file: File | Blob): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function (e): void {
resolve(e.target.result as ArrayBuffer);
resolve(e.target?.result as ArrayBuffer);
};
reader.onerror = function (e): void {
reject(e);
Expand Down Expand Up @@ -329,7 +329,7 @@ export async function uploadFile(

export default class ContentMessages {
private inprogress: RoomUpload[] = [];
private mediaConfig: IMediaConfig = null;
private mediaConfig: IMediaConfig | null = null;

public sendStickerContentToRoom(
url: string,
Expand Down Expand Up @@ -377,8 +377,8 @@ export default class ContentMessages {
modal.close();
}

const tooBigFiles = [];
const okFiles = [];
const tooBigFiles: File[] = [];
const okFiles: File[] = [];

for (const file of files) {
if (this.isFileSizeAcceptable(file)) {
Expand Down Expand Up @@ -420,7 +420,14 @@ export default class ContentMessages {
}

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

Expand Down Expand Up @@ -584,7 +591,7 @@ export default class ContentMessages {
}

private ensureMediaConfigFetched(matrixClient: MatrixClient): Promise<void> {
if (this.mediaConfig !== null) return;
if (this.mediaConfig !== null) return Promise.resolve();

logger.log("[Media Config] Fetching");
return matrixClient
Expand Down
12 changes: 6 additions & 6 deletions src/DecryptionFailureTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,23 +138,23 @@ export class DecryptionFailureTracker {
return;
}
if (err) {
this.addDecryptionFailure(new DecryptionFailure(e.getId(), err.code));
this.addDecryptionFailure(new DecryptionFailure(e.getId()!, err.code));
} else {
// Could be an event in the failures, remove it
this.removeDecryptionFailuresForEvent(e);
}
}

public addVisibleEvent(e: MatrixEvent): void {
const eventId = e.getId();
const eventId = e.getId()!;

if (this.trackedEvents.has(eventId)) {
return;
}

this.visibleEvents.add(eventId);
if (this.failures.has(eventId) && !this.visibleFailures.has(eventId)) {
this.visibleFailures.set(eventId, this.failures.get(eventId));
this.visibleFailures.set(eventId, this.failures.get(eventId)!);
}
}

Expand All @@ -172,7 +172,7 @@ export class DecryptionFailureTracker {
}

public removeDecryptionFailuresForEvent(e: MatrixEvent): void {
const eventId = e.getId();
const eventId = e.getId()!;
this.failures.delete(eventId);
this.visibleFailures.delete(eventId);
}
Expand All @@ -193,8 +193,8 @@ export class DecryptionFailureTracker {
* Clear state and stop checking for and tracking failures.
*/
public stop(): void {
clearInterval(this.checkInterval);
clearInterval(this.trackInterval);
if (this.checkInterval) clearInterval(this.checkInterval);
if (this.trackInterval) clearInterval(this.trackInterval);

this.failures = new Map();
this.visibleEvents = new Set();
Expand Down
18 changes: 9 additions & 9 deletions src/DeviceListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { isBulkUnverifiedDeviceReminderSnoozed } from "./utils/device/snoozeBulk
const KEY_BACKUP_POLL_INTERVAL = 5 * 60 * 1000;

export default class DeviceListener {
private dispatcherRef: string;
private dispatcherRef: string | null;
// device IDs for which the user has dismissed the verify toast ('Later')
private dismissed = new Set<string>();
// has the user dismissed any of the various nag toasts to setup encryption on this device?
Expand Down Expand Up @@ -152,7 +152,7 @@ export default class DeviceListener {
private ensureDeviceIdsAtStartPopulated(): void {
if (this.ourDeviceIdsAtStart === null) {
const cli = MatrixClientPeg.get();
this.ourDeviceIdsAtStart = new Set(cli.getStoredDevicesForUser(cli.getUserId()).map((d) => d.deviceId));
this.ourDeviceIdsAtStart = new Set(cli.getStoredDevicesForUser(cli.getUserId()!).map((d) => d.deviceId));
}
}

Expand All @@ -162,15 +162,15 @@ export default class DeviceListener {
// devicesAtStart list to the devices that we see after the fetch.
if (initialFetch) return;

const myUserId = MatrixClientPeg.get().getUserId();
const myUserId = MatrixClientPeg.get().getUserId()!;
if (users.includes(myUserId)) this.ensureDeviceIdsAtStartPopulated();

// No need to do a recheck here: we just need to get a snapshot of our devices
// before we download any new ones.
};

private onDevicesUpdated = (users: string[]): void => {
if (!users.includes(MatrixClientPeg.get().getUserId())) return;
if (!users.includes(MatrixClientPeg.get().getUserId()!)) return;
this.recheck();
};

Expand Down Expand Up @@ -225,7 +225,7 @@ export default class DeviceListener {

// The server doesn't tell us when key backup is set up, so we poll
// & cache the result
private async getKeyBackupInfo(): Promise<IKeyBackupInfo> {
private async getKeyBackupInfo(): Promise<IKeyBackupInfo | null> {
const now = new Date().getTime();
if (!this.keyBackupInfo || this.keyBackupFetchedAt < now - KEY_BACKUP_POLL_INTERVAL) {
this.keyBackupInfo = await MatrixClientPeg.get().getKeyBackupVersion();
Expand Down Expand Up @@ -265,10 +265,10 @@ export default class DeviceListener {
this.checkKeyBackupStatus();
} else if (this.shouldShowSetupEncryptionToast()) {
// make sure our keys are finished downloading
await cli.downloadKeys([cli.getUserId()]);
await cli.downloadKeys([cli.getUserId()!]);
// cross signing isn't enabled - nag to enable it
// There are 3 different toasts for:
if (!cli.getCrossSigningId() && cli.getStoredCrossSigningForUser(cli.getUserId())) {
if (!cli.getCrossSigningId() && cli.getStoredCrossSigningForUser(cli.getUserId()!)) {
// Cross-signing on account but this device doesn't trust the master key (verify this session)
showSetupEncryptionToast(SetupKind.VERIFY_THIS_SESSION);
this.checkKeyBackupStatus();
Expand Down Expand Up @@ -310,13 +310,13 @@ export default class DeviceListener {
// as long as cross-signing isn't ready,
// you can't see or dismiss any device toasts
if (crossSigningReady) {
const devices = cli.getStoredDevicesForUser(cli.getUserId());
const devices = cli.getStoredDevicesForUser(cli.getUserId()!);
for (const device of devices) {
if (device.deviceId === cli.deviceId) continue;

const deviceTrust = await cli.checkDeviceTrust(cli.getUserId()!, device.deviceId!);
if (!deviceTrust.isCrossSigningVerified() && !this.dismissed.has(device.deviceId)) {
if (this.ourDeviceIdsAtStart.has(device.deviceId)) {
if (this.ourDeviceIdsAtStart?.has(device.deviceId)) {
oldUnverifiedDeviceIds.add(device.deviceId);
} else {
newUnverifiedDeviceIds.add(device.deviceId);
Expand Down
6 changes: 3 additions & 3 deletions src/IdentityAuthClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export default class IdentityAuthClient {
window.localStorage.setItem("mx_is_access_token", this.accessToken);
}

private readToken(): string {
private readToken(): string | null {
if (this.tempClient) return null; // temporary client: ignore
return window.localStorage.getItem("mx_is_access_token");
}
Expand All @@ -77,13 +77,13 @@ export default class IdentityAuthClient {
}

// Returns a promise that resolves to the access_token string from the IS
public async getAccessToken({ check = true } = {}): Promise<string> {
public async getAccessToken({ check = true } = {}): Promise<string | null> {
if (!this.authEnabled) {
// The current IS doesn't support authentication
return null;
}

let token = this.accessToken;
let token: string | null = this.accessToken;
if (!token) {
token = this.readToken();
}
Expand Down
30 changes: 15 additions & 15 deletions src/LegacyCallHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export default class LegacyCallHandler extends EventEmitter {
* Gets the user-facing room associated with a call (call.roomId may be the call "virtual room"
* if a voip_mxid_translate_pattern is set in the config)
*/
public roomIdForCall(call: MatrixCall): string {
public roomIdForCall(call?: MatrixCall): string | null {
if (!call) return null;

// check asserted identity: if we're not obeying asserted identity,
Expand All @@ -194,7 +194,7 @@ export default class LegacyCallHandler extends EventEmitter {
}
}

return VoipUserMapper.sharedInstance().nativeRoomForVirtualRoom(call.roomId) || call.roomId;
return VoipUserMapper.sharedInstance().nativeRoomForVirtualRoom(call.roomId) ?? call.roomId ?? null;
}

public start(): void {
Expand Down Expand Up @@ -282,7 +282,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

public unSilenceCall(callId: string): void {
if (this.isForcedSilent) return;
if (this.isForcedSilent()) return;
this.silencedCalls.delete(callId);
this.emit(LegacyCallHandlerEvent.SilencedCallsChanged, this.silencedCalls);
this.play(AudioID.Ring);
Expand Down Expand Up @@ -341,14 +341,14 @@ export default class LegacyCallHandler extends EventEmitter {
}

private shouldObeyAssertedfIdentity(): boolean {
return SdkConfig.getObject("voip")?.get("obey_asserted_identity");
return !!SdkConfig.getObject("voip")?.get("obey_asserted_identity");
}

public getSupportsPstnProtocol(): boolean {
public getSupportsPstnProtocol(): boolean | null {
return this.supportsPstnProtocol;
}

public getSupportsVirtualRooms(): boolean {
public getSupportsVirtualRooms(): boolean | null {
return this.supportsSipNativeVirtual;
}

Expand Down Expand Up @@ -414,7 +414,7 @@ export default class LegacyCallHandler extends EventEmitter {
cli.prepareToEncrypt(cli.getRoom(call.roomId));
};

public getCallById(callId: string): MatrixCall {
public getCallById(callId: string): MatrixCall | null {
for (const call of this.calls.values()) {
if (call.callId === callId) return call;
}
Expand All @@ -435,7 +435,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

public getAllActiveCalls(): MatrixCall[] {
const activeCalls = [];
const activeCalls: MatrixCall[] = [];

for (const call of this.calls.values()) {
if (call.state !== CallState.Ended && call.state !== CallState.Ringing) {
Expand All @@ -446,7 +446,7 @@ export default class LegacyCallHandler extends EventEmitter {
}

public getAllActiveCallsNotInRoom(notInThisRoomId: string): MatrixCall[] {
const callsNotInThatRoom = [];
const callsNotInThatRoom: MatrixCall[] = [];

for (const [roomId, call] of this.calls.entries()) {
if (roomId !== notInThisRoomId && call.state !== CallState.Ended) {
Expand Down Expand Up @@ -547,7 +547,7 @@ export default class LegacyCallHandler extends EventEmitter {
const mappedRoomId = this.roomIdForCall(call);

const callForThisRoom = this.getCallForRoom(mappedRoomId);
return callForThisRoom && call.callId === callForThisRoom.callId;
return !!callForThisRoom && call.callId === callForThisRoom.callId;
}

private setCallListeners(call: MatrixCall): void {
Expand Down Expand Up @@ -610,7 +610,7 @@ export default class LegacyCallHandler extends EventEmitter {
return;
}

const newAssertedIdentity = call.getRemoteAssertedIdentity().id;
const newAssertedIdentity = call.getRemoteAssertedIdentity()?.id;
let newNativeAssertedIdentity = newAssertedIdentity;
if (newAssertedIdentity) {
const response = await this.sipNativeLookup(newAssertedIdentity);
Expand Down Expand Up @@ -642,7 +642,7 @@ export default class LegacyCallHandler extends EventEmitter {
});
}

private onCallStateChanged = (newState: CallState, oldState: CallState, call: MatrixCall): void => {
private onCallStateChanged = (newState: CallState, oldState: CallState | null, call: MatrixCall): void => {
if (!this.matchesCallForThisRoom(call)) return;

const mappedRoomId = this.roomIdForCall(call);
Expand Down Expand Up @@ -830,7 +830,7 @@ export default class LegacyCallHandler extends EventEmitter {
"<code>turn.matrix.org</code>, but this will not be as reliable, and " +
"it will share your IP address with that server. You can also manage " +
"this in Settings.",
null,
undefined,
{ code },
)}
</p>
Expand All @@ -843,7 +843,7 @@ export default class LegacyCallHandler extends EventEmitter {
cli.setFallbackICEServerAllowed(allow);
},
},
null,
undefined,
true,
);
}
Expand Down Expand Up @@ -882,7 +882,7 @@ export default class LegacyCallHandler extends EventEmitter {
title,
description,
},
null,
undefined,
true,
);
}
Expand Down
Loading

0 comments on commit 4574c66

Please sign in to comment.