From 27d79458dabe979dc0e5838d89a334659407b5f3 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Tue, 15 Aug 2023 09:43:15 +0100 Subject: [PATCH] Remove dead & duplicated code (#11405) * Remove dead code * Make dead code happier * DRY pickle additional data calculation * Iterate --- src/AddThreepid.ts | 8 +--- src/BasePlatform.ts | 33 ++++++------- src/IdentityAuthClient.tsx | 4 -- src/LegacyCallHandler.tsx | 9 ---- src/PasswordReset.ts | 35 -------------- src/RoomNotifs.ts | 5 +- src/ScalarMessaging.ts | 2 +- .../views/dialogs/FeedbackDialog.tsx | 2 +- src/editor/model.ts | 2 +- src/indexing/BaseEventIndexManager.ts | 7 --- src/integrations/IntegrationManagers.ts | 47 ------------------- src/mjolnir/BanList.ts | 4 -- src/models/Call.ts | 2 +- src/rageshake/submit-rageshake.ts | 2 +- src/sentry.ts | 2 +- src/stores/room-list/RoomListStore.ts | 3 +- src/stores/room-list/SlidingRoomListStore.ts | 2 - src/stores/room-list/algorithms/Algorithm.ts | 4 -- src/stores/widgets/StopGapWidget.ts | 4 -- src/stores/widgets/StopGapWidgetDriver.ts | 2 +- src/utils/WidgetUtils.ts | 39 --------------- src/utils/permalinks/PermalinkConstructor.ts | 4 -- src/utils/permalinks/Permalinks.ts | 5 +- test/utils/SearchInput-test.ts | 2 - test/utils/permalinks/Permalinks-test.ts | 22 +++++++++ 25 files changed, 50 insertions(+), 201 deletions(-) diff --git a/src/AddThreepid.ts b/src/AddThreepid.ts index 88996b259e..bc9958cb6d 100644 --- a/src/AddThreepid.ts +++ b/src/AddThreepid.ts @@ -281,16 +281,15 @@ export default class AddThreepid { ): Promise<[success?: boolean, result?: IAuthData | Error | null] | undefined> { const authClient = new IdentityAuthClient(); - let result: { success: boolean } | MatrixError; if (this.submitUrl) { - result = await this.matrixClient.submitMsisdnTokenOtherUrl( + await this.matrixClient.submitMsisdnTokenOtherUrl( this.submitUrl, this.sessionId!, this.clientSecret, msisdnToken, ); } else if (this.bind) { - result = await this.matrixClient.submitMsisdnToken( + await this.matrixClient.submitMsisdnToken( this.sessionId!, this.clientSecret, msisdnToken, @@ -299,9 +298,6 @@ export default class AddThreepid { } else { throw new UserFriendlyError("The add / bind with MSISDN flow is misconfigured"); } - if (result instanceof Error) { - throw result; - } if (this.bind) { await this.matrixClient.bindThreePid({ diff --git a/src/BasePlatform.ts b/src/BasePlatform.ts index b43ecfcd8b..496c89c181 100644 --- a/src/BasePlatform.ts +++ b/src/BasePlatform.ts @@ -67,7 +67,7 @@ export default abstract class BasePlatform { protected notificationCount = 0; protected errorDidOccur = false; - public constructor() { + protected constructor() { dis.register(this.onAction); this.startUpdateCheck = this.startUpdateCheck.bind(this); } @@ -365,14 +365,7 @@ export default abstract class BasePlatform { return null; } - const additionalData = new Uint8Array(userId.length + deviceId.length + 1); - for (let i = 0; i < userId.length; i++) { - additionalData[i] = userId.charCodeAt(i); - } - additionalData[userId.length] = 124; // "|" - for (let i = 0; i < deviceId.length; i++) { - additionalData[userId.length + 1 + i] = deviceId.charCodeAt(i); - } + const additionalData = this.getPickleAdditionalData(userId, deviceId); try { const key = await crypto.subtle.decrypt( @@ -387,6 +380,18 @@ export default abstract class BasePlatform { } } + private getPickleAdditionalData(userId: string, deviceId: string): Uint8Array { + const additionalData = new Uint8Array(userId.length + deviceId.length + 1); + for (let i = 0; i < userId.length; i++) { + additionalData[i] = userId.charCodeAt(i); + } + additionalData[userId.length] = 124; // "|" + for (let i = 0; i < deviceId.length; i++) { + additionalData[userId.length + 1 + i] = deviceId.charCodeAt(i); + } + return additionalData; + } + /** * Create and store a pickle key for encrypting libolm objects. * @param {string} userId the user ID for the user that the pickle key is for. @@ -408,15 +413,7 @@ export default abstract class BasePlatform { const iv = new Uint8Array(32); crypto.getRandomValues(iv); - const additionalData = new Uint8Array(userId.length + deviceId.length + 1); - for (let i = 0; i < userId.length; i++) { - additionalData[i] = userId.charCodeAt(i); - } - additionalData[userId.length] = 124; // "|" - for (let i = 0; i < deviceId.length; i++) { - additionalData[userId.length + 1 + i] = deviceId.charCodeAt(i); - } - + const additionalData = this.getPickleAdditionalData(userId, deviceId); const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, cryptoKey, randomArray); try { diff --git a/src/IdentityAuthClient.tsx b/src/IdentityAuthClient.tsx index 87909f5277..44f0aaf2e6 100644 --- a/src/IdentityAuthClient.tsx +++ b/src/IdentityAuthClient.tsx @@ -75,10 +75,6 @@ export default class IdentityAuthClient { return window.localStorage.getItem("mx_is_access_token"); } - public hasCredentials(): boolean { - return Boolean(this.accessToken); - } - // Returns a promise that resolves to the access_token string from the IS public async getAccessToken({ check = true } = {}): Promise { if (!this.authEnabled) { diff --git a/src/LegacyCallHandler.tsx b/src/LegacyCallHandler.tsx index 5c9460aa98..18ae6b8b8e 100644 --- a/src/LegacyCallHandler.tsx +++ b/src/LegacyCallHandler.tsx @@ -429,15 +429,6 @@ export default class LegacyCallHandler extends EventEmitter { return this.calls.get(roomId) || null; } - public getAnyActiveCall(): MatrixCall | null { - for (const call of this.calls.values()) { - if (call.state !== CallState.Ended) { - return call; - } - } - return null; - } - public getAllActiveCalls(): MatrixCall[] { const activeCalls: MatrixCall[] = []; diff --git a/src/PasswordReset.ts b/src/PasswordReset.ts index 851aa95df1..1c897f71ac 100644 --- a/src/PasswordReset.ts +++ b/src/PasswordReset.ts @@ -47,41 +47,6 @@ export default class PasswordReset { this.clientSecret = this.client.generateClientSecret(); } - /** - * Attempt to reset the user's password. This will trigger a side-effect of - * sending an email to the provided email address. - * @param {string} emailAddress The email address - * @param {string} newPassword The new password for the account. - * @param {boolean} logoutDevices Should all devices be signed out after the reset? Defaults to `true`. - * @return {Promise} Resolves when the email has been sent. Then call checkEmailLinkClicked(). - */ - public async resetPassword( - emailAddress: string, - newPassword: string, - logoutDevices = true, - ): Promise { - this.password = newPassword; - this.logoutDevices = logoutDevices; - this.sendAttempt++; - - try { - const result = await this.client.requestPasswordEmailToken( - emailAddress, - this.clientSecret, - this.sendAttempt, - ); - this.sessionId = result.sid; - return result; - } catch (err: any) { - if (err.errcode === "M_THREEPID_NOT_FOUND") { - err.message = _t("This email address was not found"); - } else if (err.httpStatus) { - err.message = err.message + ` (Status ${err.httpStatus})`; - } - throw err; - } - } - /** * Request a password reset token. * This will trigger a side-effect of sending an email to the provided email address. diff --git a/src/RoomNotifs.ts b/src/RoomNotifs.ts index c99026ceaa..8eeb0469e5 100644 --- a/src/RoomNotifs.ts +++ b/src/RoomNotifs.ts @@ -256,9 +256,8 @@ export function determineUnreadState( return { symbol: null, count: trueCount, color: NotificationColor.Grey }; } - // We don't have any notified messages, but we might have unread messages. Let's - // find out. - let hasUnread = false; + // We don't have any notified messages, but we might have unread messages. Let's find out. + let hasUnread: boolean; if (threadId) hasUnread = doesRoomOrThreadHaveUnreadMessages(room.getThread(threadId)!); else hasUnread = doesRoomHaveUnreadMessages(room); diff --git a/src/ScalarMessaging.ts b/src/ScalarMessaging.ts index d86bdf970f..2ed51109a7 100644 --- a/src/ScalarMessaging.ts +++ b/src/ScalarMessaging.ts @@ -679,7 +679,7 @@ function canSendEvent(event: MessageEvent, roomId: string): void { } const me = client.credentials.userId!; - let canSend = false; + let canSend: boolean; if (isState) { canSend = room.currentState.maySendStateEvent(evType, me); } else { diff --git a/src/components/views/dialogs/FeedbackDialog.tsx b/src/components/views/dialogs/FeedbackDialog.tsx index 2ed1d967c2..db2d71ceb0 100644 --- a/src/components/views/dialogs/FeedbackDialog.tsx +++ b/src/components/views/dialogs/FeedbackDialog.tsx @@ -117,7 +117,7 @@ const FeedbackDialog: React.FC = (props: IProps) => { return ( diff --git a/src/editor/model.ts b/src/editor/model.ts index 78c749c94e..232971adf0 100644 --- a/src/editor/model.ts +++ b/src/editor/model.ts @@ -461,7 +461,7 @@ export default class EditorModel { */ public transform(callback: ManualTransformCallback): Promise { const pos = callback(); - let acPromise: Promise | null = null; + let acPromise: Promise | null; if (!(pos instanceof Range)) { acPromise = this.setActivePart(pos, true); } else { diff --git a/src/indexing/BaseEventIndexManager.ts b/src/indexing/BaseEventIndexManager.ts index d618d1718a..519312de0b 100644 --- a/src/indexing/BaseEventIndexManager.ts +++ b/src/indexing/BaseEventIndexManager.ts @@ -112,13 +112,6 @@ export default abstract class BaseEventIndexManager { throw new Error("Unimplemented"); } - /** - * Check if our event index is empty. - */ - public indexIsEmpty(): Promise { - throw new Error("Unimplemented"); - } - /** * Check if the room with the given id is already indexed. * diff --git a/src/integrations/IntegrationManagers.ts b/src/integrations/IntegrationManagers.ts index 21a6124951..0ec7d99185 100644 --- a/src/integrations/IntegrationManagers.ts +++ b/src/integrations/IntegrationManagers.ts @@ -26,7 +26,6 @@ import IntegrationsImpossibleDialog from "../components/views/dialogs/Integratio import IntegrationsDisabledDialog from "../components/views/dialogs/IntegrationsDisabledDialog"; import WidgetUtils from "../utils/WidgetUtils"; import { MatrixClientPeg } from "../MatrixClientPeg"; -import { parseUrl } from "../utils/UrlUtils"; const KIND_PREFERENCE = [ // Ordered: first is most preferred, last is least preferred. @@ -179,52 +178,6 @@ export class IntegrationManagers { public showDisabledDialog(): void { Modal.createDialog(IntegrationsDisabledDialog); } - - /** - * Attempts to discover an integration manager using only its name. This will not validate that - * the integration manager is functional - that is the caller's responsibility. - * @param {string} domainName The domain name to look up. - * @returns {Promise} Resolves to an integration manager instance, - * or null if none was found. - */ - public async tryDiscoverManager(domainName: string): Promise { - logger.log("Looking up integration manager via .well-known"); - if (domainName.startsWith("http:") || domainName.startsWith("https:")) { - // trim off the scheme and just use the domain - domainName = parseUrl(domainName).host; - } - - let wkConfig: IClientWellKnown; - try { - const result = await fetch(`https://${domainName}/.well-known/matrix/integrations`); - wkConfig = await result.json(); - } catch (e) { - logger.error(e); - logger.warn("Failed to locate integration manager"); - return null; - } - - if (!wkConfig || !wkConfig["m.integrations_widget"]) { - logger.warn("Missing integrations widget on .well-known response"); - return null; - } - - const widget = wkConfig["m.integrations_widget"]; - if (!widget["url"] || !widget["data"] || !widget["data"]["api_url"]) { - logger.warn("Malformed .well-known response for integrations widget"); - return null; - } - - // All discovered managers are per-user managers - const manager = new IntegrationManagerInstance(Kind.Account, widget["data"]["api_url"], widget["url"]); - logger.log("Got an integration manager (untested)"); - - // We don't test the manager because the caller may need to do extra - // checks or similar with it. For instance, they may need to deal with - // terms of service or want to call something particular. - - return manager; - } } // For debugging diff --git a/src/mjolnir/BanList.ts b/src/mjolnir/BanList.ts index 0d82a4c080..68c15282c1 100644 --- a/src/mjolnir/BanList.ts +++ b/src/mjolnir/BanList.ts @@ -63,10 +63,6 @@ export class BanList { return this._rules.filter((r) => r.kind === RULE_USER); } - public get roomRules(): ListRule[] { - return this._rules.filter((r) => r.kind === RULE_ROOM); - } - public async banEntity(kind: string, entity: string, reason: string): Promise { const type = ruleTypeToStable(kind); if (!type) return; // unknown rule type diff --git a/src/models/Call.ts b/src/models/Call.ts index 724d277f4e..c45bf94925 100644 --- a/src/models/Call.ts +++ b/src/models/Call.ts @@ -157,7 +157,7 @@ export abstract class Call extends TypedEventEmitter { !!(pkCache && (await pkCache.getCrossSigningKeyCache?.("user_signing"))), ), secret_storage_ready: String(await client.isSecretStorageReady()), - secret_storage_key_in_account: String(!!(await secretStorage.hasKey())), + secret_storage_key_in_account: String(await secretStorage.hasKey()), session_backup_key_in_secret_storage: String(!!(await client.isKeyBackupKeyStored())), session_backup_key_cached: String(!!sessionBackupKeyFromCache), session_backup_key_well_formed: String(sessionBackupKeyFromCache instanceof Uint8Array), diff --git a/src/stores/room-list/RoomListStore.ts b/src/stores/room-list/RoomListStore.ts index 562d421962..e35726b338 100644 --- a/src/stores/room-list/RoomListStore.ts +++ b/src/stores/room-list/RoomListStore.ts @@ -577,10 +577,9 @@ export class RoomListStoreClass extends AsyncStoreWithClient implements * @param {IFilterCondition} filter The filter condition to add. */ public async addFilter(filter: IFilterCondition): Promise { - let promise = Promise.resolve(); filter.on(FILTER_CHANGED, this.onPrefilterUpdated); this.prefilterConditions.push(filter); - promise = this.recalculatePrefiltering(); + const promise = this.recalculatePrefiltering(); promise.then(() => this.updateFn.trigger()); } diff --git a/src/stores/room-list/SlidingRoomListStore.ts b/src/stores/room-list/SlidingRoomListStore.ts index 77942f6bb3..af8b4f5990 100644 --- a/src/stores/room-list/SlidingRoomListStore.ts +++ b/src/stores/room-list/SlidingRoomListStore.ts @@ -399,6 +399,4 @@ export class SlidingRoomListStoreClass extends AsyncStoreWithClient impl } protected async onAction(payload: ActionPayload): Promise {} - - protected async onDispatchAsync(payload: ActionPayload): Promise {} } diff --git a/src/stores/room-list/algorithms/Algorithm.ts b/src/stores/room-list/algorithms/Algorithm.ts index c389ee399e..3ae5fcfea3 100644 --- a/src/stores/room-list/algorithms/Algorithm.ts +++ b/src/stores/room-list/algorithms/Algorithm.ts @@ -90,10 +90,6 @@ export class Algorithm extends EventEmitter { return this._stickyRoom ? this._stickyRoom.room : null; } - public get knownRooms(): Room[] { - return this.rooms; - } - public get hasTagSortingMap(): boolean { return !!this.sortAlgorithms; } diff --git a/src/stores/widgets/StopGapWidget.ts b/src/stores/widgets/StopGapWidget.ts index 8187ae2973..b22437fcb6 100644 --- a/src/stores/widgets/StopGapWidget.ts +++ b/src/stores/widgets/StopGapWidget.ts @@ -242,10 +242,6 @@ export class StopGapWidget extends EventEmitter { return parsed.toString().replace(/%24/g, "$"); } - public get isManagedByManager(): boolean { - return !!this.scalarToken; - } - public get started(): boolean { return !!this.messaging; } diff --git a/src/stores/widgets/StopGapWidgetDriver.ts b/src/stores/widgets/StopGapWidgetDriver.ts index df82dfe43e..8ae9196241 100644 --- a/src/stores/widgets/StopGapWidgetDriver.ts +++ b/src/stores/widgets/StopGapWidgetDriver.ts @@ -245,7 +245,7 @@ export class StopGapWidgetDriver extends WidgetDriver { if (!client || !roomId) throw new Error("Not in a room or not attached to a client"); - let r: { event_id: string } | null = null; // eslint-disable-line camelcase + let r: { event_id: string } | null; if (stateKey !== null) { // state event r = await client.sendStateEvent(roomId, eventType, content, stateKey); diff --git a/src/utils/WidgetUtils.ts b/src/utils/WidgetUtils.ts index 688ac59506..42a87507a4 100644 --- a/src/utils/WidgetUtils.ts +++ b/src/utils/WidgetUtils.ts @@ -411,45 +411,6 @@ export default class WidgetUtils { return widgets.filter((w) => w.content?.type === "m.integration_manager"); } - public static getRoomWidgetsOfType(room: Room, type: WidgetType): MatrixEvent[] { - const widgets = WidgetUtils.getRoomWidgets(room) || []; - return widgets.filter((w) => { - const content = w.getContent(); - return content.url && type.matches(content.type); - }); - } - - public static async removeIntegrationManagerWidgets(client: MatrixClient | undefined): Promise { - if (!client) { - throw new Error("User not logged in"); - } - const widgets = client.getAccountData("m.widgets"); - if (!widgets) return; - const userWidgets: Record = widgets.getContent() || {}; - Object.entries(userWidgets).forEach(([key, widget]) => { - if (widget.content && widget.content.type === "m.integration_manager") { - delete userWidgets[key]; - } - }); - await client.setAccountData("m.widgets", userWidgets); - } - - public static addIntegrationManagerWidget( - client: MatrixClient, - name: string, - uiUrl: string, - apiUrl: string, - ): Promise { - return WidgetUtils.setUserWidget( - client, - "integration_manager_" + new Date().getTime(), - WidgetType.INTEGRATION_MANAGER, - uiUrl, - "Integration manager: " + name, - { api_url: apiUrl }, - ); - } - /** * Remove all stickerpicker widgets (stickerpickers are user widgets by nature) * @param client The matrix client of the logged-in user diff --git a/src/utils/permalinks/PermalinkConstructor.ts b/src/utils/permalinks/PermalinkConstructor.ts index 74f7d2d168..4248b97885 100644 --- a/src/utils/permalinks/PermalinkConstructor.ts +++ b/src/utils/permalinks/PermalinkConstructor.ts @@ -69,8 +69,4 @@ export class PermalinkParts { public get primaryEntityId(): string | null { return this.roomIdOrAlias || this.userId; } - - public get sigil(): string { - return this.primaryEntityId?.[0] || "?"; - } } diff --git a/src/utils/permalinks/Permalinks.ts b/src/utils/permalinks/Permalinks.ts index 6f2219e772..1a55b8408e 100644 --- a/src/utils/permalinks/Permalinks.ts +++ b/src/utils/permalinks/Permalinks.ts @@ -114,6 +114,7 @@ export class RoomPermalinkCreator { } public start(): void { + if (this.started) return; this.load(); this.room?.currentState.on(RoomStateEvent.Update, this.onRoomStateUpdate); this.started = true; @@ -128,10 +129,6 @@ export class RoomPermalinkCreator { return this._serverCandidates; } - public isStarted(): boolean { - return this.started; - } - public forEvent(eventId: string): string { return getPermalinkConstructor().forEvent(this.roomId, eventId, this._serverCandidates); } diff --git a/test/utils/SearchInput-test.ts b/test/utils/SearchInput-test.ts index 0f86397362..a2a9f73ee2 100644 --- a/test/utils/SearchInput-test.ts +++ b/test/utils/SearchInput-test.ts @@ -31,7 +31,6 @@ describe("transforming search term", () => { eventId: "", userId: "", viaServers: [], - sigil: "", }); expect(transformSearchTerm(roomLink)).toBe(parsedPermalink); @@ -46,7 +45,6 @@ describe("transforming search term", () => { eventId: null, userId: null, viaServers: null, - sigil: "?", }); expect(transformSearchTerm(searchTerm)).toBe(searchTerm); diff --git a/test/utils/permalinks/Permalinks-test.ts b/test/utils/permalinks/Permalinks-test.ts index 6f885a8121..8e85aac02c 100644 --- a/test/utils/permalinks/Permalinks-test.ts +++ b/test/utils/permalinks/Permalinks-test.ts @@ -12,6 +12,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ + +import { EventEmitter } from "events"; import { Room, RoomMember, EventType, MatrixEvent } from "matrix-js-sdk/src/matrix"; import { MatrixClientPeg } from "../../../src/MatrixClientPeg"; @@ -87,6 +89,26 @@ describe("Permalinks", function () { jest.spyOn(MatrixClientPeg, "get").mockRestore(); }); + it("should not clean up listeners even if start was called multiple times", () => { + const room = mockRoom("!fake:example.org", []); + const getListenerCount = (emitter: EventEmitter) => + emitter + .eventNames() + .map((e) => emitter.listenerCount(e)) + .reduce((a, b) => a + b, 0); + const listenerCountBefore = getListenerCount(room.currentState); + + const creator = new RoomPermalinkCreator(room); + creator.start(); + creator.start(); + creator.start(); + creator.start(); + expect(getListenerCount(room.currentState)).toBeGreaterThan(listenerCountBefore); + + creator.stop(); + expect(getListenerCount(room.currentState)).toBe(listenerCountBefore); + }); + it("should pick no candidate servers when the room has no members", function () { const room = mockRoom("!fake:example.org", []); const creator = new RoomPermalinkCreator(room);