Globally replace all console.logs via codemod (#6827)

This commit replaces all the `console.log` to `logger.log` via an automated script.
Related: vector-im/element-web#18425
pull/21833/head
Dariusz Niemczyk 2021-09-21 17:48:09 +02:00 committed by GitHub
parent 3a548d4c9c
commit 2d1d42b90e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
81 changed files with 396 additions and 258 deletions

View File

@ -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<T> = { default: T };
interface IProps extends IDialogProps {
@ -47,7 +49,7 @@ export default class AsyncWrapper extends React.Component<IProps, IState> {
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;

View File

@ -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?

View File

@ -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;

View File

@ -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();

View File

@ -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<string>) {
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) {

View File

@ -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', '',

View File

@ -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<boolean>
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<boolean> {
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<Matr
: null;
if (pickleKey) {
console.log("Created pickle key");
logger.log("Created pickle key");
} else {
console.log("Pickle key not created");
logger.log("Pickle key not created");
}
return doSetLoggedIn(Object.assign({}, credentials, { pickleKey }), true);
@ -544,7 +546,7 @@ async function doSetLoggedIn(
const softLogout = isSoftLogout();
console.log(
logger.log(
"setLoggedIn: mxid: " + credentials.userId +
" deviceId: " + credentials.deviceId +
" guest: " + credentials.guest +
@ -689,7 +691,7 @@ async function persistCredentials(credentials: IMatrixClientCreds): Promise<void
SecurityCustomisations.persistCredentials?.(credentials);
console.log(`Session persisted for ${credentials.userId}`);
logger.log(`Session persisted for ${credentials.userId}`);
}
let _isLoggingOut = false;
@ -726,7 +728,7 @@ export function logout(): void {
// token still valid, but we should fix this by having access
// tokens expire (and if you really think you've been compromised,
// change your password).
console.log("Failed to call logout API: token will not be invalidated");
logger.log("Failed to call logout API: token will not be invalidated");
onLoggedOut();
},
);
@ -742,7 +744,7 @@ export function softLogout(): void {
// Dev note: please keep this log line around. It can be useful for track down
// random clients stopping in the middle of the logs.
console.log("Soft logout initiated");
logger.log("Soft logout initiated");
_isLoggingOut = true; // to avoid repeated flags
// Ensure that we dispatch a view change **before** stopping the client so
// so that React components unmount first. This avoids React soft crashes
@ -768,7 +770,7 @@ export function isLoggingOut(): boolean {
* syncing the client.
*/
async function startMatrixClient(startSyncing = true): Promise<void> {
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

View File

@ -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`);
}
}

View File

@ -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<any> {
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 {

View File

@ -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 =

View File

@ -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());
}
}
}

View File

@ -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<void[]> {
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 + ')');
});
}

View File

@ -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

View File

@ -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);
}

View File

@ -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<Uint8Array> {
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<string> {
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<void> {
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 {

View File

@ -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;

View File

@ -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<string[]> {
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");

View File

@ -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;

View File

@ -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,

View File

@ -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 <audio /> element");
logger.log("Audio file too large: processing through <audio /> element");
this.element = document.createElement("AUDIO") as HTMLAudioElement;
const prom = new Promise((resolve, reject) => {
this.element.onloadeddata = () => resolve(null);

View File

@ -21,6 +21,8 @@ import decoderWasmPath from 'opus-recorder/dist/decoderWorker.min.wasm';
import wavEncoderPath from 'opus-recorder/dist/waveWorker.min.js';
import decoderPath from 'opus-recorder/dist/decoderWorker.min.js';
import { logger } from "matrix-js-sdk/src/logger";
export function createAudioContext(opts?: AudioContextOptions): AudioContext {
if (window.AudioContext) {
return new AudioContext(opts);
@ -38,7 +40,7 @@ export function decodeOgg(audioBuffer: ArrayBuffer): Promise<ArrayBuffer> {
// Condensed version of decoder example, using a promise:
// https://github.com/chris-rudmin/opus-recorder/blob/master/example/decoder.html
return new Promise((resolve) => { // no reject because the workers don't seem to have a fail path
console.log("Decoder WASM path: " + decoderWasmPath); // so we use the variable (avoid tree shake)
logger.log("Decoder WASM path: " + decoderWasmPath); // so we use the variable (avoid tree shake)
const typedArray = new Uint8Array(audioBuffer);
const decoderWorker = new Worker(decoderPath);
const wavWorker = new Worker(wavEncoderPath);

View File

@ -110,6 +110,8 @@ import { copyPlaintext } from "../../utils/strings";
import { PosthogAnalytics } from '../../PosthogAnalytics';
import { initSentry } from "../../sentry";
import { logger } from "matrix-js-sdk/src/logger";
/** constants for MatrixChat.state.view */
export enum Views {
// a special initial state which is only used at startup, while we are
@ -893,12 +895,12 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.focusComposer = true;
if (roomInfo.room_alias) {
console.log(
logger.log(
`Switching to room alias ${roomInfo.room_alias} at event ` +
roomInfo.event_id,
);
} else {
console.log(`Switching to room id ${roomInfo.room_id} at event ` +
logger.log(`Switching to room id ${roomInfo.room_id} at event ` +
roomInfo.event_id,
);
}
@ -1407,7 +1409,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// such as when laptops unsleep.
// https://github.com/vector-im/element-web/issues/3307#issuecomment-282895568
cli.setCanResetTimelineCallback((roomId) => {
console.log("Request to reset timeline in room ", roomId, " viewing:", this.state.currentRoomId);
logger.log("Request to reset timeline in room ", roomId, " viewing:", this.state.currentRoomId);
if (roomId !== this.state.currentRoomId) {
// It is safe to remove events from rooms we are not viewing.
return true;

View File

@ -91,6 +91,8 @@ import JumpToBottomButton from "../views/rooms/JumpToBottomButton";
import TopUnreadMessagesBar from "../views/rooms/TopUnreadMessagesBar";
import SpaceStore from "../../stores/SpaceStore";
import { logger } from "matrix-js-sdk/src/logger";
const DEBUG = false;
let debuglog = function(msg: string) {};
@ -98,7 +100,7 @@ const BROWSER_SUPPORTS_SANDBOX = 'sandbox' in document.createElement('iframe');
if (DEBUG) {
// using bind means that we get to keep useful line numbers in the console
debuglog = console.log.bind(console);
debuglog = logger.log.bind(console);
}
interface IProps {
@ -380,7 +382,7 @@ export default class RoomView extends React.Component<IProps, IState> {
}
// Temporary logging to diagnose https://github.com/vector-im/element-web/issues/4307
console.log(
logger.log(
'RVS update:',
newState.roomId,
newState.roomAlias,
@ -1399,7 +1401,7 @@ export default class RoomView extends React.Component<IProps, IState> {
// As per the spec, an all rooms search can create this condition,
// it happens with Seshat but not Synapse.
// It will make the result count not match the displayed count.
console.log("Hiding search result from an unknown room", roomId);
logger.log("Hiding search result from an unknown room", roomId);
continue;
}

View File

@ -21,6 +21,8 @@ import { replaceableComponent } from "../../utils/replaceableComponent";
import { getKeyBindingsManager, RoomAction } from "../../KeyBindingsManager";
import ResizeNotifier from "../../utils/ResizeNotifier";
import { logger } from "matrix-js-sdk/src/logger";
const DEBUG_SCROLL = false;
// The amount of extra scroll distance to allow prior to unfilling.
@ -38,7 +40,7 @@ const PAGE_SIZE = 400;
let debuglog;
if (DEBUG_SCROLL) {
// using bind means that we get to keep useful line numbers in the console
debuglog = console.log.bind(console, "ScrollPanel debuglog:");
debuglog = logger.log.bind(console, "ScrollPanel debuglog:");
} else {
debuglog = function() {};
}

View File

@ -80,6 +80,8 @@ import Spinner from "../views/elements/Spinner";
import GroupAvatar from "../views/avatars/GroupAvatar";
import { useDispatcher } from "../../hooks/useDispatcher";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
space: Room;
justCreatedOpts?: IOpts;
@ -696,7 +698,7 @@ const SpaceSetupPrivateInvite = ({ space, onFinished }) => {
const failedUsers = Object.keys(result.states).filter(a => result.states[a] === "error");
if (failedUsers.length > 0) {
console.log("Failed to invite users to space: ", result);
logger.log("Failed to invite users to space: ", result);
setError(_t("Failed to invite the following users to your space: %(csvUsers)s", {
csvUsers: failedUsers.join(", "),
}));

View File

@ -49,6 +49,8 @@ import EditorStateTransfer from '../../utils/EditorStateTransfer';
import ErrorDialog from '../views/dialogs/ErrorDialog';
import { debounce } from 'lodash';
import { logger } from "matrix-js-sdk/src/logger";
const PAGINATE_SIZE = 20;
const INITIAL_SIZE = 20;
const READ_RECEIPT_INTERVAL_MS = 500;
@ -60,7 +62,7 @@ const DEBUG = false;
let debuglog = function(...s: any[]) {};
if (DEBUG) {
// using bind means that we get to keep useful line numbers in the console
debuglog = console.log.bind(console);
debuglog = logger.log.bind(console);
}
interface IProps {
@ -316,7 +318,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
const differentEventId = newProps.eventId != this.props.eventId;
const differentHighlightedEventId = newProps.highlightedEventId != this.props.highlightedEventId;
if (differentEventId || differentHighlightedEventId) {
console.log("TimelinePanel switching to eventId " + newProps.eventId +
logger.log("TimelinePanel switching to eventId " + newProps.eventId +
" (was " + this.props.eventId + ")");
return this.initTimeline(newProps);
}
@ -1098,7 +1100,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// we're in a setState callback, and we know
// timelineLoading is now false, so render() should have
// mounted the message panel.
console.log("can't initialise scroll state because " +
logger.log("can't initialise scroll state because " +
"messagePanel didn't load");
return;
}

View File

@ -59,6 +59,7 @@ import RoomName from "../views/elements/RoomName";
import { replaceableComponent } from "../../utils/replaceableComponent";
import InlineSpinner from "../views/elements/InlineSpinner";
import TooltipButton from "../views/elements/TooltipButton";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
isMinimized: boolean;
}
@ -239,7 +240,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
// TODO: Archived room view: https://github.com/vector-im/element-web/issues/14038
// Note: You'll need to uncomment the button too.
console.log("TODO: Show archived rooms");
logger.log("TODO: Show archived rooms");
};
private onProvideFeedback = (ev: ButtonEvent) => {

View File

@ -38,6 +38,8 @@ import { replaceableComponent } from "../../../utils/replaceableComponent";
import AuthBody from "../../views/auth/AuthBody";
import AuthHeader from "../../views/auth/AuthHeader";
import { logger } from "matrix-js-sdk/src/logger";
// These are used in several places, and come from the js-sdk's autodiscovery
// stuff. We define them here so that they'll be picked up by i18n.
_td("Invalid homeserver discovery response");
@ -438,7 +440,7 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
// technically the flow can have multiple steps, but no one does this
// for login and loginLogic doesn't support it so we can ignore it.
if (!this.stepRendererMap[flow.type]) {
console.log("Skipping flow", flow, "due to unsupported login type", flow.type);
logger.log("Skipping flow", flow, "due to unsupported login type", flow.type);
return false;
}
return true;

View File

@ -37,6 +37,8 @@ import AuthHeader from "../../views/auth/AuthHeader";
import InteractiveAuth from "../InteractiveAuth";
import Spinner from "../../views/elements/Spinner";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
serverConfig: ValidatedServerConfig;
defaultDeviceDisplayName: string;
@ -215,7 +217,7 @@ export default class Registration extends React.Component<IProps, IState> {
if (!this.state.doingUIAuth) {
await this.makeRegisterRequest(null);
// This should never succeed since we specified no auth object.
console.log("Expecting 401 from register request but got success!");
logger.log("Expecting 401 from register request but got success!");
}
} catch (e) {
if (e.httpStatus === 401) {
@ -239,7 +241,7 @@ export default class Registration extends React.Component<IProps, IState> {
});
}
} else {
console.log("Unable to query for supported registration methods.", e);
logger.log("Unable to query for supported registration methods.", e);
showGenericError(e);
}
}
@ -330,7 +332,7 @@ export default class Registration extends React.Component<IProps, IState> {
// the user had a separate guest session they didn't actually mean to replace.
const [sessionOwner, sessionIsGuest] = await Lifecycle.getStoredSessionOwner();
if (sessionOwner && !sessionIsGuest && sessionOwner !== response.userId) {
console.log(
logger.log(
`Found a session for ${sessionOwner} but ${response.userId} has just registered.`,
);
newState.differentLoggedInUserId = sessionOwner;
@ -366,7 +368,7 @@ export default class Registration extends React.Component<IProps, IState> {
const emailPusher = pushers[i];
emailPusher.data = { brand: this.props.brand };
matrixClient.setPusher(emailPusher).then(() => {
console.log("Set email branding to " + this.props.brand);
logger.log("Set email branding to " + this.props.brand);
}, (error) => {
console.error("Couldn't set email branding: " + error);
});

View File

@ -28,6 +28,8 @@ import Spinner from '../../views/elements/Spinner';
import { IKeyBackupInfo } from "matrix-js-sdk/src/crypto/keybackup";
import { VerificationRequest } from "matrix-js-sdk/src/crypto/verification/request/VerificationRequest";
import { logger } from "matrix-js-sdk/src/logger";
function keyHasPassphrase(keyInfo: ISecretStorageKeyInfo): boolean {
return Boolean(
keyInfo.passphrase &&
@ -231,7 +233,7 @@ export default class SetupEncryptionBody extends React.Component<IProps, IState>
} else if (phase === Phase.Busy || phase === Phase.Loading) {
return <Spinner />;
} else {
console.log(`SetupEncryptionBody: Unknown phase ${phase}`);
logger.log(`SetupEncryptionBody: Unknown phase ${phase}`);
}
}
}

View File

@ -32,6 +32,8 @@ import Spinner from "../../views/elements/Spinner";
import AuthHeader from "../../views/auth/AuthHeader";
import AuthBody from "../../views/auth/AuthBody";
import { logger } from "matrix-js-sdk/src/logger";
const LOGIN_VIEW = {
LOADING: 1,
PASSWORD: 2,
@ -103,7 +105,7 @@ export default class SoftLogout extends React.Component<IProps, IState> {
onFinished: (wipeData) => {
if (!wipeData) return;
console.log("Clearing data from soft-logged-out session");
logger.log("Clearing data from soft-logged-out session");
Lifecycle.logout();
},
});

View File

@ -19,6 +19,8 @@ import { _t } from '../../../languageHandler';
import CountlyAnalytics from "../../../CountlyAnalytics";
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
const DIV_ID = 'mx_recaptcha';
interface ICaptchaFormProps {
@ -60,7 +62,7 @@ export default class CaptchaForm extends React.Component<ICaptchaFormProps, ICap
// already loaded
this.onCaptchaLoaded();
} else {
console.log("Loading recaptcha script...");
logger.log("Loading recaptcha script...");
window.mxOnRecaptchaLoaded = () => { this.onCaptchaLoaded(); };
const scriptTag = document.createElement('script');
scriptTag.setAttribute(
@ -109,7 +111,7 @@ export default class CaptchaForm extends React.Component<ICaptchaFormProps, ICap
}
private onCaptchaLoaded() {
console.log("Loaded recaptcha script.");
logger.log("Loaded recaptcha script.");
try {
this.renderRecaptcha(DIV_ID);
// clear error if re-rendered

View File

@ -29,6 +29,8 @@ import { LocalisedPolicy, Policies } from '../../../Terms';
import Field from '../elements/Field';
import CaptchaForm from "./CaptchaForm";
import { logger } from "matrix-js-sdk/src/logger";
/* This file contains a collection of components which are used by the
* InteractiveAuth to prompt the user to enter the information needed
* for an auth stage. (The intention is that they could also be used for other
@ -555,7 +557,7 @@ export class MsisdnAuthEntry extends React.Component<IMsisdnAuthEntryProps, IMsi
}
} catch (e) {
this.props.fail(e);
console.log("Failed to submit msisdn token");
logger.log("Failed to submit msisdn token");
}
};

View File

@ -125,14 +125,14 @@ const CreateSpaceFromCommunityDialog: React.FC<IProps> = ({ matrixClient: cli, g
setBusy(true);
// require & validate the space name field
if (!await spaceNameField.current.validate({ allowEmpty: false })) {
if (!(await spaceNameField.current.validate({ allowEmpty: false }))) {
setBusy(false);
spaceNameField.current.focus();
spaceNameField.current.validate({ allowEmpty: false, focused: true });
return;
}
// validate the space name alias field but do not require it
if (joinRule === JoinRule.Public && !await spaceAliasField.current.validate({ allowEmpty: true })) {
if (joinRule === JoinRule.Public && !(await spaceAliasField.current.validate({ allowEmpty: true }))) {
setBusy(false);
spaceAliasField.current.focus();
spaceAliasField.current.validate({ allowEmpty: true, focused: true });

View File

@ -64,14 +64,14 @@ const CreateSubspaceDialog: React.FC<IProps> = ({ space, onAddExistingSpaceClick
setBusy(true);
// require & validate the space name field
if (!await spaceNameField.current.validate({ allowEmpty: false })) {
if (!(await spaceNameField.current.validate({ allowEmpty: false }))) {
spaceNameField.current.focus();
spaceNameField.current.validate({ allowEmpty: false, focused: true });
setBusy(false);
return;
}
// validate the space name alias field but do not require it
if (joinRule === JoinRule.Public && !await spaceAliasField.current.validate({ allowEmpty: true })) {
if (joinRule === JoinRule.Public && !(await spaceAliasField.current.validate({ allowEmpty: true }))) {
spaceAliasField.current.focus();
spaceAliasField.current.validate({ allowEmpty: true, focused: true });
setBusy(false);

View File

@ -44,6 +44,8 @@ import { SettingLevel } from '../../../settings/SettingLevel';
import BaseDialog from "./BaseDialog";
import TruncatedList from "../elements/TruncatedList";
import { logger } from "matrix-js-sdk/src/logger";
interface IGenericEditorProps {
onBack: () => void;
}
@ -984,7 +986,7 @@ class SettingsExplorer extends React.PureComponent<IExplorerProps, ISettingsExpl
const parsedExplicit = JSON.parse(this.state.explicitValues);
const parsedExplicitRoom = JSON.parse(this.state.explicitRoomValues);
for (const level of Object.keys(parsedExplicit)) {
console.log(`[Devtools] Setting value of ${settingId} at ${level} from user input`);
logger.log(`[Devtools] Setting value of ${settingId} at ${level} from user input`);
try {
const val = parsedExplicit[level];
await SettingsStore.setValue(settingId, null, level as SettingLevel, val);
@ -994,7 +996,7 @@ class SettingsExplorer extends React.PureComponent<IExplorerProps, ISettingsExpl
}
const roomId = this.props.room.roomId;
for (const level of Object.keys(parsedExplicit)) {
console.log(`[Devtools] Setting value of ${settingId} at ${level} in ${roomId} from user input`);
logger.log(`[Devtools] Setting value of ${settingId} at ${level} in ${roomId} from user input`);
try {
const val = parsedExplicitRoom[level];
await SettingsStore.setValue(settingId, roomId, level as SettingLevel, val);

View File

@ -22,6 +22,8 @@ import { _t } from '../../../languageHandler';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { mediaFromMxc } from "../../../customisations/Media";
import { logger } from "matrix-js-sdk/src/logger";
const PHASE_START = 0;
const PHASE_SHOW_SAS = 1;
const PHASE_WAIT_FOR_PARTNER_TO_CONFIRM = 2;
@ -39,7 +41,7 @@ export default class IncomingSasDialog extends React.Component {
let phase = PHASE_START;
if (this.props.verifier.cancelled) {
console.log("Verifier was cancelled in the background.");
logger.log("Verifier was cancelled in the background.");
phase = PHASE_CANCELLED;
}
@ -90,7 +92,7 @@ export default class IncomingSasDialog extends React.Component {
this.props.verifier.verify().then(() => {
this.setState({ phase: PHASE_VERIFIED });
}).catch((e) => {
console.log("Verification failed", e);
logger.log("Verification failed", e);
});
}

View File

@ -73,6 +73,8 @@ import BaseDialog from "./BaseDialog";
import DialPadBackspaceButton from "../elements/DialPadBackspaceButton";
import SpaceStore from "../../../stores/SpaceStore";
import { logger } from "matrix-js-sdk/src/logger";
// we have a number of types defined from the Matrix spec which can't reasonably be altered here.
/* eslint-disable camelcase */
@ -775,7 +777,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
invitedUsers.push(addr);
}
}
console.log("Sharing history with", invitedUsers);
logger.log("Sharing history with", invitedUsers);
cli.sendSharedHistoryKeys(
this.props.roomId, invitedUsers,
);

View File

@ -25,6 +25,8 @@ import { MatrixClientPeg } from '../../../MatrixClientPeg';
import RestoreKeyBackupDialog from './security/RestoreKeyBackupDialog';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
onFinished: (success: boolean) => void;
}
@ -68,7 +70,7 @@ export default class LogoutDialog extends React.Component<IProps, IState> {
backupInfo,
});
} catch (e) {
console.log("Unable to fetch key backup status", e);
logger.log("Unable to fetch key backup status", e);
this.setState({
loading: false,
error: e,

View File

@ -25,6 +25,8 @@ import { IDialogProps } from "./IDialogProps";
import BaseDialog from "./BaseDialog";
import DialogButtons from "../elements/DialogButtons";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps extends IDialogProps {
widget: Widget;
widgetKind: WidgetKind;
@ -55,7 +57,7 @@ export default class WidgetOpenIDPermissionsDialog extends React.PureComponent<I
private onPermissionSelection(allowed: boolean) {
if (this.state.rememberSelection) {
console.log(`Remembering ${this.props.widget.id} as allowed=${allowed} for OpenID`);
logger.log(`Remembering ${this.props.widget.id} as allowed=${allowed} for OpenID`);
WidgetPermissionStore.instance.setOIDCState(
this.props.widget, this.props.widgetKind, this.props.inRoomId,

View File

@ -28,6 +28,8 @@ import Spinner from '../../elements/Spinner';
import InteractiveAuthDialog from '../InteractiveAuthDialog';
import { replaceableComponent } from "../../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
accountPassword?: string;
tokenLogin?: boolean;
@ -77,10 +79,10 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps
// 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 => {

View File

@ -23,6 +23,8 @@ import { MatrixClient } from 'matrix-js-sdk/src/client';
import { _t } from '../../../../languageHandler';
import { accessSecretStorage } from '../../../../SecurityManager';
import { logger } from "matrix-js-sdk/src/logger";
const RESTORE_TYPE_PASSPHRASE = 0;
const RESTORE_TYPE_RECOVERYKEY = 1;
const RESTORE_TYPE_SECRET_STORAGE = 2;
@ -127,7 +129,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
recoverInfo,
});
} catch (e) {
console.log("Error restoring backup", e);
logger.log("Error restoring backup", e);
this.setState({
loading: false,
restoreError: e,
@ -161,7 +163,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
recoverInfo,
});
} catch (e) {
console.log("Error restoring backup", e);
logger.log("Error restoring backup", e);
this.setState({
loading: false,
restoreError: e,
@ -194,7 +196,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
recoverInfo,
});
} catch (e) {
console.log("Error restoring backup", e);
logger.log("Error restoring backup", e);
this.setState({
restoreError: e,
loading: false,
@ -216,7 +218,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
});
return true;
} catch (e) {
console.log("restoreWithCachedKey failed:", e);
logger.log("restoreWithCachedKey failed:", e);
return false;
}
}
@ -230,7 +232,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
const cli = MatrixClientPeg.get();
const backupInfo = await cli.getKeyBackupVersion();
const has4S = await cli.hasSecretStorageKey();
const backupKeyStored = has4S && await cli.isKeyBackupKeyStored();
const backupKeyStored = has4S && (await cli.isKeyBackupKeyStored());
this.setState({
backupInfo,
backupKeyStored,
@ -238,7 +240,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
const gotCache = await this._restoreWithCachedKey(backupInfo);
if (gotCache) {
console.log("RestoreKeyBackupDialog: found cached backup key");
logger.log("RestoreKeyBackupDialog: found cached backup key");
this.setState({
loading: false,
});
@ -255,7 +257,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent {
loading: false,
});
} catch (e) {
console.log("Error loading backup status", e);
logger.log("Error loading backup status", e);
this.setState({
loadError: e,
loading: false,

View File

@ -86,6 +86,8 @@ interface IState {
widgetPageTitle: string;
}
import { logger } from "matrix-js-sdk/src/logger";
@replaceableComponent("views.elements.AppTile")
export default class AppTile extends React.Component<IProps, IState> {
public static defaultProps: Partial<IProps> = {
@ -115,7 +117,7 @@ export default class AppTile extends React.Component<IProps, IState> {
this.sgWidget.on("preparing", this.onWidgetPrepared);
this.sgWidget.on("ready", this.onWidgetReady);
} catch (e) {
console.log("Failed to construct widget", e);
logger.log("Failed to construct widget", e);
this.sgWidget = null;
}
@ -218,7 +220,7 @@ export default class AppTile extends React.Component<IProps, IState> {
this.sgWidget.on("ready", this.onWidgetReady);
this.startWidget();
} catch (e) {
console.log("Failed to construct widget", e);
logger.log("Failed to construct widget", e);
this.sgWidget = null;
}
}

View File

@ -29,6 +29,8 @@ import { IBodyProps } from "./IBodyProps";
import { FileDownloader } from "../../../utils/FileDownloader";
import TextWithTooltip from "../elements/TextWithTooltip";
import { logger } from "matrix-js-sdk/src/logger";
export let DOWNLOAD_ICON_URL; // cached copy of the download.svg asset for the sandboxed iframe later on
async function cacheDownloadIcon() {
@ -283,7 +285,7 @@ export default class MFileBody extends React.Component<IProps, IState> {
if (["application/pdf"].includes(fileType) && !fileTooBig) {
// We want to force a download on this type, so use an onClick handler.
downloadProps["onClick"] = (e) => {
console.log(`Downloading ${fileType} as blob (unencrypted)`);
logger.log(`Downloading ${fileType} as blob (unencrypted)`);
// Avoid letting the <a> do its thing
e.preventDefault();

View File

@ -27,6 +27,8 @@ import { IMediaEventContent } from "../../../customisations/models/IMediaEventCo
import { IBodyProps } from "./IBodyProps";
import MFileBody from "./MFileBody";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
decryptedUrl?: string;
decryptedThumbnailUrl?: string;
@ -152,7 +154,7 @@ export default class MVideoBody extends React.PureComponent<IBodyProps, IState>
try {
const thumbnailUrl = await this.props.mediaEventHelper.thumbnailUrl.value;
if (autoplay) {
console.log("Preloading video");
logger.log("Preloading video");
this.setState({
decryptedUrl: await this.props.mediaEventHelper.sourceUrl.value,
decryptedThumbnailUrl: thumbnailUrl,
@ -160,7 +162,7 @@ export default class MVideoBody extends React.PureComponent<IBodyProps, IState>
});
this.props.onHeightChanged();
} else {
console.log("NOT preloading video");
logger.log("NOT preloading video");
const content = this.props.mxEvent.getContent<IMediaEventContent>();
this.setState({
// For Chrome and Electron, we need to set some non-empty `src` to

View File

@ -71,6 +71,8 @@ import UIStore from "../../../stores/UIStore";
import { ComposerInsertPayload } from "../../../dispatcher/payloads/ComposerInsertPayload";
import SpaceStore from "../../../stores/SpaceStore";
import { logger } from "matrix-js-sdk/src/logger";
export interface IDevice {
deviceId: string;
ambiguous?: boolean;
@ -557,7 +559,7 @@ const RoomKickButton: React.FC<IBaseProps> = ({ member, startUpdating, stopUpdat
cli.kick(member.roomId, member.userId, reason || undefined).then(() => {
// NO-OP; rely on the m.room.member event coming down else we could
// get out of sync if we force setState here!
console.log("Kick success");
logger.log("Kick success");
}, function(err) {
console.error("Kick error: " + err);
Modal.createTrackedDialog('Failed to kick', '', ErrorDialog, {
@ -684,7 +686,7 @@ const BanToggleButton: React.FC<IBaseProps> = ({ member, startUpdating, stopUpda
promise.then(() => {
// NO-OP; rely on the m.room.member event coming down else we could
// get out of sync if we force setState here!
console.log("Ban success");
logger.log("Ban success");
}, function(err) {
console.error("Ban error: " + err);
Modal.createTrackedDialog('Failed to ban user', '', ErrorDialog, {
@ -757,7 +759,7 @@ const MuteToggleButton: React.FC<IBaseRoomProps> = ({ member, room, powerLevels,
cli.setPowerLevel(roomId, target, level, powerLevelEvent).then(() => {
// NO-OP; rely on the m.room.member event coming down else we could
// get out of sync if we force setState here!
console.log("Mute toggle success");
logger.log("Mute toggle success");
}, function(err) {
console.error("Mute error: " + err);
Modal.createTrackedDialog('Failed to mute user', '', ErrorDialog, {
@ -917,7 +919,7 @@ const GroupAdminToolsSection: React.FC<{
_t('Failed to withdraw invitation') :
_t('Failed to remove user from community'),
});
console.log(e);
logger.log(e);
}).finally(() => {
stopUpdating();
});
@ -1060,7 +1062,7 @@ const PowerLevelEditor: React.FC<{
function() {
// NO-OP; rely on the m.room.member event coming down else we could
// get out of sync if we force setState here!
console.log("Power change success");
logger.log("Power change success");
}, function(err) {
console.error("Failed to change power level " + err);
Modal.createTrackedDialog('Failed to change power level', '', ErrorDialog, {

View File

@ -44,6 +44,8 @@ import { ActionPayload } from "../../../dispatcher/payloads";
import AccessibleButton from '../elements/AccessibleButton';
import SettingsStore from "../../../settings/SettingsStore";
import { logger } from "matrix-js-sdk/src/logger";
function getHtmlReplyFallback(mxEvent: MatrixEvent): string {
const html = mxEvent.getContent().formatted_body;
if (!html) {
@ -308,7 +310,7 @@ export default class EditMessageComposer extends React.Component<IProps, IState>
description: errText,
});
} else {
console.log("Command success.");
logger.log("Command success.");
if (messageContent) return messageContent;
}
}

View File

@ -56,6 +56,8 @@ import QuestionDialog from "../dialogs/QuestionDialog";
import { ActionPayload } from "../../../dispatcher/payloads";
import { decorateStartSendingTime, sendRoundTripMetric } from "../../../sendTimePerformanceMetrics";
import { logger } from "matrix-js-sdk/src/logger";
function addReplyToMessageContent(
content: IContent,
replyToEvent: MatrixEvent,
@ -341,7 +343,7 @@ export default class SendMessageComposer extends React.Component<IProps> {
description: errText,
});
} else {
console.log("Command success.");
logger.log("Command success.");
if (messageContent) return messageContent;
}
}

View File

@ -34,6 +34,8 @@ import ScalarAuthClient from '../../../ScalarAuthClient';
import GenericElementContextMenu from "../context_menus/GenericElementContextMenu";
import { IApp } from "../../../stores/WidgetStore";
import { logger } from "matrix-js-sdk/src/logger";
// This should be below the dialog level (4000), but above the rest of the UI (1000-2000).
// We sit in a context menu, so this should be given to the context menu.
const STICKERPICKER_Z_INDEX = 3500;
@ -99,11 +101,11 @@ export default class Stickerpicker extends React.PureComponent<IProps, IState> {
private removeStickerpickerWidgets = async (): Promise<void> => {
const scalarClient = await this.acquireScalarClient();
console.log('Removing Stickerpicker widgets');
logger.log('Removing Stickerpicker widgets');
if (this.state.widgetId) {
if (scalarClient) {
scalarClient.disableWidgetAssets(WidgetType.STICKERPICKER, this.state.widgetId).then(() => {
console.log('Assets disabled');
logger.log('Assets disabled');
}).catch((err) => {
console.error('Failed to disable assets');
});

View File

@ -97,9 +97,9 @@ export default class CrossSigningPanel extends React.PureComponent<{}, IState> {
const secretStorage = cli.crypto.secretStorage;
const crossSigningPublicKeysOnDevice = Boolean(crossSigning.getId());
const crossSigningPrivateKeysInStorage = Boolean(await crossSigning.isStoredInSecretStorage(secretStorage));
const masterPrivateKeyCached = !!(pkCache && await pkCache.getCrossSigningKeyCache("master"));
const selfSigningPrivateKeyCached = !!(pkCache && await pkCache.getCrossSigningKeyCache("self_signing"));
const userSigningPrivateKeyCached = !!(pkCache && await pkCache.getCrossSigningKeyCache("user_signing"));
const masterPrivateKeyCached = !!(pkCache && (await pkCache.getCrossSigningKeyCache("master")));
const selfSigningPrivateKeyCached = !!(pkCache && (await pkCache.getCrossSigningKeyCache("self_signing")));
const userSigningPrivateKeyCached = !!(pkCache && (await pkCache.getCrossSigningKeyCache("user_signing")));
const homeserverSupportsCrossSigning =
await cli.doesServerSupportUnstableFeature("org.matrix.e2e_cross_signing");
const crossSigningReady = await cli.isCrossSigningReady();

View File

@ -262,7 +262,7 @@ const JoinRuleSettings = ({ room, promptUpgrade, onError, beforeChange, closeSet
}
if (beforeJoinRule === joinRule && !restrictedAllowRoomIds) return;
if (beforeChange && !await beforeChange(joinRule)) return;
if (beforeChange && !(await beforeChange(joinRule))) return;
const newContent: IJoinRuleEventContent = {
join_rule: joinRule,

View File

@ -27,6 +27,8 @@ import { mediaFromMxc } from "../../../customisations/Media";
import AccessibleButton from '../elements/AccessibleButton';
import AvatarSetting from './AvatarSetting';
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
userId?: string;
originalDisplayName?: string;
@ -104,7 +106,7 @@ export default class ProfileSettings extends React.Component<{}, IState> {
}
if (this.state.avatarFile) {
console.log(
logger.log(
`Uploading new avatar, ${this.state.avatarFile.name} of type ${this.state.avatarFile.type},` +
` (${this.state.avatarFile.size}) bytes`);
const uri = await client.uploadContent(this.state.avatarFile);
@ -116,7 +118,7 @@ export default class ProfileSettings extends React.Component<{}, IState> {
await client.setAvatarUrl(""); // use empty string as Synapse 500s on undefined
}
} catch (err) {
console.log("Failed to save profile", err);
logger.log("Failed to save profile", err);
Modal.createTrackedDialog('Failed to save profile', '', ErrorDialog, {
title: _t("Failed to save your profile"),
description: ((err && err.message) ? err.message : _t("The operation could not be completed")),

View File

@ -28,6 +28,8 @@ import RestoreKeyBackupDialog from '../dialogs/security/RestoreKeyBackupDialog';
import { accessSecretStorage } from '../../../SecurityManager';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
@replaceableComponent("views.settings.SecureBackupPanel")
export default class SecureBackupPanel extends React.PureComponent {
constructor(props) {
@ -93,7 +95,7 @@ export default class SecureBackupPanel extends React.PureComponent {
backupSigStatus: trustInfo,
});
} catch (e) {
console.log("Unable to fetch check backup status", e);
logger.log("Unable to fetch check backup status", e);
if (this._unmounted) return;
this.setState({
loading: false,
@ -118,7 +120,7 @@ export default class SecureBackupPanel extends React.PureComponent {
backupSigStatus,
});
} catch (e) {
console.log("Unable to fetch key backup status", e);
logger.log("Unable to fetch key backup status", e);
if (this._unmounted) return;
this.setState({
loading: false,

View File

@ -66,7 +66,7 @@ export class EmailAddress extends React.Component {
}
async changeBinding({ bind, label, errorTitle }) {
if (!await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
if (!(await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}

View File

@ -58,7 +58,7 @@ export class PhoneNumber extends React.Component {
}
async changeBinding({ bind, label, errorTitle }) {
if (!await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
if (!(await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}

View File

@ -32,6 +32,8 @@ import { toRightOf } from "../../../../structures/ContextMenu";
import BugReportDialog from '../../../dialogs/BugReportDialog';
import GenericTextContextMenu from "../../../context_menus/GenericTextContextMenu";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
closeSettingsFn: () => void;
}
@ -88,7 +90,7 @@ export default class HelpUserSettingsTab extends React.Component<IProps, IState>
// Dev note: please keep this log line, it's useful when troubleshooting a MatrixClient suddenly
// stopping in the middle of the logs.
console.log("Clear cache & reload clicked");
logger.log("Clear cache & reload clicked");
MatrixClientPeg.get().stopClient();
MatrixClientPeg.get().store.deleteAllData().then(() => {
PlatformPeg.get().reload();

View File

@ -233,7 +233,7 @@ export default class PreferencesUserSettingsTab extends React.Component<IProps,
const alwaysShowMenuBarSupported = await platform.supportsAutoHideMenuBar();
let alwaysShowMenuBar = true;
if (alwaysShowMenuBarSupported) {
alwaysShowMenuBar = !await platform.getAutoHideMenuBarEnabled();
alwaysShowMenuBar = !(await platform.getAutoHideMenuBarEnabled());
}
const minimizeToTraySupported = await platform.supportsMinimizeToTray();

View File

@ -28,6 +28,8 @@ import { replaceableComponent } from "../../../../../utils/replaceableComponent"
import SettingsFlag from '../../../elements/SettingsFlag';
import ErrorDialog from '../../../dialogs/ErrorDialog';
import { logger } from "matrix-js-sdk/src/logger";
const getDefaultDevice = (devices: Array<Partial<MediaDeviceInfo>>) => {
// Note we're looking for a device with deviceId 'default' but adding a device
// with deviceId == the empty string: this is because Chrome gives us a device
@ -101,7 +103,7 @@ export default class VoiceUserSettingsTab extends React.Component<{}, IState> {
}
}
if (error) {
console.log("Failed to list userMedia devices", error);
logger.log("Failed to list userMedia devices", error);
const brand = SdkConfig.get().brand;
Modal.createTrackedDialog('No media permissions', '', ErrorDialog, {
title: _t('No media permissions'),

View File

@ -30,6 +30,8 @@ import { replaceableComponent } from "../../../utils/replaceableComponent";
import { EventSubscription } from 'fbemitter';
import PictureInPictureDragger from './PictureInPictureDragger';
import { logger } from "matrix-js-sdk/src/logger";
const SHOW_CALL_IN_STATES = [
CallState.Connected,
CallState.InviteSent,
@ -78,7 +80,7 @@ function getPrimarySecondaryCalls(calls: MatrixCall[]): [MatrixCall, MatrixCall[
if (secondaries.length > 1) {
// We should never be in more than two calls so this shouldn't happen
console.log("Found more than 1 secondary call! Other calls will not be shown.");
logger.log("Found more than 1 secondary call! Other calls will not be shown.");
}
return [primary, secondaries];

View File

@ -31,6 +31,8 @@ import SettingsStore from "../settings/SettingsStore";
import { SettingLevel } from "../settings/SettingLevel";
import { ICrawlerCheckpoint, ILoadArgs, ISearchArgs } from "./BaseEventIndexManager";
import { logger } from "matrix-js-sdk/src/logger";
// The time in ms that the crawler will wait loop iterations if there
// have not been any checkpoints to consume in the last iteration.
const CRAWLER_IDLE_TIME = 5000;
@ -54,7 +56,7 @@ export default class EventIndex extends EventEmitter {
const indexManager = PlatformPeg.get().getEventIndexingManager();
this.crawlerCheckpoints = await indexManager.loadCheckpoints();
console.log("EventIndex: Loaded checkpoints", this.crawlerCheckpoints);
logger.log("EventIndex: Loaded checkpoints", this.crawlerCheckpoints);
this.registerListeners();
}
@ -102,7 +104,7 @@ export default class EventIndex extends EventEmitter {
// rooms can use the search provided by the homeserver.
const encryptedRooms = rooms.filter(isRoomEncrypted);
console.log("EventIndex: Adding initial crawler checkpoints");
logger.log("EventIndex: Adding initial crawler checkpoints");
// Gather the prev_batch tokens and create checkpoints for
// our message crawler.
@ -134,7 +136,7 @@ export default class EventIndex extends EventEmitter {
this.crawlerCheckpoints.push(forwardCheckpoint);
}
} catch (e) {
console.log(
logger.log(
"EventIndex: Error adding initial checkpoints for room",
room.roomId,
backCheckpoint,
@ -213,8 +215,8 @@ export default class EventIndex extends EventEmitter {
private onRoomStateEvent = async (ev: MatrixEvent, state: RoomState) => {
if (!MatrixClientPeg.get().isRoomEncrypted(state.roomId)) return;
if (ev.getType() === "m.room.encryption" && !await this.isRoomIndexed(state.roomId)) {
console.log("EventIndex: Adding a checkpoint for a newly encrypted room", state.roomId);
if (ev.getType() === "m.room.encryption" && !(await this.isRoomIndexed(state.roomId))) {
logger.log("EventIndex: Adding a checkpoint for a newly encrypted room", state.roomId);
this.addRoomCheckpoint(state.roomId, true);
}
};
@ -232,7 +234,7 @@ export default class EventIndex extends EventEmitter {
try {
await indexManager.deleteEvent(ev.getAssociatedId());
} catch (e) {
console.log("EventIndex: Error deleting event from index", e);
logger.log("EventIndex: Error deleting event from index", e);
}
};
@ -246,7 +248,7 @@ export default class EventIndex extends EventEmitter {
if (room === null) return;
if (!MatrixClientPeg.get().isRoomEncrypted(room.roomId)) return;
console.log("EventIndex: Adding a checkpoint because of a limited timeline",
logger.log("EventIndex: Adding a checkpoint because of a limited timeline",
room.roomId);
this.addRoomCheckpoint(room.roomId, false);
@ -374,12 +376,12 @@ export default class EventIndex extends EventEmitter {
direction: Direction.Backward,
};
console.log("EventIndex: Adding checkpoint", checkpoint);
logger.log("EventIndex: Adding checkpoint", checkpoint);
try {
await indexManager.addCrawlerCheckpoint(checkpoint);
} catch (e) {
console.log(
logger.log(
"EventIndex: Error adding new checkpoint for room",
room.roomId,
checkpoint,
@ -465,12 +467,12 @@ export default class EventIndex extends EventEmitter {
);
} catch (e) {
if (e.httpStatus === 403) {
console.log("EventIndex: Removing checkpoint as we don't have ",
logger.log("EventIndex: Removing checkpoint as we don't have ",
"permissions to fetch messages from this room.", checkpoint);
try {
await indexManager.removeCrawlerCheckpoint(checkpoint);
} catch (e) {
console.log("EventIndex: Error removing checkpoint", checkpoint, e);
logger.log("EventIndex: Error removing checkpoint", checkpoint, e);
// We don't push the checkpoint here back, it will
// hopefully be removed after a restart. But let us
// ignore it for now as we don't want to hammer the
@ -479,7 +481,7 @@ export default class EventIndex extends EventEmitter {
continue;
}
console.log("EventIndex: Error crawling using checkpoint:", checkpoint, ",", e);
logger.log("EventIndex: Error crawling using checkpoint:", checkpoint, ",", e);
this.crawlerCheckpoints.push(checkpoint);
continue;
}
@ -490,13 +492,13 @@ export default class EventIndex extends EventEmitter {
}
if (res.chunk.length === 0) {
console.log("EventIndex: Done with the checkpoint", checkpoint);
logger.log("EventIndex: Done with the checkpoint", checkpoint);
// We got to the start/end of our timeline, lets just
// delete our checkpoint and go back to sleep.
try {
await indexManager.removeCrawlerCheckpoint(checkpoint);
} catch (e) {
console.log("EventIndex: Error removing checkpoint", checkpoint, e);
logger.log("EventIndex: Error removing checkpoint", checkpoint, e);
}
continue;
}
@ -591,7 +593,7 @@ export default class EventIndex extends EventEmitter {
// We didn't get a valid new checkpoint from the server, nothing
// to do here anymore.
if (!newCheckpoint) {
console.log("EventIndex: The server didn't return a valid ",
logger.log("EventIndex: The server didn't return a valid ",
"new checkpoint, not continuing the crawl.", checkpoint);
continue;
}
@ -601,18 +603,18 @@ export default class EventIndex extends EventEmitter {
// Let us delete the checkpoint in that case, otherwise push
// the new checkpoint to be used by the crawler.
if (eventsAlreadyAdded === true && newCheckpoint.fullCrawl !== true) {
console.log("EventIndex: Checkpoint had already all events",
logger.log("EventIndex: Checkpoint had already all events",
"added, stopping the crawl", checkpoint);
await indexManager.removeCrawlerCheckpoint(newCheckpoint);
} else {
if (eventsAlreadyAdded === true) {
console.log("EventIndex: Checkpoint had already all events",
logger.log("EventIndex: Checkpoint had already all events",
"added, but continuing due to a full crawl", checkpoint);
}
this.crawlerCheckpoints.push(newCheckpoint);
}
} catch (e) {
console.log("EventIndex: Error durring a crawl", e);
logger.log("EventIndex: Error durring a crawl", e);
// An error occurred, put the checkpoint back so we
// can retry.
this.crawlerCheckpoints.push(checkpoint);
@ -712,7 +714,7 @@ export default class EventIndex extends EventEmitter {
try {
events = await indexManager.loadFileEvents(loadArgs);
} catch (e) {
console.log("EventIndex: Error getting file events", e);
logger.log("EventIndex: Error getting file events", e);
return [];
}
@ -820,7 +822,7 @@ export default class EventIndex extends EventEmitter {
ret = true;
}
console.log("EventIndex: Populating file panel with", matrixEvents.length,
logger.log("EventIndex: Populating file panel with", matrixEvents.length,
"events and setting the pagination token to", paginationToken);
timeline.setPaginationToken(paginationToken, EventTimeline.BACKWARDS);

View File

@ -25,6 +25,8 @@ import { MatrixClientPeg } from "../MatrixClientPeg";
import SettingsStore from '../settings/SettingsStore';
import { SettingLevel } from "../settings/SettingLevel";
import { logger } from "matrix-js-sdk/src/logger";
const INDEX_VERSION = 1;
export class EventIndexPeg {
@ -43,19 +45,19 @@ export class EventIndexPeg {
async init() {
const indexManager = PlatformPeg.get().getEventIndexingManager();
if (!indexManager) {
console.log("EventIndex: Platform doesn't support event indexing, not initializing.");
logger.log("EventIndex: Platform doesn't support event indexing, not initializing.");
return false;
}
this._supportIsInstalled = await indexManager.supportsEventIndexing();
if (!this.supportIsInstalled()) {
console.log("EventIndex: Event indexing isn't installed for the platform, not initializing.");
logger.log("EventIndex: Event indexing isn't installed for the platform, not initializing.");
return false;
}
if (!SettingsStore.getValueAt(SettingLevel.DEVICE, 'enableEventIndexing')) {
console.log("EventIndex: Event indexing is disabled, not initializing");
logger.log("EventIndex: Event indexing is disabled, not initializing");
return false;
}
@ -92,10 +94,10 @@ export class EventIndexPeg {
await indexManager.setUserVersion(INDEX_VERSION);
}
console.log("EventIndex: Successfully initialized the event index");
logger.log("EventIndex: Successfully initialized the event index");
await index.init();
} catch (e) {
console.log("EventIndex: Error initializing the event index", e);
logger.log("EventIndex: Error initializing the event index", e);
this.error = e;
return false;
}
@ -174,7 +176,7 @@ export class EventIndexPeg {
if (indexManager !== null) {
await this.unset();
console.log("EventIndex: Deleting event index.");
logger.log("EventIndex: Deleting event index.");
await indexManager.deleteEventIndex();
}
}

View File

@ -30,6 +30,8 @@ import SettingsStore from "../settings/SettingsStore";
import url from 'url';
import { compare } from "../utils/strings";
import { logger } from "matrix-js-sdk/src/logger";
const KIND_PREFERENCE = [
// Ordered: first is most preferred, last is least preferred.
Kind.Account,
@ -86,12 +88,12 @@ export class IntegrationManagers {
}
private setupHomeserverManagers = async (discoveryResponse) => {
console.log("Updating homeserver-configured integration managers...");
logger.log("Updating homeserver-configured integration managers...");
if (discoveryResponse && discoveryResponse['m.integrations']) {
let managers = discoveryResponse['m.integrations']['managers'];
if (!Array.isArray(managers)) managers = []; // make it an array so we can wipe the HS managers
console.log(`Homeserver has ${managers.length} integration managers`);
logger.log(`Homeserver has ${managers.length} integration managers`);
// Clear out any known managers for the homeserver
// TODO: Log out of the scalar clients
@ -109,7 +111,7 @@ export class IntegrationManagers {
this.primaryManager = null; // reset primary
} else {
console.log("Homeserver has no integration managers");
logger.log("Homeserver has no integration managers");
}
};
@ -211,7 +213,7 @@ export class IntegrationManagers {
* or null if none was found.
*/
async tryDiscoverManager(domainName: string): Promise<IntegrationManagerInstance> {
console.log("Looking up integration manager via .well-known");
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 = url.parse(domainName).host;
@ -240,7 +242,7 @@ export class IntegrationManagers {
// All discovered managers are per-user managers
const manager = new IntegrationManagerInstance(Kind.Account, widget["data"]["api_url"], widget["url"]);
console.log("Got an integration manager (untested)");
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

View File

@ -29,6 +29,8 @@ import webpackLangJsonUrl from "$webapp/i18n/languages.json";
import { SettingLevel } from "./settings/SettingLevel";
import { retry } from "./utils/promise";
import { logger } from "matrix-js-sdk/src/logger";
const i18nFolder = 'i18n/';
// Control whether to also return original, untranslated strings
@ -308,7 +310,7 @@ export function replaceByRegexes(text: string, mapping: IVariables | Tags): stri
// However, not showing count is so common that it's not worth logging. And other commonly unused variables
// here, if there are any.
if (regexpString !== '%\\(count\\)s') {
console.log(`Could not find ${regexp} in ${text}`);
logger.log(`Could not find ${regexp} in ${text}`);
}
}
}
@ -361,7 +363,7 @@ export function setLanguage(preferredLangs: string | string[]) {
SettingsStore.setValue("language", null, SettingLevel.DEVICE, langToUse);
// Adds a lot of noise to test runs, so disable logging there.
if (process.env.NODE_ENV !== "test") {
console.log("set language to " + langToUse);
logger.log("set language to " + langToUse);
}
// Set 'en' as fallback language:
@ -518,7 +520,7 @@ function weblateToCounterpart(inTrs: object): object {
async function getLanguageRetry(langPath: string, num = 3): Promise<object> {
return retry(() => getLanguage(langPath), num, e => {
console.log("Failed to load i18n", langPath);
logger.log("Failed to load i18n", langPath);
console.error(e);
return true; // always retry
});

View File

@ -24,6 +24,8 @@ import { SettingLevel } from "../settings/SettingLevel";
import { Preset } from "matrix-js-sdk/src/@types/partials";
import { ActionPayload } from "../dispatcher/payloads";
import { logger } from "matrix-js-sdk/src/logger";
// TODO: Move this and related files to the js-sdk or something once finalized.
export class Mjolnir {
@ -54,7 +56,7 @@ export class Mjolnir {
private onAction = (payload: ActionPayload) => {
if (payload['action'] === 'setup_mjolnir') {
console.log("Setting up Mjolnir: after sync");
logger.log("Setting up Mjolnir: after sync");
this.setup();
}
};
@ -147,7 +149,7 @@ export class Mjolnir {
private updateLists(listRoomIds: string[]) {
if (!MatrixClientPeg.get()) return;
console.log("Updating Mjolnir ban lists to: " + listRoomIds);
logger.log("Updating Mjolnir ban lists to: " + listRoomIds);
this._lists = [];
this._roomIds = listRoomIds || [];
if (!listRoomIds) return;

View File

@ -38,6 +38,8 @@ limitations under the License.
// purge on startup to prevent logs from accumulating.
// the frequency with which we flush to indexeddb
import { logger } from "matrix-js-sdk/src/logger";
const FLUSH_RATE_MS = 30 * 1000;
// the length of log data we keep in indexeddb (and include in the reports)
@ -375,11 +377,11 @@ class IndexedDBLogStore {
}
}
if (removeLogIds.length > 0) {
console.log("Removing logs: ", removeLogIds);
logger.log("Removing logs: ", removeLogIds);
// Don't await this because it's non-fatal if we can't clean up
// logs.
Promise.all(removeLogIds.map((id) => deleteLogs(id))).then(() => {
console.log(`Removed ${removeLogIds.length} old logs.`);
logger.log(`Removed ${removeLogIds.length} old logs.`);
}, (err) => {
console.error(err);
});
@ -465,7 +467,7 @@ export function tryInitStorage() {
return global.mx_rage_initStoragePromise;
}
console.log("Configuring rageshake persistence...");
logger.log("Configuring rageshake persistence...");
// just *accessing* indexedDB throws an exception in firefox with
// indexeddb disabled.

View File

@ -28,6 +28,8 @@ import * as rageshake from './rageshake';
import SettingsStore from "../settings/SettingsStore";
import SdkConfig from "../SdkConfig";
import { logger } from "matrix-js-sdk/src/logger";
interface IOpts {
label?: string;
userText?: string;
@ -63,7 +65,7 @@ async function collectBugReport(opts: IOpts = {}, gzipLogs = true) {
const client = MatrixClientPeg.get();
console.log("Sending bug report.");
logger.log("Sending bug report.");
const body = new FormData();
body.append('text', opts.userText || "User did not supply any additional text.");
@ -98,11 +100,11 @@ async function collectBugReport(opts: IOpts = {}, gzipLogs = true) {
const pkCache = client.getCrossSigningCacheCallbacks();
body.append("cross_signing_master_privkey_cached",
String(!!(pkCache && await pkCache.getCrossSigningKeyCache("master"))));
String(!!(pkCache && (await pkCache.getCrossSigningKeyCache("master")))));
body.append("cross_signing_self_signing_privkey_cached",
String(!!(pkCache && await pkCache.getCrossSigningKeyCache("self_signing"))));
String(!!(pkCache && (await pkCache.getCrossSigningKeyCache("self_signing")))));
body.append("cross_signing_user_signing_privkey_cached",
String(!!(pkCache && await pkCache.getCrossSigningKeyCache("user_signing"))));
String(!!(pkCache && (await pkCache.getCrossSigningKeyCache("user_signing")))));
body.append("secret_storage_ready", String(await client.isSecretStorageReady()));
body.append("secret_storage_key_in_account", String(!!(await secretStorage.hasKey())));

View File

@ -135,9 +135,9 @@ async function getCryptoContext(client: MatrixClient): Promise<CryptoContext> {
"cross_signing_privkey_in_secret_storage": String(
!!(await crossSigning.isStoredInSecretStorage(secretStorage))),
"cross_signing_master_privkey_cached": String(
!!(pkCache && await pkCache.getCrossSigningKeyCache("master"))),
!!(pkCache && (await pkCache.getCrossSigningKeyCache("master")))),
"cross_signing_user_signing_privkey_cached": String(
!!(pkCache && await pkCache.getCrossSigningKeyCache("user_signing"))),
!!(pkCache && (await pkCache.getCrossSigningKeyCache("user_signing")))),
"secret_storage_ready": String(await client.isSecretStorageReady()),
"secret_storage_key_in_account": String(!!(await secretStorage.hasKey())),
"session_backup_key_in_secret_storage": String(!!(await client.isKeyBackupKeyStored())),

View File

@ -32,6 +32,8 @@ import SettingsHandler from "./handlers/SettingsHandler";
import { SettingUpdatedPayload } from "../dispatcher/payloads/SettingUpdatedPayload";
import { Action } from "../dispatcher/actions";
import { logger } from "matrix-js-sdk/src/logger";
const defaultWatchManager = new WatchManager();
// Convert the settings to easier to manage objects for the handlers
@ -527,16 +529,16 @@ export default class SettingsStore {
* @param {string} roomId Optional room ID to test the setting in.
*/
public static debugSetting(realSettingName: string, roomId: string) {
console.log(`--- DEBUG ${realSettingName}`);
logger.log(`--- DEBUG ${realSettingName}`);
// Note: we intentionally use JSON.stringify here to avoid the console masking the
// problem if there's a type representation issue. Also, this way it is guaranteed
// to show up in a rageshake if required.
const def = SETTINGS[realSettingName];
console.log(`--- definition: ${def ? JSON.stringify(def) : '<NOT_FOUND>'}`);
console.log(`--- default level order: ${JSON.stringify(LEVEL_ORDER)}`);
console.log(`--- registered handlers: ${JSON.stringify(Object.keys(LEVEL_HANDLERS))}`);
logger.log(`--- definition: ${def ? JSON.stringify(def) : '<NOT_FOUND>'}`);
logger.log(`--- default level order: ${JSON.stringify(LEVEL_ORDER)}`);
logger.log(`--- registered handlers: ${JSON.stringify(Object.keys(LEVEL_HANDLERS))}`);
const doChecks = (settingName) => {
for (const handlerName of Object.keys(LEVEL_HANDLERS)) {
@ -544,40 +546,40 @@ export default class SettingsStore {
try {
const value = handler.getValue(settingName, roomId);
console.log(`--- ${handlerName}@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
logger.log(`--- ${handlerName}@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- ${handler}@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
logger.log(`--- ${handler}@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
console.error(e);
}
if (roomId) {
try {
const value = handler.getValue(settingName, null);
console.log(`--- ${handlerName}@<no_room> = ${JSON.stringify(value)}`);
logger.log(`--- ${handlerName}@<no_room> = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- ${handler}@<no_room> THREW ERROR: ${e.message}`);
logger.log(`--- ${handler}@<no_room> THREW ERROR: ${e.message}`);
console.error(e);
}
}
}
console.log(`--- calculating as returned by SettingsStore`);
console.log(`--- these might not match if the setting uses a controller - be warned!`);
logger.log(`--- calculating as returned by SettingsStore`);
logger.log(`--- these might not match if the setting uses a controller - be warned!`);
try {
const value = SettingsStore.getValue(settingName, roomId);
console.log(`--- SettingsStore#generic@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
logger.log(`--- SettingsStore#generic@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- SettingsStore#generic@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
logger.log(`--- SettingsStore#generic@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
console.error(e);
}
if (roomId) {
try {
const value = SettingsStore.getValue(settingName, null);
console.log(`--- SettingsStore#generic@<no_room> = ${JSON.stringify(value)}`);
logger.log(`--- SettingsStore#generic@<no_room> = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- SettingsStore#generic@$<no_room> THREW ERROR: ${e.message}`);
logger.log(`--- SettingsStore#generic@$<no_room> THREW ERROR: ${e.message}`);
console.error(e);
}
}
@ -585,18 +587,18 @@ export default class SettingsStore {
for (const level of LEVEL_ORDER) {
try {
const value = SettingsStore.getValueAt(level, settingName, roomId);
console.log(`--- SettingsStore#${level}@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
logger.log(`--- SettingsStore#${level}@${roomId || '<no_room>'} = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- SettingsStore#${level}@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
logger.log(`--- SettingsStore#${level}@${roomId || '<no_room>'} THREW ERROR: ${e.message}`);
console.error(e);
}
if (roomId) {
try {
const value = SettingsStore.getValueAt(level, settingName, null);
console.log(`--- SettingsStore#${level}@<no_room> = ${JSON.stringify(value)}`);
logger.log(`--- SettingsStore#${level}@<no_room> = ${JSON.stringify(value)}`);
} catch (e) {
console.log(`--- SettingsStore#${level}@$<no_room> THREW ERROR: ${e.message}`);
logger.log(`--- SettingsStore#${level}@$<no_room> THREW ERROR: ${e.message}`);
console.error(e);
}
}
@ -606,12 +608,12 @@ export default class SettingsStore {
doChecks(realSettingName);
if (def.invertedSettingName) {
console.log(`--- TESTING INVERTED SETTING NAME`);
console.log(`--- inverted: ${def.invertedSettingName}`);
logger.log(`--- TESTING INVERTED SETTING NAME`);
logger.log(`--- inverted: ${def.invertedSettingName}`);
doChecks(def.invertedSettingName);
}
console.log(`--- END DEBUG`);
logger.log(`--- END DEBUG`);
}
private static getHandler(settingName: string, level: SettingLevel): SettingsHandler {

View File

@ -23,6 +23,8 @@ import { setTheme } from "../../theme";
import { ActionPayload } from '../../dispatcher/payloads';
import { SettingLevel } from "../SettingLevel";
import { logger } from "matrix-js-sdk/src/logger";
export default class ThemeWatcher {
private themeWatchRef: string;
private systemThemeWatchRef: string;
@ -105,7 +107,7 @@ export default class ThemeWatcher {
const systemThemeExplicit = SettingsStore.getValueAt(
SettingLevel.DEVICE, "use_system_theme", null, false, true);
if (systemThemeExplicit) {
console.log("returning explicit system theme");
logger.log("returning explicit system theme");
if (this.preferDark.matches) return 'dark';
if (this.preferLight.matches) return 'light';
}
@ -116,7 +118,7 @@ export default class ThemeWatcher {
const themeExplicit = SettingsStore.getValueAt(
SettingLevel.DEVICE, "theme", null, false, true);
if (themeExplicit) {
console.log("returning explicit theme: " + themeExplicit);
logger.log("returning explicit theme: " + themeExplicit);
return themeExplicit;
}
@ -126,7 +128,7 @@ export default class ThemeWatcher {
if (this.preferDark.matches) return 'dark';
if (this.preferLight.matches) return 'light';
}
console.log("returning theme value");
logger.log("returning theme value");
return SettingsStore.getValue('theme');
}

View File

@ -16,6 +16,8 @@ limitations under the License.
import EventEmitter from 'events';
import { logger } from "matrix-js-sdk/src/logger";
const BULK_REQUEST_DEBOUNCE_MS = 200;
// Does the server support groups? Assume yes until we receive M_UNRECOGNIZED.
@ -186,14 +188,14 @@ class FlairStore extends EventEmitter {
}
// No request yet, start one
console.log('FlairStore: Request group profile of ' + groupId);
logger.log('FlairStore: Request group profile of ' + groupId);
this._groupProfilesPromise[groupId] = matrixClient.getGroupProfile(groupId);
let profile;
try {
profile = await this._groupProfilesPromise[groupId];
} catch (e) {
console.log('FlairStore: Failed to get group profile for ' + groupId, e);
logger.log('FlairStore: Failed to get group profile for ' + groupId, e);
// Don't retry, but allow a retry when the profile is next requested
delete this._groupProfilesPromise[groupId];
return null;
@ -209,7 +211,7 @@ class FlairStore extends EventEmitter {
/// XXX: This is verging on recreating a third "Flux"-looking Store. We really
/// should replace FlairStore with a Flux store and some async actions.
console.log('FlairStore: Emit updateGroupProfile for ' + groupId);
logger.log('FlairStore: Emit updateGroupProfile for ' + groupId);
this.emit('updateGroupProfile');
setTimeout(() => {

View File

@ -31,6 +31,8 @@ import { Action } from "../dispatcher/actions";
import { retry } from "../utils/promise";
import CountlyAnalytics from "../CountlyAnalytics";
import { logger } from "matrix-js-sdk/src/logger";
const NUM_JOIN_RETRY = 5;
const INITIAL_STATE = {
@ -319,7 +321,7 @@ class RoomViewStore extends Store<ActionPayload> {
});
const err = payload.err;
let msg = err.message ? err.message : JSON.stringify(err);
console.log("Failed to join room:", msg);
logger.log("Failed to join room:", msg);
if (err.name === "ConnectionError") {
msg = _t("There was an error joining the room");

View File

@ -23,6 +23,8 @@ import { PHASE_DONE as VERIF_PHASE_DONE } from "matrix-js-sdk/src/crypto/verific
import { MatrixClientPeg } from '../MatrixClientPeg';
import { accessSecretStorage, AccessCancelledError } from '../SecurityManager';
import { logger } from "matrix-js-sdk/src/logger";
export enum Phase {
Loading = 0,
Intro = 1,
@ -153,7 +155,7 @@ export class SetupEncryptionStore extends EventEmitter {
}
} catch (e) {
if (!(e instanceof AccessCancelledError)) {
console.log(e);
logger.log(e);
}
// this will throw if the user hits cancel, so ignore
this.phase = Phase.Intro;

View File

@ -28,6 +28,8 @@ import { WidgetType } from "../widgets/WidgetType";
import { UPDATE_EVENT } from "./AsyncStore";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {}
export interface IApp extends IWidget {
@ -146,7 +148,7 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
ActiveWidgetStore.getRoomId(persistentWidgetId) === room.roomId &&
!roomInfo.widgets.some(w => w.id === persistentWidgetId)
) {
console.log(`Persistent widget ${persistentWidgetId} removed from room ${room.roomId}: destroying.`);
logger.log(`Persistent widget ${persistentWidgetId} removed from room ${room.roomId}: destroying.`);
ActiveWidgetStore.destroyPersistentWidget(persistentWidgetId);
}
}

View File

@ -39,6 +39,8 @@ import SpaceStore from "../SpaceStore";
import { Action } from "../../dispatcher/actions";
import { SettingUpdatedPayload } from "../../dispatcher/payloads/SettingUpdatedPayload";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
tagsEnabled?: boolean;
}
@ -129,7 +131,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
// Update any settings here, as some may have happened before we were logically ready.
// Update any settings here, as some may have happened before we were logically ready.
console.log("Regenerating room lists: Startup");
logger.log("Regenerating room lists: Startup");
await this.readAndCacheSettingsFromStore();
this.regenerateAllLists({ trigger: false });
this.handleRVSUpdate({ trigger: false }); // fake an RVS update to adjust sticky room, if needed
@ -205,7 +207,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
if (payload.action === Action.SettingUpdated) {
const settingUpdatedPayload = payload as SettingUpdatedPayload;
if (this.watchedSettings.includes(settingUpdatedPayload.settingName)) {
console.log("Regenerating room lists: Settings changed");
logger.log("Regenerating room lists: Settings changed");
await this.readAndCacheSettingsFromStore();
this.regenerateAllLists({ trigger: false }); // regenerate the lists now

View File

@ -57,6 +57,8 @@ import { getUserLanguage } from "../../languageHandler";
import { WidgetVariableCustomisations } from "../../customisations/WidgetVariables";
import { arrayFastClone } from "../../utils/arrays";
import { logger } from "matrix-js-sdk/src/logger";
// TODO: Destroy all of this code
interface IAppTileProps {
@ -405,7 +407,7 @@ export class StopGapWidget extends EventEmitter {
public stop(opts = { forceDestroy: false }) {
if (!opts?.forceDestroy && ActiveWidgetStore.getPersistentWidgetId() === this.mockWidget.id) {
console.log("Skipping destroy - persistent widget");
logger.log("Skipping destroy - persistent widget");
return;
}
if (!this.started) return;

View File

@ -20,9 +20,10 @@ limitations under the License.
* author Roel Nieskens, https://pixelambacht.nl
* MIT license
*/
import { logger } from "matrix-js-sdk/src/logger";
function safariVersionCheck(ua: string): boolean {
console.log("Browser is Safari - checking version for COLR support");
logger.log("Browser is Safari - checking version for COLR support");
try {
const safariVersionMatch = ua.match(/Mac OS X ([\d|_]+).*Version\/([\d|.]+).*Safari/);
if (safariVersionMatch) {
@ -32,7 +33,7 @@ function safariVersionCheck(ua: string): boolean {
const safariVersion = safariVersionStr.split(".").map(n => parseInt(n, 10));
const colrFontSupported = macOSVersion[0] >= 10 && macOSVersion[1] >= 14 && safariVersion[0] >= 12;
// https://www.colorfonts.wtf/ states safari supports COLR fonts from this version on
console.log(`COLR support on Safari requires macOS 10.14 and Safari 12, ` +
logger.log(`COLR support on Safari requires macOS 10.14 and Safari 12, ` +
`detected Safari ${safariVersionStr} on macOS ${macOSVersionStr}, ` +
`COLR supported: ${colrFontSupported}`);
return colrFontSupported;
@ -45,7 +46,7 @@ function safariVersionCheck(ua: string): boolean {
}
async function isColrFontSupported(): Promise<boolean> {
console.log("Checking for COLR support");
logger.log("Checking for COLR support");
const { userAgent } = navigator;
// Firefox has supported COLR fonts since version 26
@ -53,7 +54,7 @@ async function isColrFontSupported(): Promise<boolean> {
// "Extract canvas data" permissions
// when content blocking is enabled.
if (userAgent.includes("Firefox")) {
console.log("Browser is Firefox - assuming COLR is supported");
logger.log("Browser is Firefox - assuming COLR is supported");
return true;
}
// Safari doesn't wait for the font to load (if it doesn't have it in cache)
@ -87,12 +88,12 @@ async function isColrFontSupported(): Promise<boolean> {
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
console.log("Waiting for COLR SVG to load");
logger.log("Waiting for COLR SVG to load");
await new Promise(resolve => img.onload = resolve);
console.log("Drawing canvas to detect COLR support");
logger.log("Drawing canvas to detect COLR support");
context.drawImage(img, 0, 0);
const colrFontSupported = (context.getImageData(10, 10, 1, 1).data[0] === 200);
console.log("Canvas check revealed COLR is supported? " + colrFontSupported);
logger.log("Canvas check revealed COLR is supported? " + colrFontSupported);
return colrFontSupported;
} catch (e) {
console.error("Couldn't load COLR font", e);

View File

@ -18,6 +18,8 @@ limitations under the License.
import { _t } from '../languageHandler';
import SdkConfig from '../SdkConfig';
import { logger } from "matrix-js-sdk/src/logger";
const subtleCrypto = window.crypto.subtle || window.crypto.webkitSubtle;
/**
@ -227,7 +229,7 @@ async function deriveKeys(salt, iterations, password) {
}
const now = new Date();
console.log("E2e import/export: deriveKeys took " + (now - start) + "ms");
logger.log("E2e import/export: deriveKeys took " + (now - start) + "ms");
const aesKey = keybits.slice(0, 32);
const hmacKey = keybits.slice(32);

View File

@ -25,6 +25,8 @@ import Modal from "../Modal";
import SettingsStore from "../settings/SettingsStore";
import AskInviteAnywayDialog from "../components/views/dialogs/AskInviteAnywayDialog";
import { logger } from "matrix-js-sdk/src/logger";
export enum InviteState {
Invited = "invited",
Error = "error",
@ -161,7 +163,7 @@ export default class MultiInviter {
private doInvite(address: string, ignoreProfile = false): Promise<void> {
return new Promise<void>((resolve, reject) => {
console.log(`Inviting ${address}`);
logger.log(`Inviting ${address}`);
let doInvite;
if (this.groupId !== null) {
@ -271,7 +273,7 @@ export default class MultiInviter {
return;
}
console.log("Showing failed to invite dialog...");
logger.log("Showing failed to invite dialog...");
Modal.createTrackedDialog('Failed to invite', '', AskInviteAnywayDialog, {
unknownProfileUsers: unknownProfileUsers.map(u => ({
userId: u,

View File

@ -19,6 +19,8 @@ import Analytics from '../Analytics';
import { IndexedDBStore } from "matrix-js-sdk/src/store/indexeddb";
import { IndexedDBCryptoStore } from "matrix-js-sdk/src/crypto/store/indexeddb-crypto-store";
import { logger } from "matrix-js-sdk/src/logger";
const localStorage = window.localStorage;
// just *accessing* indexedDB throws an exception in firefox with
@ -33,7 +35,7 @@ const SYNC_STORE_NAME = "riot-web-sync";
const CRYPTO_STORE_NAME = "matrix-js-sdk:crypto";
function log(msg: string) {
console.log(`StorageManager: ${msg}`);
logger.log(`StorageManager: ${msg}`);
}
function error(msg: string, ...args: string[]) {
@ -47,15 +49,15 @@ function track(action: string) {
export function tryPersistStorage() {
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persist().then(persistent => {
console.log("StorageManager: Persistent?", persistent);
logger.log("StorageManager: Persistent?", persistent);
});
} else if (document.requestStorageAccess) { // Safari
document.requestStorageAccess().then(
() => console.log("StorageManager: Persistent?", true),
() => console.log("StorageManager: Persistent?", false),
() => logger.log("StorageManager: Persistent?", true),
() => logger.log("StorageManager: Persistent?", false),
);
} else {
console.log("StorageManager: Persistence unsupported");
logger.log("StorageManager: Persistence unsupported");
}
}

View File

@ -50,7 +50,7 @@ export async function verifyDevice(user: User, device: IDevice) {
}
// if cross-signing is not explicitly disabled, check if it should be enabled first.
if (cli.getCryptoTrustCrossSignedDevices()) {
if (!await enable4SIfNeeded()) {
if (!(await enable4SIfNeeded())) {
return;
}
}
@ -91,7 +91,7 @@ export async function legacyVerifyUser(user: User) {
}
// if cross-signing is not explicitly disabled, check if it should be enabled first.
if (cli.getCryptoTrustCrossSignedDevices()) {
if (!await enable4SIfNeeded()) {
if (!(await enable4SIfNeeded())) {
return;
}
}
@ -109,7 +109,7 @@ export async function verifyUser(user: User) {
dis.dispatch({ action: 'require_registration' });
return;
}
if (!await enable4SIfNeeded()) {
if (!(await enable4SIfNeeded())) {
return;
}
const existingRequest = pendingVerificationRequestForUser(user);

View File

@ -17,6 +17,8 @@ limitations under the License.
import SdkConfig from "../SdkConfig";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
const JITSI_WK_PROPERTY = "im.vector.riot.jitsi";
export interface JitsiWidgetData {
@ -69,7 +71,7 @@ export class Jitsi {
// Start with a default of the config's domain
let domain = (SdkConfig.get()['jitsi'] || {})['preferredDomain'] || 'jitsi.riot.im';
console.log("Attempting to get Jitsi conference information from homeserver");
logger.log("Attempting to get Jitsi conference information from homeserver");
if (discoveryResponse && discoveryResponse[JITSI_WK_PROPERTY]) {
const wkPreferredDomain = discoveryResponse[JITSI_WK_PROPERTY]['preferredDomain'];
if (wkPreferredDomain) domain = wkPreferredDomain;
@ -77,7 +79,7 @@ export class Jitsi {
// Put the result into memory for us to use later
this.domain = domain;
console.log("Jitsi conference domain:", this.preferredDomain);
logger.log("Jitsi conference domain:", this.preferredDomain);
};
/**