diff --git a/src/AsyncWrapper.tsx b/src/AsyncWrapper.tsx index ef8924add8..68e33e02fe 100644 --- a/src/AsyncWrapper.tsx +++ b/src/AsyncWrapper.tsx @@ -20,6 +20,8 @@ import * as sdk from './index'; import { _t } from './languageHandler'; import { IDialogProps } from "./components/views/dialogs/IDialogProps"; +import { logger } from "matrix-js-sdk/src/logger"; + type AsyncImport = { default: T }; interface IProps extends IDialogProps { @@ -47,7 +49,7 @@ export default class AsyncWrapper extends React.Component { componentDidMount() { // XXX: temporary logging to try to diagnose // https://github.com/vector-im/element-web/issues/3148 - console.log('Starting load of AsyncWrapper for modal'); + logger.log('Starting load of AsyncWrapper for modal'); this.props.prom.then((result) => { if (this.unmounted) return; diff --git a/src/CallHandler.tsx b/src/CallHandler.tsx index fe938c9929..bc9ccc4bcd 100644 --- a/src/CallHandler.tsx +++ b/src/CallHandler.tsx @@ -286,9 +286,9 @@ export default class CallHandler extends EventEmitter { dis.dispatch({ action: Action.VirtualRoomSupportUpdated }); } catch (e) { if (maxTries === 1) { - console.log("Failed to check for protocol support and no retries remain: assuming no support", e); + logger.log("Failed to check for protocol support and no retries remain: assuming no support", e); } else { - console.log("Failed to check for protocol support: will retry", e); + logger.log("Failed to check for protocol support: will retry", e); this.pstnSupportCheckTimer = setTimeout(() => { this.checkProtocols(maxTries - 1); }, 10000); @@ -399,7 +399,7 @@ export default class CallHandler extends EventEmitter { // or chrome doesn't think so and is denying the request. Not sure what // we can really do here... // https://github.com/vector-im/element-web/issues/7657 - console.log("Unable to play audio clip", e); + logger.log("Unable to play audio clip", e); } }; if (this.audioPromises.has(audioId)) { @@ -477,7 +477,7 @@ export default class CallHandler extends EventEmitter { call.on(CallEvent.Replaced, (newCall: MatrixCall) => { if (!this.matchesCallForThisRoom(call)) return; - console.log(`Call ID ${call.callId} is being replaced by call ID ${newCall.callId}`); + logger.log(`Call ID ${call.callId} is being replaced by call ID ${newCall.callId}`); if (call.state === CallState.Ringing) { this.pause(AudioID.Ring); @@ -493,7 +493,7 @@ export default class CallHandler extends EventEmitter { call.on(CallEvent.AssertedIdentityChanged, async () => { if (!this.matchesCallForThisRoom(call)) return; - console.log(`Call ID ${call.callId} got new asserted identity:`, call.getRemoteAssertedIdentity()); + logger.log(`Call ID ${call.callId} got new asserted identity:`, call.getRemoteAssertedIdentity()); const newAssertedIdentity = call.getRemoteAssertedIdentity().id; let newNativeAssertedIdentity = newAssertedIdentity; @@ -503,7 +503,7 @@ export default class CallHandler extends EventEmitter { newNativeAssertedIdentity = response[0].userid; } } - console.log(`Asserted identity ${newAssertedIdentity} mapped to ${newNativeAssertedIdentity}`); + logger.log(`Asserted identity ${newAssertedIdentity} mapped to ${newNativeAssertedIdentity}`); if (newNativeAssertedIdentity) { this.assertedIdentityNativeUsers[call.callId] = newNativeAssertedIdentity; @@ -516,11 +516,11 @@ export default class CallHandler extends EventEmitter { await ensureDMExists(MatrixClientPeg.get(), newNativeAssertedIdentity); const newMappedRoomId = this.roomIdForCall(call); - console.log(`Old room ID: ${mappedRoomId}, new room ID: ${newMappedRoomId}`); + logger.log(`Old room ID: ${mappedRoomId}, new room ID: ${newMappedRoomId}`); if (newMappedRoomId !== mappedRoomId) { this.removeCallForRoom(mappedRoomId); mappedRoomId = newMappedRoomId; - console.log("Moving call to room " + mappedRoomId); + logger.log("Moving call to room " + mappedRoomId); this.addCallForRoom(mappedRoomId, call, true); } } @@ -656,7 +656,7 @@ export default class CallHandler extends EventEmitter { private setCallState(call: MatrixCall, status: CallState) { const mappedRoomId = CallHandler.sharedInstance().roomIdForCall(call); - console.log( + logger.log( `Call state in ${mappedRoomId} changed to ${status}`, ); @@ -681,7 +681,7 @@ export default class CallHandler extends EventEmitter { } private removeCallForRoom(roomId: string) { - console.log("Removing call for room ", roomId); + logger.log("Removing call for room ", roomId); this.calls.delete(roomId); this.emit(CallHandlerEvent.CallsChanged, this.calls); } @@ -752,7 +752,7 @@ export default class CallHandler extends EventEmitter { logger.debug("Mapped real room " + roomId + " to room ID " + mappedRoomId); const timeUntilTurnCresExpire = MatrixClientPeg.get().getTurnServersExpiry() - Date.now(); - console.log("Current turn creds expire in " + timeUntilTurnCresExpire + " ms"); + logger.log("Current turn creds expire in " + timeUntilTurnCresExpire + " ms"); const call = MatrixClientPeg.get().createCall(mappedRoomId); try { @@ -862,7 +862,7 @@ export default class CallHandler extends EventEmitter { const mappedRoomId = CallHandler.sharedInstance().roomIdForCall(call); if (this.getCallForRoom(mappedRoomId)) { - console.log( + logger.log( "Got incoming call for room " + mappedRoomId + " but there's already a call for this room: ignoring", ); @@ -966,7 +966,7 @@ export default class CallHandler extends EventEmitter { const nativeLookupResults = await this.sipNativeLookup(userId); const lookupSuccess = nativeLookupResults.length > 0 && nativeLookupResults[0].fields.lookup_success; nativeUserId = lookupSuccess ? nativeLookupResults[0].userid : userId; - console.log("Looked up " + number + " to " + userId + " and mapped to native user " + nativeUserId); + logger.log("Looked up " + number + " to " + userId + " and mapped to native user " + nativeUserId); } else { nativeUserId = userId; } @@ -1014,7 +1014,7 @@ export default class CallHandler extends EventEmitter { try { await call.transfer(destination); } catch (e) { - console.log("Failed to transfer call", e); + logger.log("Failed to transfer call", e); Modal.createTrackedDialog('Failed to transfer call', '', ErrorDialog, { title: _t('Transfer Failed'), description: _t('Failed to transfer call'), @@ -1104,7 +1104,7 @@ export default class CallHandler extends EventEmitter { ); WidgetUtils.setRoomWidget(roomId, widgetId, WidgetType.JITSI, widgetUrl, 'Jitsi', widgetData).then(() => { - console.log('Jitsi widget added'); + logger.log('Jitsi widget added'); }).catch((e) => { if (e.errcode === 'M_FORBIDDEN') { Modal.createTrackedDialog('Call Failed', '', ErrorDialog, { @@ -1152,11 +1152,11 @@ export default class CallHandler extends EventEmitter { private addCallForRoom(roomId: string, call: MatrixCall, changedRooms = false): void { if (this.calls.has(roomId)) { - console.log(`Couldn't add call to room ${roomId}: already have a call for this room`); + logger.log(`Couldn't add call to room ${roomId}: already have a call for this room`); throw new Error("Already have a call for room " + roomId); } - console.log("setting call for room " + roomId); + logger.log("setting call for room " + roomId); this.calls.set(roomId, call); // Should we always emit CallsChanged too? diff --git a/src/ContentMessages.tsx b/src/ContentMessages.tsx index 40f8e307a5..60242b373a 100644 --- a/src/ContentMessages.tsx +++ b/src/ContentMessages.tsx @@ -42,6 +42,8 @@ import { BlurhashEncoder } from "./BlurhashEncoder"; import SettingsStore from "./settings/SettingsStore"; import { decorateStartSendingTime, sendRoundTripMetric } from "./sendTimePerformanceMetrics"; +import { logger } from "matrix-js-sdk/src/logger"; + const MAX_WIDTH = 800; const MAX_HEIGHT = 600; @@ -678,13 +680,13 @@ export default class ContentMessages { private ensureMediaConfigFetched(matrixClient: MatrixClient) { if (this.mediaConfig !== null) return; - console.log("[Media Config] Fetching"); + logger.log("[Media Config] Fetching"); return matrixClient.getMediaConfig().then((config) => { - console.log("[Media Config] Fetched config:", config); + logger.log("[Media Config] Fetched config:", config); return config; }).catch(() => { // Media repo can't or won't report limits, so provide an empty object (no limits). - console.log("[Media Config] Could not fetch config, so not limiting uploads."); + logger.log("[Media Config] Could not fetch config, so not limiting uploads."); return {}; }).then((config) => { this.mediaConfig = config; diff --git a/src/CountlyAnalytics.ts b/src/CountlyAnalytics.ts index 72b0462bcd..391bcb0dd6 100644 --- a/src/CountlyAnalytics.ts +++ b/src/CountlyAnalytics.ts @@ -536,7 +536,7 @@ export default class CountlyAnalytics { // sanitize the error from identifiers error = await strReplaceAsync(error, /([!@+#]).+?:[\w:.]+/g, async (substring: string, glyph: string) => { - return glyph + await hashHex(substring.substring(1)); + return glyph + (await hashHex(substring.substring(1))); }); const metrics = this.getMetrics(); diff --git a/src/DeviceListener.ts b/src/DeviceListener.ts index 1a551d7813..f218e6c6a7 100644 --- a/src/DeviceListener.ts +++ b/src/DeviceListener.ts @@ -35,6 +35,8 @@ import { isLoggedIn } from './components/structures/MatrixChat'; import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { ActionPayload } from "./dispatcher/payloads"; +import { logger } from "matrix-js-sdk/src/logger"; + const KEY_BACKUP_POLL_INTERVAL = 5 * 60 * 1000; export default class DeviceListener { @@ -100,7 +102,7 @@ export default class DeviceListener { * @param {String[]} deviceIds List of device IDs to dismiss notifications for */ async dismissUnverifiedSessions(deviceIds: Iterable) { - console.log("Dismissing unverified sessions: " + Array.from(deviceIds).join(',')); + logger.log("Dismissing unverified sessions: " + Array.from(deviceIds).join(',')); for (const d of deviceIds) { this.dismissed.add(d); } @@ -211,7 +213,7 @@ export default class DeviceListener { private async recheck() { const cli = MatrixClientPeg.get(); - if (!await cli.doesServerSupportUnstableFeature("org.matrix.e2e_cross_signing")) return; + if (!(await cli.doesServerSupportUnstableFeature("org.matrix.e2e_cross_signing"))) return; if (!cli.isCryptoEnabled()) return; // don't recheck until the initial sync is complete: lots of account data events will fire @@ -286,8 +288,8 @@ export default class DeviceListener { } } - console.log("Old unverified sessions: " + Array.from(oldUnverifiedDeviceIds).join(',')); - console.log("New unverified sessions: " + Array.from(newUnverifiedDeviceIds).join(',')); + logger.log("Old unverified sessions: " + Array.from(oldUnverifiedDeviceIds).join(',')); + logger.log("New unverified sessions: " + Array.from(newUnverifiedDeviceIds).join(',')); // Display or hide the batch toast for old unverified sessions if (oldUnverifiedDeviceIds.size > 0) { diff --git a/src/IdentityAuthClient.js b/src/IdentityAuthClient.js index ffece510de..54cf3b43e3 100644 --- a/src/IdentityAuthClient.js +++ b/src/IdentityAuthClient.js @@ -29,6 +29,8 @@ import { } from './utils/IdentityServerUtils'; import { abbreviateUrl } from './utils/UrlUtils'; +import { logger } from "matrix-js-sdk/src/logger"; + export class AbortedIdentityActionError extends Error {} export default class IdentityAuthClient { @@ -127,7 +129,7 @@ export default class IdentityAuthClient { await this._matrixClient.getIdentityAccount(token); } catch (e) { if (e.errcode === "M_TERMS_NOT_SIGNED") { - console.log("Identity server requires new terms to be agreed to"); + logger.log("Identity server requires new terms to be agreed to"); await startTermsFlow([new Service( SERVICE_TYPES.IS, identityServerUrl, @@ -141,7 +143,7 @@ export default class IdentityAuthClient { if ( !this.tempClient && !doesAccountDataHaveIdentityServer() && - !await doesIdentityServerHaveTerms(identityServerUrl) + !(await doesIdentityServerHaveTerms(identityServerUrl)) ) { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); const { finished } = Modal.createTrackedDialog('Default identity server terms warning', '', diff --git a/src/Lifecycle.ts b/src/Lifecycle.ts index 5f5aeb389f..57c922aeb7 100644 --- a/src/Lifecycle.ts +++ b/src/Lifecycle.ts @@ -58,6 +58,8 @@ import LazyLoadingDisabledDialog from "./components/views/dialogs/LazyLoadingDis import SessionRestoreErrorDialog from "./components/views/dialogs/SessionRestoreErrorDialog"; import StorageEvictedDialog from "./components/views/dialogs/StorageEvictedDialog"; +import { logger } from "matrix-js-sdk/src/logger"; + const HOMESERVER_URL_KEY = "mx_hs_url"; const ID_SERVER_URL_KEY = "mx_is_url"; @@ -118,7 +120,7 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise fragmentQueryParams.guest_user_id && fragmentQueryParams.guest_access_token ) { - console.log("Using guest access credentials"); + logger.log("Using guest access credentials"); return doSetLoggedIn({ userId: fragmentQueryParams.guest_user_id as string, accessToken: fragmentQueryParams.guest_access_token as string, @@ -204,7 +206,7 @@ export function attemptTokenLogin( initial_device_display_name: defaultDeviceDisplayName, }, ).then(function(creds) { - console.log("Logged in with token"); + logger.log("Logged in with token"); return clearStorage().then(async () => { await persistCredentials(creds); // remember that we just logged in @@ -273,7 +275,7 @@ function registerAsGuest( isUrl: string, defaultDeviceDisplayName: string, ): Promise { - console.log(`Doing guest login on ${hsUrl}`); + logger.log(`Doing guest login on ${hsUrl}`); // create a temporary MatrixClient to do the login const client = createClient({ @@ -285,7 +287,7 @@ function registerAsGuest( initial_device_display_name: defaultDeviceDisplayName, }, }).then((creds) => { - console.log(`Registered as guest: ${creds.user_id}`); + logger.log(`Registered as guest: ${creds.user_id}`); return doSetLoggedIn({ userId: creds.user_id, deviceId: creds.device_id, @@ -411,27 +413,27 @@ export async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }): if (accessToken && userId && hsUrl) { if (ignoreGuest && isGuest) { - console.log("Ignoring stored guest account: " + userId); + logger.log("Ignoring stored guest account: " + userId); return false; } let decryptedAccessToken = accessToken; const pickleKey = await PlatformPeg.get().getPickleKey(userId, deviceId); if (pickleKey) { - console.log("Got pickle key"); + logger.log("Got pickle key"); if (typeof accessToken !== "string") { const encrKey = await pickleKeyToAesKey(pickleKey); decryptedAccessToken = await decryptAES(accessToken, encrKey, "access_token"); encrKey.fill(0); } } else { - console.log("No pickle key available"); + logger.log("No pickle key available"); } const freshLogin = sessionStorage.getItem("mx_fresh_login") === "true"; sessionStorage.removeItem("mx_fresh_login"); - console.log(`Restoring session for ${userId}`); + logger.log(`Restoring session for ${userId}`); await doSetLoggedIn({ userId: userId, deviceId: deviceId, @@ -444,7 +446,7 @@ export async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }): }, false); return true; } else { - console.log("No previous session found."); + logger.log("No previous session found."); return false; } } @@ -488,9 +490,9 @@ export async function setLoggedIn(credentials: IMatrixClientCreds): Promise { - console.log(`Lifecycle: Starting MatrixClient`); + logger.log(`Lifecycle: Starting MatrixClient`); // dispatch this before starting the matrix client: it's used // to add listeners for the 'sync' event so otherwise we'd have diff --git a/src/Login.ts b/src/Login.ts index a8848210be..bb1ab2ef36 100644 --- a/src/Login.ts +++ b/src/Login.ts @@ -21,6 +21,8 @@ import { MatrixClient } from "matrix-js-sdk/src/client"; import { IMatrixClientCreds } from "./MatrixClientPeg"; import SecurityCustomisations from "./customisations/Security"; +import { logger } from "matrix-js-sdk/src/logger"; + interface ILoginOptions { defaultDeviceDisplayName?: string; } @@ -166,7 +168,7 @@ export default class Login { return sendLoginRequest( this.fallbackHsUrl, this.isUrl, 'm.login.password', loginParams, ).catch((fallbackError) => { - console.log("fallback HS login failed", fallbackError); + logger.log("fallback HS login failed", fallbackError); // throw the original error throw originalError; }); @@ -184,7 +186,7 @@ export default class Login { } throw originalLoginError; }).catch((error) => { - console.log("Login failed", error); + logger.log("Login failed", error); throw error; }); } @@ -218,12 +220,12 @@ export async function sendLoginRequest( if (wellknown) { if (wellknown["m.homeserver"] && wellknown["m.homeserver"]["base_url"]) { hsUrl = wellknown["m.homeserver"]["base_url"]; - console.log(`Overrode homeserver setting with ${hsUrl} from login response`); + logger.log(`Overrode homeserver setting with ${hsUrl} from login response`); } if (wellknown["m.identity_server"] && wellknown["m.identity_server"]["base_url"]) { // TODO: should we prompt here? isUrl = wellknown["m.identity_server"]["base_url"]; - console.log(`Overrode IS setting with ${isUrl} from login response`); + logger.log(`Overrode IS setting with ${isUrl} from login response`); } } diff --git a/src/MatrixClientPeg.ts b/src/MatrixClientPeg.ts index 7d0ff560b7..3860a5c133 100644 --- a/src/MatrixClientPeg.ts +++ b/src/MatrixClientPeg.ts @@ -36,6 +36,8 @@ import { crossSigningCallbacks, tryToUnlockSecretStorageWithDehydrationKey } fro import { SHOW_QR_CODE_METHOD } from "matrix-js-sdk/src/crypto/verification/QRCode"; import SecurityCustomisations from "./customisations/Security"; +import { logger } from "matrix-js-sdk/src/logger"; + export interface IMatrixClientCreds { homeserverUrl: string; identityServerUrl: string; @@ -166,7 +168,7 @@ class MatrixClientPegClass implements IMatrixClientPeg { for (const dbType of ['indexeddb', 'memory']) { try { const promise = this.matrixClient.store.startup(); - console.log("MatrixClientPeg: waiting for MatrixClient store to initialise"); + logger.log("MatrixClientPeg: waiting for MatrixClient store to initialise"); await promise; break; } catch (err) { @@ -225,9 +227,9 @@ class MatrixClientPegClass implements IMatrixClientPeg { public async start(): Promise { const opts = await this.assign(); - console.log(`MatrixClientPeg: really starting MatrixClient`); + logger.log(`MatrixClientPeg: really starting MatrixClient`); await this.get().startClient(opts); - console.log(`MatrixClientPeg: MatrixClient started`); + logger.log(`MatrixClientPeg: MatrixClient started`); } public getCredentials(): IMatrixClientCreds { diff --git a/src/Notifier.ts b/src/Notifier.ts index 1137e44aec..81c9bf7f4f 100644 --- a/src/Notifier.ts +++ b/src/Notifier.ts @@ -38,6 +38,8 @@ import UserActivity from "./UserActivity"; import { mediaFromMxc } from "./customisations/Media"; import ErrorDialog from "./components/views/dialogs/ErrorDialog"; +import { logger } from "matrix-js-sdk/src/logger"; + /* * Dispatches: * { @@ -160,7 +162,7 @@ export const Notifier = { _playAudioNotification: async function(ev: MatrixEvent, room: Room) { const sound = this.getSoundForRoom(room.roomId); - console.log(`Got sound ${sound && sound.name || "default"} for ${room.roomId}`); + logger.log(`Got sound ${sound && sound.name || "default"} for ${room.roomId}`); try { const selector = diff --git a/src/PosthogAnalytics.ts b/src/PosthogAnalytics.ts index c6e351b91a..bdc0814b5d 100644 --- a/src/PosthogAnalytics.ts +++ b/src/PosthogAnalytics.ts @@ -21,6 +21,8 @@ import SettingsStore from './settings/SettingsStore'; import { MatrixClientPeg } from "./MatrixClientPeg"; import { MatrixClient } from "matrix-js-sdk/src/client"; +import { logger } from "matrix-js-sdk/src/logger"; + /* Posthog analytics tracking. * * Anonymity behaviour is as follows: @@ -175,7 +177,7 @@ export class PosthogAnalytics { // $redacted_current_url is injected by this class earlier in capture(), as its generation // is async and can't be done in this non-async callback. if (!properties['$redacted_current_url']) { - console.log("$redacted_current_url not set in sanitizeProperties, will drop $current_url entirely"); + logger.log("$redacted_current_url not set in sanitizeProperties, will drop $current_url entirely"); } properties['$current_url'] = properties['$redacted_current_url']; delete properties['$redacted_current_url']; @@ -291,7 +293,7 @@ export class PosthogAnalytics { } catch (e) { // The above could fail due to network requests, but not essential to starting the application, // so swallow it. - console.log("Unable to identify user for tracking" + e.toString()); + logger.log("Unable to identify user for tracking" + e.toString()); } } } diff --git a/src/Resend.ts b/src/Resend.ts index be9fb9550b..0b5c279165 100644 --- a/src/Resend.ts +++ b/src/Resend.ts @@ -20,6 +20,8 @@ import { Room } from 'matrix-js-sdk/src/models/room'; import { MatrixClientPeg } from './MatrixClientPeg'; import dis from './dispatcher/dispatcher'; +import { logger } from "matrix-js-sdk/src/logger"; + export default class Resend { static resendUnsentEvents(room: Room): Promise { return Promise.all(room.getPendingEvents().filter(function(ev: MatrixEvent) { @@ -47,7 +49,7 @@ export default class Resend { }, function(err: Error) { // XXX: temporary logging to try to diagnose // https://github.com/vector-im/element-web/issues/3148 - console.log('Resend got send failure: ' + err.name + '(' + err + ')'); + logger.log('Resend got send failure: ' + err.name + '(' + err + ')'); }); } diff --git a/src/ScalarAuthClient.ts b/src/ScalarAuthClient.ts index 86dd4b7a0f..e791633c8e 100644 --- a/src/ScalarAuthClient.ts +++ b/src/ScalarAuthClient.ts @@ -25,6 +25,8 @@ import { WidgetType } from "./widgets/WidgetType"; import { SERVICE_TYPES } from "matrix-js-sdk/src/service-types"; import { Room } from "matrix-js-sdk/src/models/room"; +import { logger } from "matrix-js-sdk/src/logger"; + // The version of the integration manager API we're intending to work with const imApiVersion = "1.1"; @@ -136,7 +138,7 @@ export default class ScalarAuthClient { return token; }).catch((e) => { if (e instanceof TermsNotSignedError) { - console.log("Integration manager requires new terms to be agreed to"); + logger.log("Integration manager requires new terms to be agreed to"); // The terms endpoints are new and so live on standard _matrix prefixes, // but IM rest urls are currently configured with paths, so remove the // path from the base URL before passing it to the js-sdk diff --git a/src/ScalarMessaging.js b/src/ScalarMessaging.js index 600241bc06..609ac5c67c 100644 --- a/src/ScalarMessaging.js +++ b/src/ScalarMessaging.js @@ -245,6 +245,8 @@ import { IntegrationManagers } from "./integrations/IntegrationManagers"; import { WidgetType } from "./widgets/WidgetType"; import { objectClone } from "./utils/objects"; +import { logger } from "matrix-js-sdk/src/logger"; + function sendResponse(event, res) { const data = objectClone(event.data); data.response = res; @@ -266,7 +268,7 @@ function sendError(event, msg, nestedError) { } function inviteUser(event, roomId, userId) { - console.log(`Received request to invite ${userId} into room ${roomId}`); + logger.log(`Received request to invite ${userId} into room ${roomId}`); const client = MatrixClientPeg.get(); if (!client) { sendError(event, _t('You need to be logged in.')); @@ -400,7 +402,7 @@ function setPlumbingState(event, roomId, status) { if (typeof status !== 'string') { throw new Error('Plumbing state status should be a string'); } - console.log(`Received request to set plumbing state to status "${status}" in room ${roomId}`); + logger.log(`Received request to set plumbing state to status "${status}" in room ${roomId}`); const client = MatrixClientPeg.get(); if (!client) { sendError(event, _t('You need to be logged in.')); @@ -416,7 +418,7 @@ function setPlumbingState(event, roomId, status) { } function setBotOptions(event, roomId, userId) { - console.log(`Received request to set options for bot ${userId} in room ${roomId}`); + logger.log(`Received request to set options for bot ${userId} in room ${roomId}`); const client = MatrixClientPeg.get(); if (!client) { sendError(event, _t('You need to be logged in.')); @@ -437,7 +439,7 @@ function setBotPower(event, roomId, userId, level) { return; } - console.log(`Received request to set power level to ${level} for bot ${userId} in room ${roomId}.`); + logger.log(`Received request to set power level to ${level} for bot ${userId} in room ${roomId}.`); const client = MatrixClientPeg.get(); if (!client) { sendError(event, _t('You need to be logged in.')); @@ -463,17 +465,17 @@ function setBotPower(event, roomId, userId, level) { } function getMembershipState(event, roomId, userId) { - console.log(`membership_state of ${userId} in room ${roomId} requested.`); + logger.log(`membership_state of ${userId} in room ${roomId} requested.`); returnStateEvent(event, roomId, "m.room.member", userId); } function getJoinRules(event, roomId) { - console.log(`join_rules of ${roomId} requested.`); + logger.log(`join_rules of ${roomId} requested.`); returnStateEvent(event, roomId, "m.room.join_rules", ""); } function botOptions(event, roomId, userId) { - console.log(`bot_options of ${userId} in room ${roomId} requested.`); + logger.log(`bot_options of ${userId} in room ${roomId} requested.`); returnStateEvent(event, roomId, "m.room.bot.options", "_" + userId); } diff --git a/src/SecurityManager.ts b/src/SecurityManager.ts index 370b21b396..925b023584 100644 --- a/src/SecurityManager.ts +++ b/src/SecurityManager.ts @@ -31,6 +31,8 @@ import SettingsStore from "./settings/SettingsStore"; import SecurityCustomisations from "./customisations/Security"; import { DeviceTrustLevel } from 'matrix-js-sdk/src/crypto/CrossSigning'; +import { logger } from "matrix-js-sdk/src/logger"; + // This stores the secret storage private keys in memory for the JS SDK. This is // only meant to act as a cache to avoid prompting the user multiple times // during the same single operation. Use `accessSecretStorage` below to scope a @@ -136,7 +138,7 @@ async function getSecretStorageKey( const keyFromCustomisations = SecurityCustomisations.getSecretStorageKey?.(); if (keyFromCustomisations) { - console.log("Using key from security customisations (secret storage)"); + logger.log("Using key from security customisations (secret storage)"); cacheSecretStorageKey(keyId, keyInfo, keyFromCustomisations); return [keyId, keyFromCustomisations]; } @@ -186,7 +188,7 @@ export async function getDehydrationKey( ): Promise { const keyFromCustomisations = SecurityCustomisations.getSecretStorageKey?.(); if (keyFromCustomisations) { - console.log("Using key from security customisations (dehydration)"); + logger.log("Using key from security customisations (dehydration)"); return keyFromCustomisations; } @@ -248,13 +250,13 @@ async function onSecretRequested( name: string, deviceTrust: DeviceTrustLevel, ): Promise { - console.log("onSecretRequested", userId, deviceId, requestId, name, deviceTrust); + logger.log("onSecretRequested", userId, deviceId, requestId, name, deviceTrust); const client = MatrixClientPeg.get(); if (userId !== client.getUserId()) { return; } if (!deviceTrust || !deviceTrust.isVerified()) { - console.log(`Ignoring secret request from untrusted device ${deviceId}`); + logger.log(`Ignoring secret request from untrusted device ${deviceId}`); return; } if ( @@ -267,7 +269,7 @@ async function onSecretRequested( const keyId = name.replace("m.cross_signing.", ""); const key = await callbacks.getCrossSigningKeyCache(keyId); if (!key) { - console.log( + logger.log( `${keyId} requested by ${deviceId}, but not found in cache`, ); } @@ -275,7 +277,7 @@ async function onSecretRequested( } else if (name === "m.megolm_backup.v1") { const key = await client.crypto.getSessionBackupPrivateKey(); if (!key) { - console.log( + logger.log( `session backup key requested by ${deviceId}, but not found in cache`, ); } @@ -329,7 +331,7 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f const cli = MatrixClientPeg.get(); secretStorageBeingAccessed = true; try { - if (!await cli.hasSecretStorageKey() || forceReset) { + if (!(await cli.hasSecretStorageKey()) || forceReset) { // This dialog calls bootstrap itself after guiding the user through // passphrase creation. const { finished } = Modal.createTrackedDialogAsync('Create Secret Storage dialog', '', @@ -383,12 +385,12 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f if (secretStorageKeyInfo[keyId] && secretStorageKeyInfo[keyId].passphrase) { dehydrationKeyInfo = { passphrase: secretStorageKeyInfo[keyId].passphrase }; } - console.log("Setting dehydration key"); + logger.log("Setting dehydration key"); await cli.setDehydrationKey(secretStorageKeys[keyId], dehydrationKeyInfo, "Backup device"); } else if (!keyId) { console.warn("Not setting dehydration key: no SSSS key found"); } else { - console.log("Not setting dehydration key: feature disabled"); + logger.log("Not setting dehydration key: feature disabled"); } } @@ -416,8 +418,8 @@ export async function tryToUnlockSecretStorageWithDehydrationKey( ): Promise { const key = dehydrationCache.key; let restoringBackup = false; - if (key && await client.isSecretStorageReady()) { - console.log("Trying to set up cross-signing using dehydration key"); + if (key && (await client.isSecretStorageReady())) { + logger.log("Trying to set up cross-signing using dehydration key"); secretStorageBeingAccessed = true; nonInteractive = true; try { diff --git a/src/SlashCommands.tsx b/src/SlashCommands.tsx index 902c82fff8..f3214c4757 100644 --- a/src/SlashCommands.tsx +++ b/src/SlashCommands.tsx @@ -55,6 +55,8 @@ import RoomUpgradeWarningDialog from "./components/views/dialogs/RoomUpgradeWarn import InfoDialog from "./components/views/dialogs/InfoDialog"; import SlashCommandHelpDialog from "./components/views/dialogs/SlashCommandHelpDialog"; +import { logger } from "matrix-js-sdk/src/logger"; + // XXX: workaround for https://github.com/microsoft/TypeScript/issues/31816 interface HTMLInputEvent extends Event { target: HTMLInputElement & EventTarget; @@ -291,7 +293,7 @@ export const Commands = [ const cli = MatrixClientPeg.get(); const ev = cli.getRoom(roomId).currentState.getStateEvents('m.room.member', cli.getUserId()); const content = { - ...ev ? ev.getContent() : { membership: 'join' }, + ...(ev ? ev.getContent() : { membership: 'join' }), displayname: args, }; return success(cli.sendStateEvent(roomId, 'm.room.member', content, cli.getUserId())); @@ -335,7 +337,7 @@ export const Commands = [ if (!url) return; const ev = room.currentState.getStateEvents('m.room.member', userId); const content = { - ...ev ? ev.getContent() : { membership: 'join' }, + ...(ev ? ev.getContent() : { membership: 'join' }), avatar_url: url, }; return cli.sendStateEvent(roomId, 'm.room.member', content, userId); @@ -801,7 +803,7 @@ export const Commands = [ const iframe = embed.childNodes[0] as ChildElement; if (iframe.tagName.toLowerCase() === 'iframe' && iframe.attrs) { const srcAttr = iframe.attrs.find(a => a.name === 'src'); - console.log("Pulling URL out of iframe (embed code)"); + logger.log("Pulling URL out of iframe (embed code)"); widgetUrl = srcAttr.value; } } @@ -821,7 +823,7 @@ export const Commands = [ // Make the widget a Jitsi widget if it looks like a Jitsi widget const jitsiData = Jitsi.getInstance().parsePreferredConferenceUrl(widgetUrl); if (jitsiData) { - console.log("Making /addwidget widget a Jitsi conference"); + logger.log("Making /addwidget widget a Jitsi conference"); type = WidgetType.JITSI; name = "Jitsi Conference"; data = jitsiData; diff --git a/src/Terms.ts b/src/Terms.ts index 351d1c0951..86d006c832 100644 --- a/src/Terms.ts +++ b/src/Terms.ts @@ -21,6 +21,8 @@ import { MatrixClientPeg } from './MatrixClientPeg'; import * as sdk from '.'; import Modal from './Modal'; +import { logger } from "matrix-js-sdk/src/logger"; + export class TermsNotSignedError extends Error {} /** @@ -140,11 +142,11 @@ export async function startTermsFlow( const numAcceptedBeforeAgreement = agreedUrlSet.size; if (unagreedPoliciesAndServicePairs.length > 0) { const newlyAgreedUrls = await interactionCallback(unagreedPoliciesAndServicePairs, [...agreedUrlSet]); - console.log("User has agreed to URLs", newlyAgreedUrls); + logger.log("User has agreed to URLs", newlyAgreedUrls); // Merge with previously agreed URLs newlyAgreedUrls.forEach(url => agreedUrlSet.add(url)); } else { - console.log("User has already agreed to all required policies"); + logger.log("User has already agreed to all required policies"); } // We only ever add to the set of URLs, so if anything has changed then we'd see a different length @@ -188,7 +190,7 @@ export function dialogTermsInteractionCallback( extraClassNames?: string, ): Promise { return new Promise((resolve, reject) => { - console.log("Terms that need agreement", policiesAndServicePairs); + logger.log("Terms that need agreement", policiesAndServicePairs); // FIXME: Using an import will result in test failures const TermsDialog = sdk.getComponent("views.dialogs.TermsDialog"); diff --git a/src/VoipUserMapper.ts b/src/VoipUserMapper.ts index dacb4262bd..e2e590548e 100644 --- a/src/VoipUserMapper.ts +++ b/src/VoipUserMapper.ts @@ -20,6 +20,8 @@ import DMRoomMap from "./utils/DMRoomMap"; import CallHandler, { VIRTUAL_ROOM_EVENT_TYPE } from './CallHandler'; import { Room } from 'matrix-js-sdk/src/models/room'; +import { logger } from "matrix-js-sdk/src/logger"; + // Functions for mapping virtual users & rooms. Currently the only lookup // is sip virtual: there could be others in the future. @@ -59,7 +61,7 @@ export default class VoipUserMapper { public nativeRoomForVirtualRoom(roomId: string): string { const cachedNativeRoomId = this.virtualToNativeRoomIdCache.get(roomId); if (cachedNativeRoomId) { - console.log( + logger.log( "Returning native room ID " + cachedNativeRoomId + " for virtual room ID " + roomId + " from cache", ); return cachedNativeRoomId; @@ -98,7 +100,7 @@ export default class VoipUserMapper { if (!CallHandler.sharedInstance().getSupportsVirtualRooms()) return; const inviterId = invitedRoom.getDMInviter(); - console.log(`Checking virtual-ness of room ID ${invitedRoom.roomId}, invited by ${inviterId}`); + logger.log(`Checking virtual-ness of room ID ${invitedRoom.roomId}, invited by ${inviterId}`); const result = await CallHandler.sharedInstance().sipNativeLookup(inviterId); if (result.length === 0) { return; diff --git a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js index 641df4f897..5fbc97d2f1 100644 --- a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js +++ b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.js @@ -34,6 +34,8 @@ import RestoreKeyBackupDialog from "../../../../components/views/dialogs/securit import { getSecureBackupSetupMethods, isSecureBackupRequired } from '../../../../utils/WellKnownUtils'; import SecurityCustomisations from "../../../../customisations/Security"; +import { logger } from "matrix-js-sdk/src/logger"; + const PHASE_LOADING = 0; const PHASE_LOADERROR = 1; const PHASE_CHOOSE_KEY_PASSPHRASE = 2; @@ -122,7 +124,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent { _getInitialPhase() { const keyFromCustomisations = SecurityCustomisations.createSecretStorageKey?.(); if (keyFromCustomisations) { - console.log("Created key via customisations, jumping to bootstrap step"); + logger.log("Created key via customisations, jumping to bootstrap step"); this._recoveryKey = { privateKey: keyFromCustomisations, }; @@ -138,7 +140,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent { const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupSigStatus = ( // we may not have started crypto yet, in which case we definitely don't trust the backup - MatrixClientPeg.get().isCryptoEnabled() && await MatrixClientPeg.get().isKeyBackupTrusted(backupInfo) + MatrixClientPeg.get().isCryptoEnabled() && (await MatrixClientPeg.get().isKeyBackupTrusted(backupInfo)) ); const { forceReset } = this.props; @@ -165,10 +167,10 @@ export default class CreateSecretStorageDialog extends React.PureComponent { // We should never get here: the server should always require // UI auth to upload device signing keys. If we do, we upload // no keys which would be a no-op. - console.log("uploadDeviceSigningKeys unexpectedly succeeded without UI auth!"); + logger.log("uploadDeviceSigningKeys unexpectedly succeeded without UI auth!"); } catch (error) { if (!error.data || !error.data.flows) { - console.log("uploadDeviceSigningKeys advertised no flows!"); + logger.log("uploadDeviceSigningKeys advertised no flows!"); return; } const canUploadKeysWithPasswordOnly = error.data.flows.some(f => { @@ -304,7 +306,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent { try { if (forceReset) { - console.log("Forcing secret storage reset"); + logger.log("Forcing secret storage reset"); await cli.bootstrapSecretStorage({ createSecretStorageKey: async () => this._recoveryKey, setupNewKeyBackup: true, diff --git a/src/audio/Playback.ts b/src/audio/Playback.ts index 03f3bad760..9ad4c85df5 100644 --- a/src/audio/Playback.ts +++ b/src/audio/Playback.ts @@ -23,6 +23,8 @@ import { PlaybackClock } from "./PlaybackClock"; import { createAudioContext, decodeOgg } from "./compat"; import { clamp } from "../utils/numbers"; +import { logger } from "matrix-js-sdk/src/logger"; + export enum PlaybackState { Decoding = "decoding", Stopped = "stopped", // no progress on timeline @@ -139,7 +141,7 @@ export class Playback extends EventEmitter implements IDestroyable { // audio buffer in memory, as that can balloon to far greater than the input buffer's // byte length. if (this.buf.byteLength > 5 * 1024 * 1024) { // 5mb - console.log("Audio file too large: processing through