Replace console.warn with logger.warn

Related https://github.com/vector-im/element-web/issues/18425
This commit is contained in:
Dariusz Niemczyk 2021-10-15 16:31:29 +02:00 committed by Dariusz Niemczyk
parent 5e73a212f4
commit 5290afcc4c
71 changed files with 195 additions and 127 deletions

View file

@ -17,6 +17,8 @@ limitations under the License.
import { EventSubscription } from 'fbemitter'; import { EventSubscription } from 'fbemitter';
import RoomViewStore from './stores/RoomViewStore'; import RoomViewStore from './stores/RoomViewStore';
import { logger } from "matrix-js-sdk/src/logger";
type Listener = (isActive: boolean) => void; type Listener = (isActive: boolean) => void;
/** /**
@ -54,7 +56,7 @@ export class ActiveRoomObserver {
this.listeners[roomId].splice(i, 1); this.listeners[roomId].splice(i, 1);
} }
} else { } else {
console.warn("Unregistering unrecognised listener (roomId=" + roomId + ")"); logger.warn("Unregistering unrecognised listener (roomId=" + roomId + ")");
} }
} }

View file

@ -33,7 +33,7 @@ function getRedactedHash(hash: string): string {
// Don't leak URLs we aren't expecting - they could contain tokens/PII // Don't leak URLs we aren't expecting - they could contain tokens/PII
const match = hashRegex.exec(hash); const match = hashRegex.exec(hash);
if (!match) { if (!match) {
console.warn(`Unexpected hash location "${hash}"`); logger.warn(`Unexpected hash location "${hash}"`);
return '#/<unexpected hash location>'; return '#/<unexpected hash location>';
} }
@ -322,7 +322,7 @@ export class Analytics {
} }
if (typeof generationTimeMs !== 'number') { if (typeof generationTimeMs !== 'number') {
console.warn('Analytics.trackPageChange: expected generationTimeMs to be a number'); logger.warn('Analytics.trackPageChange: expected generationTimeMs to be a number');
// But continue anyway because we still want to track the change // But continue anyway because we still want to track the change
} }

View file

@ -61,7 +61,7 @@ export default class AsyncWrapper extends React.Component<IProps, IState> {
: result as ComponentType; : result as ComponentType;
this.setState({ component }); this.setState({ component });
}).catch((e) => { }).catch((e) => {
console.warn('AsyncWrapper promise failed', e); logger.warn('AsyncWrapper promise failed', e);
this.setState({ error: e }); this.setState({ error: e });
}); });
} }

View file

@ -419,7 +419,7 @@ export default class ContentMessages {
sendStickerContentToRoom(url: string, roomId: string, info: IImageInfo, text: string, matrixClient: MatrixClient) { sendStickerContentToRoom(url: string, roomId: string, info: IImageInfo, text: string, matrixClient: MatrixClient) {
const startTime = CountlyAnalytics.getTimestamp(); const startTime = CountlyAnalytics.getTimestamp();
const prom = matrixClient.sendStickerMessage(roomId, url, info, text).catch((e) => { const prom = matrixClient.sendStickerMessage(roomId, url, info, text).catch((e) => {
console.warn(`Failed to send content with URL ${url} to room ${roomId}`, e); logger.warn(`Failed to send content with URL ${url} to room ${roomId}`, e);
throw e; throw e;
}); });
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, false, false, { msgtype: "m.sticker" }); CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, false, false, { msgtype: "m.sticker" });

View file

@ -429,7 +429,7 @@ export default class CountlyAnalytics {
try { try {
this.appVersion = await platform.getAppVersion(); this.appVersion = await platform.getAppVersion();
} catch (e) { } catch (e) {
console.warn("Failed to get app version, using 'unknown'"); logger.warn("Failed to get app version, using 'unknown'");
} }
// start heartbeat // start heartbeat

View file

@ -111,7 +111,7 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise<boolean>
const defaultDeviceDisplayName = opts.defaultDeviceDisplayName; const defaultDeviceDisplayName = opts.defaultDeviceDisplayName;
if (enableGuest && !guestHsUrl) { if (enableGuest && !guestHsUrl) {
console.warn("Cannot enable guest access: can't determine HS URL to use"); logger.warn("Cannot enable guest access: can't determine HS URL to use");
enableGuest = false; enableGuest = false;
} }
@ -188,7 +188,7 @@ export function attemptTokenLogin(
const homeserver = localStorage.getItem(SSO_HOMESERVER_URL_KEY); const homeserver = localStorage.getItem(SSO_HOMESERVER_URL_KEY);
const identityServer = localStorage.getItem(SSO_ID_SERVER_URL_KEY); const identityServer = localStorage.getItem(SSO_ID_SERVER_URL_KEY);
if (!homeserver) { if (!homeserver) {
console.warn("Cannot log in with token: can't determine HS URL to use"); logger.warn("Cannot log in with token: can't determine HS URL to use");
Modal.createTrackedDialog("SSO", "Unknown HS", ErrorDialog, { Modal.createTrackedDialog("SSO", "Unknown HS", ErrorDialog, {
title: _t("We couldn't log you in"), title: _t("We couldn't log you in"),
description: _t("We asked the browser to remember which homeserver you use to let you sign in, " + description: _t("We asked the browser to remember which homeserver you use to let you sign in, " +
@ -523,7 +523,7 @@ export function hydrateSession(credentials: IMatrixClientCreds): Promise<MatrixC
const overwrite = credentials.userId !== oldUserId || credentials.deviceId !== oldDeviceId; const overwrite = credentials.userId !== oldUserId || credentials.deviceId !== oldDeviceId;
if (overwrite) { if (overwrite) {
console.warn("Clearing all data: Old session belongs to a different user/session"); logger.warn("Clearing all data: Old session belongs to a different user/session");
} }
return doSetLoggedIn(credentials, overwrite); return doSetLoggedIn(credentials, overwrite);
@ -602,10 +602,10 @@ async function doSetLoggedIn(
// make sure we don't think that it's a fresh login any more // make sure we don't think that it's a fresh login any more
sessionStorage.removeItem("mx_fresh_login"); sessionStorage.removeItem("mx_fresh_login");
} catch (e) { } catch (e) {
console.warn("Error using local storage: can't persist session!", e); logger.warn("Error using local storage: can't persist session!", e);
} }
} else { } else {
console.warn("No local storage available: can't persist session!"); logger.warn("No local storage available: can't persist session!");
} }
dis.dispatch({ action: 'on_logged_in' }); dis.dispatch({ action: 'on_logged_in' });
@ -650,7 +650,7 @@ async function persistCredentials(credentials: IMatrixClientCreds): Promise<void
encryptedAccessToken = await encryptAES(credentials.accessToken, encrKey, "access_token"); encryptedAccessToken = await encryptAES(credentials.accessToken, encrKey, "access_token");
encrKey.fill(0); encrKey.fill(0);
} catch (e) { } catch (e) {
console.warn("Could not encrypt access token", e); logger.warn("Could not encrypt access token", e);
} }
try { try {
// save either the encrypted access token, or the plain access // save either the encrypted access token, or the plain access
@ -801,7 +801,7 @@ async function startMatrixClient(startSyncing = true): Promise<void> {
await EventIndexPeg.init(); await EventIndexPeg.init();
await MatrixClientPeg.start(); await MatrixClientPeg.start();
} else { } else {
console.warn("Caller requested only auxiliary services be started"); logger.warn("Caller requested only auxiliary services be started");
await MatrixClientPeg.assign(); await MatrixClientPeg.assign();
} }

View file

@ -207,7 +207,7 @@ class MatrixClientPegClass implements IMatrixClientPeg {
} }
// this can happen for a number of reasons, the most likely being // this can happen for a number of reasons, the most likely being
// that the olm library was missing. It's not fatal. // that the olm library was missing. It's not fatal.
console.warn("Unable to initialise e2e", e); logger.warn("Unable to initialise e2e", e);
} }
const opts = utils.deepCopy(this.opts); const opts = utils.deepCopy(this.opts);

View file

@ -20,6 +20,8 @@ import { SettingLevel } from "./settings/SettingLevel";
import EventEmitter from 'events'; import EventEmitter from 'events';
import { MatrixClientPeg } from "./MatrixClientPeg"; import { MatrixClientPeg } from "./MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
// XXX: MediaDeviceKind is a union type, so we make our own enum // XXX: MediaDeviceKind is a union type, so we make our own enum
export enum MediaDeviceKindEnum { export enum MediaDeviceKindEnum {
AudioOutput = "audiooutput", AudioOutput = "audiooutput",
@ -63,7 +65,7 @@ export default class MediaDeviceHandler extends EventEmitter {
devices.forEach((device) => output[device.kind].push(device)); devices.forEach((device) => output[device.kind].push(device));
return output; return output;
} catch (error) { } catch (error) {
console.warn('Unable to refresh WebRTC Devices: ', error); logger.warn('Unable to refresh WebRTC Devices: ', error);
} }
} }

View file

@ -141,12 +141,12 @@ export const Notifier = {
} }
if (!content.url) { if (!content.url) {
console.warn(`${roomId} has custom notification sound event, but no url key`); logger.warn(`${roomId} has custom notification sound event, but no url key`);
return null; return null;
} }
if (!content.url.startsWith("mxc://")) { if (!content.url.startsWith("mxc://")) {
console.warn(`${roomId} has custom notification sound event, but url is not a mxc url`); logger.warn(`${roomId} has custom notification sound event, but url is not a mxc url`);
return null; return null;
} }
@ -181,7 +181,7 @@ export const Notifier = {
} }
await audioElement.play(); await audioElement.play();
} catch (ex) { } catch (ex) {
console.warn("Caught error when trying to fetch room notification sound:", ex); logger.warn("Caught error when trying to fetch room notification sound:", ex);
} }
}, },

View file

@ -695,7 +695,7 @@ const onMessage = function(event: MessageEvent<any>): void {
setBotPower(event, roomId, userId, event.data.level, event.data.ignoreIfGreater); setBotPower(event, roomId, userId, event.data.level, event.data.ignoreIfGreater);
break; break;
default: default:
console.warn("Unhandled postMessage event with action '" + event.data.action +"'"); logger.warn("Unhandled postMessage event with action '" + event.data.action +"'");
break; break;
} }
}; };

View file

@ -283,7 +283,7 @@ async function onSecretRequested(
} }
return key && encodeBase64(key); return key && encodeBase64(key);
} }
console.warn("onSecretRequested didn't recognise the secret named ", name); logger.warn("onSecretRequested didn't recognise the secret named ", name);
} }
export const crossSigningCallbacks: ICryptoCallbacks = { export const crossSigningCallbacks: ICryptoCallbacks = {
@ -388,7 +388,7 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f
logger.log("Setting dehydration key"); logger.log("Setting dehydration key");
await cli.setDehydrationKey(secretStorageKeys[keyId], dehydrationKeyInfo, "Backup device"); await cli.setDehydrationKey(secretStorageKeys[keyId], dehydrationKeyInfo, "Backup device");
} else if (!keyId) { } else if (!keyId) {
console.warn("Not setting dehydration key: no SSSS key found"); logger.warn("Not setting dehydration key: no SSSS key found");
} else { } else {
logger.log("Not setting dehydration key: feature disabled"); logger.log("Not setting dehydration key: feature disabled");
} }

View file

@ -20,6 +20,8 @@ import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { SerializedPart } from "./editor/parts"; import { SerializedPart } from "./editor/parts";
import EditorModel from "./editor/model"; import EditorModel from "./editor/model";
import { logger } from "matrix-js-sdk/src/logger";
interface IHistoryItem { interface IHistoryItem {
parts: SerializedPart[]; parts: SerializedPart[];
replyEventId?: string; replyEventId?: string;
@ -42,7 +44,7 @@ export default class SendHistoryManager {
try { try {
this.history.push(JSON.parse(itemJSON)); this.history.push(JSON.parse(itemJSON));
} catch (e) { } catch (e) {
console.warn("Throwing away unserialisable history", e); logger.warn("Throwing away unserialisable history", e);
break; break;
} }
++index; ++index;

View file

@ -27,6 +27,8 @@ import { SetRightPanelPhasePayload } from './dispatcher/payloads/SetRightPanelPh
import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { MatrixClientPeg } from "./MatrixClientPeg"; import { MatrixClientPeg } from "./MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
// These functions are frequently used just to check whether an event has // These functions are frequently used just to check whether an event has
// any text to display at all. For this reason they return deferred values // any text to display at all. For this reason they return deferred values
// to avoid the expense of looking up translations when they're not needed. // to avoid the expense of looking up translations when they're not needed.
@ -122,7 +124,7 @@ function textForMemberEvent(ev: MatrixEvent, allowJSX: boolean, showHiddenEvents
return null; return null;
} }
} else { } else {
if (!ev.target) console.warn("Join message has no target! -- " + ev.getContent().state_key); if (!ev.target) logger.warn("Join message has no target! -- " + ev.getContent().state_key);
return () => _t('%(targetName)s joined the room', { targetName }); return () => _t('%(targetName)s joined the room', { targetName });
} }
case 'leave': case 'leave':

View file

@ -157,7 +157,7 @@ export class Playback extends EventEmitter implements IDestroyable {
// This error handler is largely for Safari as well, which doesn't support Opus/Ogg // This error handler is largely for Safari as well, which doesn't support Opus/Ogg
// very well. // very well.
logger.error("Error decoding recording: ", e); logger.error("Error decoding recording: ", e);
console.warn("Trying to re-encode to WAV instead..."); logger.warn("Trying to re-encode to WAV instead...");
const wav = await decodeOgg(this.buf); const wav = await decodeOgg(this.buf);

View file

@ -26,6 +26,8 @@ import { isVoiceMessage } from "../utils/EventUtils";
import RoomViewStore from "../stores/RoomViewStore"; import RoomViewStore from "../stores/RoomViewStore";
import { EventType } from "matrix-js-sdk/src/@types/event"; import { EventType } from "matrix-js-sdk/src/@types/event";
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Audio playback queue management for a given room. This keeps track of where the user * Audio playback queue management for a given room. This keeps track of where the user
* was at for each playback, what order the playbacks were played in, and triggers subsequent * was at for each playback, what order the playbacks were played in, and triggers subsequent
@ -114,7 +116,7 @@ export class PlaybackQueue {
if (next) { if (next) {
const instance = this.playbacks.get(next); const instance = this.playbacks.get(next);
if (!instance) { if (!instance) {
console.warn( logger.warn(
"Voice message queue desync: Missing playback for next message: " "Voice message queue desync: Missing playback for next message: "
+ `Current=${this.currentPlaybackId} Last=${last} Next=${next}`, + `Current=${this.currentPlaybackId} Last=${last} Next=${next}`,
); );
@ -173,7 +175,7 @@ export class PlaybackQueue {
} }
} }
} else { } else {
console.warn( logger.warn(
"Voice message queue desync: Expected playback stop to be last in order. " "Voice message queue desync: Expected playback stop to be last in order. "
+ `Current=${this.currentPlaybackId} Last=${last} EventID=${mxEvent.getId()}`, + `Current=${this.currentPlaybackId} Last=${last} EventID=${mxEvent.getId()}`,
); );

View file

@ -27,6 +27,8 @@ import MatrixClientContext from "../../contexts/MatrixClientContext";
import AutoHideScrollbar from "./AutoHideScrollbar"; import AutoHideScrollbar from "./AutoHideScrollbar";
import { ActionPayload } from "../../dispatcher/payloads"; import { ActionPayload } from "../../dispatcher/payloads";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
// URL to request embedded page content from // URL to request embedded page content from
url?: string; url?: string;
@ -79,7 +81,7 @@ export default class EmbeddedPage extends React.PureComponent<IProps, IState> {
} }
if (err || response.status < 200 || response.status >= 300) { if (err || response.status < 200 || response.status >= 300) {
console.warn(`Error loading page: ${err}`); logger.warn(`Error loading page: ${err}`);
this.setState({ page: _t("Couldn't load page") }); this.setState({ page: _t("Couldn't load page") });
return; return;
} }

View file

@ -917,7 +917,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
let waitFor = Promise.resolve(null); let waitFor = Promise.resolve(null);
if (!this.firstSyncComplete) { if (!this.firstSyncComplete) {
if (!this.firstSyncPromise) { if (!this.firstSyncPromise) {
console.warn('Cannot view a room before first sync. room_id:', roomInfo.room_id); logger.warn('Cannot view a room before first sync. room_id:', roomInfo.room_id);
return; return;
} }
waitFor = this.firstSyncPromise.promise; waitFor = this.firstSyncPromise.promise;
@ -973,7 +973,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// Wait for the first sync to complete // Wait for the first sync to complete
if (!this.firstSyncComplete) { if (!this.firstSyncComplete) {
if (!this.firstSyncPromise) { if (!this.firstSyncPromise) {
console.warn('Cannot view a group before first sync. group_id:', groupId); logger.warn('Cannot view a group before first sync. group_id:', groupId);
return; return;
} }
await this.firstSyncPromise.promise; await this.firstSyncPromise.promise;
@ -1475,7 +1475,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
Modal.closeCurrentModal('Session.logged_out'); Modal.closeCurrentModal('Session.logged_out');
if (errObj.httpStatus === 401 && errObj.data && errObj.data['soft_logout']) { if (errObj.httpStatus === 401 && errObj.data && errObj.data['soft_logout']) {
console.warn("Soft logout issued by server - avoiding data deletion"); logger.warn("Soft logout issued by server - avoiding data deletion");
Lifecycle.softLogout(); Lifecycle.softLogout();
return; return;
} }

View file

@ -133,7 +133,7 @@ export default class RoomDirectory extends React.Component<IProps, IState> {
} }
this.setState({ protocolsLoading: false }); this.setState({ protocolsLoading: false });
}, (err) => { }, (err) => {
console.warn(`error loading third party protocols: ${err}`); logger.warn(`error loading third party protocols: ${err}`);
this.setState({ protocolsLoading: false }); this.setState({ protocolsLoading: false });
if (MatrixClientPeg.get().isGuest()) { if (MatrixClientPeg.get().isGuest()) {
// Guests currently aren't allowed to use this API, so // Guests currently aren't allowed to use this API, so

View file

@ -312,7 +312,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// //
// for now, just warn about this. But we're going to end up paginating // for now, just warn about this. But we're going to end up paginating
// both rooms separately, and it's all bad. // both rooms separately, and it's all bad.
console.warn("Replacing timelineSet on a TimelinePanel - confusion may ensue"); logger.warn("Replacing timelineSet on a TimelinePanel - confusion may ensue");
} }
const differentEventId = newProps.eventId != this.props.eventId; const differentEventId = newProps.eventId != this.props.eventId;
@ -1266,7 +1266,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// Somehow, it seems to be possible for live events to not have // Somehow, it seems to be possible for live events to not have
// a timeline, even though that should not happen. :( // a timeline, even though that should not happen. :(
// https://github.com/vector-im/element-web/issues/12120 // https://github.com/vector-im/element-web/issues/12120
console.warn( logger.warn(
`Event ${events[i].getId()} in room ${room.roomId} is live, ` + `Event ${events[i].getId()} in room ${room.roomId} is live, ` +
`but it does not have a timeline`, `but it does not have a timeline`,
); );

View file

@ -176,7 +176,7 @@ const CreateSpaceFromCommunityDialog: React.FC<IProps> = ({ matrixClient: cli, g
const { servers } = await cli.getRoomIdForAlias(canonicalAlias); const { servers } = await cli.getRoomIdForAlias(canonicalAlias);
viaMap.set(roomId, servers); viaMap.set(roomId, servers);
} catch (e) { } catch (e) {
console.warn("Failed to resolve alias during community migration", e); logger.warn("Failed to resolve alias during community migration", e);
} }
} }
@ -221,7 +221,7 @@ const CreateSpaceFromCommunityDialog: React.FC<IProps> = ({ matrixClient: cli, g
_t("This community has been upgraded into a Space") + `</h1></a><br />` _t("This community has been upgraded into a Space") + `</h1></a><br />`
+ groupSummary.profile.long_description, + groupSummary.profile.long_description,
} as IGroupSummary["profile"]).catch(e => { } as IGroupSummary["profile"]).catch(e => {
console.warn("Failed to update community profile during migration", e); logger.warn("Failed to update community profile during migration", e);
}); });
onFinished(roomId); onFinished(roomId);

View file

@ -158,7 +158,7 @@ export default class DeactivateAccountDialog extends React.Component<IProps, ISt
// Our application lifecycle will catch the error and do the logout bits. // Our application lifecycle will catch the error and do the logout bits.
// We'll try to log something in an vain attempt to record what happened (storage // We'll try to log something in an vain attempt to record what happened (storage
// is also obliterated on logout). // is also obliterated on logout).
console.warn("User's account got deactivated without confirmation: Server had no auth"); logger.warn("User's account got deactivated without confirmation: Server had no auth");
this.setState({ errStr: _t("Server did not require any authentication") }); this.setState({ errStr: _t("Server did not require any authentication") });
}).catch(e => { }).catch(e => {
if (e && e.httpStatus === 401 && e.data) { if (e && e.httpStatus === 401 && e.data) {

View file

@ -991,7 +991,7 @@ class SettingsExplorer extends React.PureComponent<IExplorerProps, ISettingsExpl
const val = parsedExplicit[level]; const val = parsedExplicit[level];
await SettingsStore.setValue(settingId, null, level as SettingLevel, val); await SettingsStore.setValue(settingId, null, level as SettingLevel, val);
} catch (e) { } catch (e) {
console.warn(e); logger.warn(e);
} }
} }
const roomId = this.props.room.roomId; const roomId = this.props.room.roomId;
@ -1001,7 +1001,7 @@ class SettingsExplorer extends React.PureComponent<IExplorerProps, ISettingsExpl
const val = parsedExplicitRoom[level]; const val = parsedExplicitRoom[level];
await SettingsStore.setValue(settingId, roomId, level as SettingLevel, val); await SettingsStore.setValue(settingId, roomId, level as SettingLevel, val);
} catch (e) { } catch (e) {
console.warn(e); logger.warn(e);
} }
} }
this.setState({ this.setState({
@ -1035,7 +1035,7 @@ class SettingsExplorer extends React.PureComponent<IExplorerProps, ISettingsExpl
vals[level] = null; vals[level] = null;
} }
} catch (e) { } catch (e) {
console.warn(e); logger.warn(e);
} }
} }
return JSON.stringify(vals, null, 4); return JSON.stringify(vals, null, 4);

View file

@ -33,6 +33,8 @@ import {
} from "./HostSignupDialogTypes"; } from "./HostSignupDialogTypes";
import { replaceableComponent } from "../../../utils/replaceableComponent"; import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
const HOST_SIGNUP_KEY = "host_signup"; const HOST_SIGNUP_KEY = "host_signup";
interface IProps {} interface IProps {}
@ -146,7 +148,7 @@ export default class HostSignupDialog extends React.PureComponent<IProps, IState
private async sendAccountDetails() { private async sendAccountDetails() {
const openIdToken = await MatrixClientPeg.get().getOpenIdToken(); const openIdToken = await MatrixClientPeg.get().getOpenIdToken();
if (!openIdToken || !openIdToken.access_token) { if (!openIdToken || !openIdToken.access_token) {
console.warn("Failed to connect to homeserver for OpenID token."); logger.warn("Failed to connect to homeserver for OpenID token.");
this.setState({ this.setState({
completed: true, completed: true,
error: _t("Failed to connect to your homeserver. Please close this dialog and try again."), error: _t("Failed to connect to your homeserver. Please close this dialog and try again."),

View file

@ -470,7 +470,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
for (const member of otherMembers) { for (const member of otherMembers) {
if (rooms[member.userId]) continue; // already have a room if (rooms[member.userId]) continue; // already have a room
console.warn(`Adding DM room for ${member.userId} as ${dmRoom.roomId} from tag, not DM map`); logger.warn(`Adding DM room for ${member.userId} as ${dmRoom.roomId} from tag, not DM map`);
rooms[member.userId] = dmRoom; rooms[member.userId] = dmRoom;
} }
} }
@ -479,7 +479,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
for (const userId in rooms) { for (const userId in rooms) {
// Filter out user IDs that are already in the room / should be excluded // Filter out user IDs that are already in the room / should be excluded
if (excludedTargetIds.has(userId)) { if (excludedTargetIds.has(userId)) {
console.warn(`[Invite:Recents] Excluding ${userId} from recents`); logger.warn(`[Invite:Recents] Excluding ${userId} from recents`);
continue; continue;
} }
@ -487,7 +487,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
const member = room.getMember(userId); const member = room.getMember(userId);
if (!member) { if (!member) {
// just skip people who don't have memberships for some reason // just skip people who don't have memberships for some reason
console.warn(`[Invite:Recents] ${userId} is missing a member object in their own DM (${room.roomId})`); logger.warn(`[Invite:Recents] ${userId} is missing a member object in their own DM (${room.roomId})`);
continue; continue;
} }
@ -507,13 +507,13 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
} }
if (!lastEventTs) { if (!lastEventTs) {
// something weird is going on with this room // something weird is going on with this room
console.warn(`[Invite:Recents] ${userId} (${room.roomId}) has a weird last timestamp: ${lastEventTs}`); logger.warn(`[Invite:Recents] ${userId} (${room.roomId}) has a weird last timestamp: ${lastEventTs}`);
continue; continue;
} }
recents.push({ userId, user: member, lastActive: lastEventTs }); recents.push({ userId, user: member, lastActive: lastEventTs });
} }
if (!recents) console.warn("[Invite:Recents] No recents to suggest!"); if (!recents) logger.warn("[Invite:Recents] No recents to suggest!");
// Sort the recents by last active to save us time later // Sort the recents by last active to save us time later
recents.sort((a, b) => b.lastActive - a.lastActive); recents.sort((a, b) => b.lastActive - a.lastActive);
@ -873,8 +873,8 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
}); });
} }
} catch (e) { } catch (e) {
console.warn("Non-fatal error trying to make an invite for a user ID"); logger.warn("Non-fatal error trying to make an invite for a user ID");
console.warn(e); logger.warn(e);
// Add a result anyways, just without a profile. We stick it at the // Add a result anyways, just without a profile. We stick it at the
// top so it is most obviously presented to the user. // top so it is most obviously presented to the user.

View file

@ -176,7 +176,7 @@ export default class AppTile extends React.Component<IProps, IState> {
const u = url.parse(this.props.app.url); const u = url.parse(this.props.app.url);
const childContentProtocol = u.protocol; const childContentProtocol = u.protocol;
if (parentContentProtocol === 'https:' && childContentProtocol !== 'https:') { if (parentContentProtocol === 'https:' && childContentProtocol !== 'https:') {
console.warn("Refusing to load mixed-content app:", logger.warn("Refusing to load mixed-content app:",
parentContentProtocol, childContentProtocol, window.location, this.props.app.url); parentContentProtocol, childContentProtocol, window.location, this.props.app.url);
return true; return true;
} }
@ -305,7 +305,7 @@ export default class AppTile extends React.Component<IProps, IState> {
dis.dispatch({ action: 'post_sticker_message', data: payload.data }); dis.dispatch({ action: 'post_sticker_message', data: payload.data });
dis.dispatch({ action: 'stickerpicker_close' }); dis.dispatch({ action: 'stickerpicker_close' });
} else { } else {
console.warn('Ignoring sticker message. Invalid capability'); logger.warn('Ignoring sticker message. Invalid capability');
} }
break; break;
} }

View file

@ -22,6 +22,8 @@ import dis from "../../../dispatcher/dispatcher";
import { Action } from "../../../dispatcher/actions"; import { Action } from "../../../dispatcher/actions";
import { UserTab } from "../dialogs/UserSettingsDialog"; import { UserTab } from "../dialogs/UserSettingsDialog";
import { logger } from "matrix-js-sdk/src/logger";
export enum WarningKind { export enum WarningKind {
Files, Files,
Search, Search,
@ -83,7 +85,7 @@ export default function DesktopBuildsNotice({ isRoomEncrypted, kind }: IProps) {
// for safety // for safety
if (!text) { if (!text) {
console.warn("Unknown desktop builds warning kind: ", kind); logger.warn("Unknown desktop builds warning kind: ", kind);
return null; return null;
} }

View file

@ -20,6 +20,8 @@ import ICanvasEffect from '../../../effects/ICanvasEffect';
import { CHAT_EFFECTS } from '../../../effects'; import { CHAT_EFFECTS } from '../../../effects';
import UIStore, { UI_EVENTS } from "../../../stores/UIStore"; import UIStore, { UI_EVENTS } from "../../../stores/UIStore";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
roomWidth: number; roomWidth: number;
} }
@ -38,7 +40,7 @@ const EffectsOverlay: FunctionComponent<IProps> = ({ roomWidth }) => {
effect = new Effect(options); effect = new Effect(options);
effectsRef.current[name] = effect; effectsRef.current[name] = effect;
} catch (err) { } catch (err) {
console.warn(`Unable to load effect module at '../../../effects/${name}.`, err); logger.warn(`Unable to load effect module at '../../../effects/${name}.`, err);
} }
} }
return effect; return effect;

View file

@ -33,6 +33,8 @@ import SettingsStore from "../../../settings/SettingsStore";
import { mediaFromMxc } from "../../../customisations/Media"; import { mediaFromMxc } from "../../../customisations/Media";
import { replaceableComponent } from "../../../utils/replaceableComponent"; import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
// A class for a child of GroupFilterPanel (possibly wrapped in a DNDTagTile) that represents // A class for a child of GroupFilterPanel (possibly wrapped in a DNDTagTile) that represents
// a thing to click on for the user to filter the visible rooms in the RoomList to: // a thing to click on for the user to filter the visible rooms in the RoomList to:
// - Rooms that are part of the group // - Rooms that are part of the group
@ -85,7 +87,7 @@ export default class TagTile extends React.Component {
if (this.unmounted) return; if (this.unmounted) return;
this.setState({ profile }); this.setState({ profile });
}).catch((err) => { }).catch((err) => {
console.warn('Could not fetch group profile for ' + this.props.tag, err); logger.warn('Could not fetch group profile for ' + this.props.tag, err);
}); });
}; };

View file

@ -27,6 +27,8 @@ import { PlaybackManager } from "../../../audio/PlaybackManager";
import { isVoiceMessage } from "../../../utils/EventUtils"; import { isVoiceMessage } from "../../../utils/EventUtils";
import { PlaybackQueue } from "../../../audio/PlaybackQueue"; import { PlaybackQueue } from "../../../audio/PlaybackQueue";
import { logger } from "matrix-js-sdk/src/logger";
interface IState { interface IState {
error?: Error; error?: Error;
playback?: Playback; playback?: Playback;
@ -49,12 +51,12 @@ export default class MAudioBody extends React.PureComponent<IBodyProps, IState>
buffer = await blob.arrayBuffer(); buffer = await blob.arrayBuffer();
} catch (e) { } catch (e) {
this.setState({ error: e }); this.setState({ error: e });
console.warn("Unable to decrypt audio message", e); logger.warn("Unable to decrypt audio message", e);
return; // stop processing the audio file return; // stop processing the audio file
} }
} catch (e) { } catch (e) {
this.setState({ error: e }); this.setState({ error: e });
console.warn("Unable to decrypt/download audio message", e); logger.warn("Unable to decrypt/download audio message", e);
return; // stop processing the audio file return; // stop processing the audio file
} }

View file

@ -170,7 +170,7 @@ export default class MFileBody extends React.Component<IProps, IState> {
decryptedBlob: await this.props.mediaEventHelper.sourceBlob.value, decryptedBlob: await this.props.mediaEventHelper.sourceBlob.value,
}); });
} catch (err) { } catch (err) {
console.warn("Unable to decrypt attachment: ", err); logger.warn("Unable to decrypt attachment: ", err);
Modal.createTrackedDialog('Error decrypting attachment', '', ErrorDialog, { Modal.createTrackedDialog('Error decrypting attachment', '', ErrorDialog, {
title: _t("Error"), title: _t("Error"),
description: _t("Error decrypting attachment"), description: _t("Error decrypting attachment"),

View file

@ -34,6 +34,8 @@ import { IBodyProps } from "./IBodyProps";
import classNames from 'classnames'; import classNames from 'classnames';
import { CSSTransition, SwitchTransition } from 'react-transition-group'; import { CSSTransition, SwitchTransition } from 'react-transition-group';
import { logger } from "matrix-js-sdk/src/logger";
interface IState { interface IState {
decryptedUrl?: string; decryptedUrl?: string;
decryptedThumbnailUrl?: string; decryptedThumbnailUrl?: string;
@ -275,7 +277,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
}); });
} catch (err) { } catch (err) {
if (this.unmounted) return; if (this.unmounted) return;
console.warn("Unable to decrypt attachment: ", err); logger.warn("Unable to decrypt attachment: ", err);
// Set a placeholder image when we can't decrypt the image. // Set a placeholder image when we can't decrypt the image.
this.setState({ this.setState({
error: err, error: err,

View file

@ -180,7 +180,7 @@ export default class MVideoBody extends React.PureComponent<IBodyProps, IState>
}); });
} }
} catch (err) { } catch (err) {
console.warn("Unable to decrypt attachment: ", err); logger.warn("Unable to decrypt attachment: ", err);
// Set a placeholder image when we can't decrypt the image. // Set a placeholder image when we can't decrypt the image.
this.setState({ this.setState({
error: err, error: err,

View file

@ -236,7 +236,7 @@ export default class VerificationPanel extends React.PureComponent<IProps, IStat
if (!device) { if (!device) {
// This can happen if the device is logged out while we're still showing verification // This can happen if the device is logged out while we're still showing verification
// UI for it. // UI for it.
console.warn("Verified device we don't know about: " + this.props.request.channel.deviceId); logger.warn("Verified device we don't know about: " + this.props.request.channel.deviceId);
description = _t("You've successfully verified your device!"); description = _t("You've successfully verified your device!");
} else { } else {
description = _t("You've successfully verified %(deviceName)s (%(deviceId)s)!", { description = _t("You've successfully verified %(deviceName)s (%(deviceId)s)!", {

View file

@ -61,6 +61,8 @@ import MKeyVerificationConclusion from "../messages/MKeyVerificationConclusion";
import { dispatchShowThreadEvent } from '../../../dispatcher/dispatch-actions/threads'; import { dispatchShowThreadEvent } from '../../../dispatcher/dispatch-actions/threads';
import { MessagePreviewStore } from '../../../stores/room-list/MessagePreviewStore'; import { MessagePreviewStore } from '../../../stores/room-list/MessagePreviewStore';
import { logger } from "matrix-js-sdk/src/logger";
const eventTileTypes = { const eventTileTypes = {
[EventType.RoomMessage]: 'messages.MessageEvent', [EventType.RoomMessage]: 'messages.MessageEvent',
[EventType.Sticker]: 'messages.MessageEvent', [EventType.Sticker]: 'messages.MessageEvent',
@ -974,7 +976,7 @@ export default class EventTile extends React.Component<IProps, IState> {
// before trying to instantiate us // before trying to instantiate us
if (!tileHandler) { if (!tileHandler) {
const { mxEvent } = this.props; const { mxEvent } = this.props;
console.warn(`Event type not supported: type:${eventType} isState:${mxEvent.isState()}`); logger.warn(`Event type not supported: type:${eventType} isState:${mxEvent.isState()}`);
return <div className="mx_EventTile mx_EventTile_info mx_MNoticeBody"> return <div className="mx_EventTile mx_EventTile_info mx_MNoticeBody">
<div className="mx_EventTile_line"> <div className="mx_EventTile_line">
{ _t('This event could not be displayed') } { _t('This event could not be displayed') }

View file

@ -48,6 +48,8 @@ import { shouldShowComponent } from "../../../customisations/helpers/UIComponent
import { UIComponent } from "../../../settings/UIFeature"; import { UIComponent } from "../../../settings/UIFeature";
import { JoinRule } from "matrix-js-sdk/src/@types/partials"; import { JoinRule } from "matrix-js-sdk/src/@types/partials";
import { logger } from "matrix-js-sdk/src/logger";
const getSearchQueryLSKey = (roomId: string) => `mx_MemberList_searchQuarry_${roomId}`; const getSearchQueryLSKey = (roomId: string) => `mx_MemberList_searchQuarry_${roomId}`;
const INITIAL_LOAD_NUM_MEMBERS = 30; const INITIAL_LOAD_NUM_MEMBERS = 30;
@ -184,7 +186,7 @@ export default class MemberList extends React.Component<IProps, IState> {
try { try {
searchQuery = window.localStorage.getItem(getSearchQueryLSKey(this.props.roomId)); searchQuery = window.localStorage.getItem(getSearchQueryLSKey(this.props.roomId));
} catch (error) { } catch (error) {
console.warn("Failed to get last the MemberList search query", error); logger.warn("Failed to get last the MemberList search query", error);
} }
// set the state after determining showPresence to make sure it's // set the state after determining showPresence to make sure it's
@ -433,7 +435,7 @@ export default class MemberList extends React.Component<IProps, IState> {
try { try {
window.localStorage.setItem(getSearchQueryLSKey(this.props.roomId), searchQuery); window.localStorage.setItem(getSearchQueryLSKey(this.props.roomId), searchQuery);
} catch (error) { } catch (error) {
console.warn("Failed to set the last MemberList search query", error); logger.warn("Failed to set the last MemberList search query", error);
} }
this.setState({ this.setState({

View file

@ -26,6 +26,8 @@ import { replaceableComponent } from "../../../utils/replaceableComponent";
import MemberAvatar from '../avatars/MemberAvatar'; import MemberAvatar from '../avatars/MemberAvatar';
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
// the RoomMember to show the RR for // the RoomMember to show the RR for
member?: RoomMember; member?: RoomMember;
@ -145,7 +147,7 @@ export default class ReadReceiptMarker extends React.PureComponent<IProps, IStat
// this seems to happen sometimes for reasons I don't understand // this seems to happen sometimes for reasons I don't understand
// the docs for `offsetParent` say it may be null if `display` is // the docs for `offsetParent` say it may be null if `display` is
// `none`, but I can't see why that would happen. // `none`, but I can't see why that would happen.
console.warn( logger.warn(
`ReadReceiptMarker for ${this.props.fallbackUserId} in has no offsetParent`, `ReadReceiptMarker for ${this.props.fallbackUserId} in has no offsetParent`,
); );
startTopOffset = 0; startTopOffset = 0;

View file

@ -29,6 +29,8 @@ import { getEventDisplayInfo, isVoiceMessage } from '../../../utils/EventUtils';
import MFileBody from "../messages/MFileBody"; import MFileBody from "../messages/MFileBody";
import MVoiceMessageBody from "../messages/MVoiceMessageBody"; import MVoiceMessageBody from "../messages/MVoiceMessageBody";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
mxEvent: MatrixEvent; mxEvent: MatrixEvent;
permalinkCreator?: RoomPermalinkCreator; permalinkCreator?: RoomPermalinkCreator;
@ -107,7 +109,7 @@ export default class ReplyTile extends React.PureComponent<IProps> {
// before trying to instantiate us // before trying to instantiate us
if (!tileHandler) { if (!tileHandler) {
const { mxEvent } = this.props; const { mxEvent } = this.props;
console.warn(`Event type not supported: type:${mxEvent.getType()} isState:${mxEvent.isState()}`); logger.warn(`Event type not supported: type:${mxEvent.getType()} isState:${mxEvent.isState()}`);
return <div className="mx_ReplyTile mx_ReplyTile_info mx_MNoticeBody"> return <div className="mx_ReplyTile mx_ReplyTile_info mx_MNoticeBody">
{ _t('This event could not be displayed') } { _t('This event could not be displayed') }
</div>; </div>;

View file

@ -50,6 +50,8 @@ import IconizedContextMenu, {
import { CommunityPrototypeStore, IRoomProfile } from "../../../stores/CommunityPrototypeStore"; import { CommunityPrototypeStore, IRoomProfile } from "../../../stores/CommunityPrototypeStore";
import { replaceableComponent } from "../../../utils/replaceableComponent"; import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
room: Room; room: Room;
showMessagePreview: boolean; showMessagePreview: boolean;
@ -299,7 +301,7 @@ export default class RoomTile extends React.PureComponent<IProps, IState> {
0, 0,
)); ));
} else { } else {
console.warn(`Unexpected tag ${tagId} applied to ${this.props.room.roomId}`); logger.warn(`Unexpected tag ${tagId} applied to ${this.props.room.roomId}`);
} }
if ((ev as React.KeyboardEvent).key === Key.ENTER) { if ((ev as React.KeyboardEvent).key === Key.ENTER) {

View file

@ -113,7 +113,7 @@ export default class Stickerpicker extends React.PureComponent<IProps, IState> {
logger.error("Cannot disable assets: no scalar client"); logger.error("Cannot disable assets: no scalar client");
} }
} else { } else {
console.warn('No widget ID specified, not disabling assets'); logger.warn('No widget ID specified, not disabling assets');
} }
this.props.setShowStickers(false); this.props.setShowStickers(false);

View file

@ -27,6 +27,8 @@ import { isUrlPermitted } from '../../../HtmlUtils';
import { replaceableComponent } from "../../../utils/replaceableComponent"; import { replaceableComponent } from "../../../utils/replaceableComponent";
import { mediaFromMxc } from "../../../customisations/Media"; import { mediaFromMxc } from "../../../customisations/Media";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps { interface IProps {
ev: MatrixEvent; ev: MatrixEvent;
room: Room; room: Room;
@ -75,13 +77,13 @@ export default class BridgeTile extends React.PureComponent<IProps> {
const content: IBridgeStateEvent = this.props.ev.getContent(); const content: IBridgeStateEvent = this.props.ev.getContent();
// Validate // Validate
if (!content.channel?.id || !content.protocol?.id) { if (!content.channel?.id || !content.protocol?.id) {
console.warn(`Bridge info event ${this.props.ev.getId()} has missing content. Tile will not render`); logger.warn(`Bridge info event ${this.props.ev.getId()} has missing content. Tile will not render`);
return null; return null;
} }
if (!content.bridgebot) { if (!content.bridgebot) {
// Bridgebot was not required previously, so in order to not break rooms we are allowing // Bridgebot was not required previously, so in order to not break rooms we are allowing
// the sender to be used in place. When the proposal is merged, this should be removed. // the sender to be used in place. When the proposal is merged, this should be removed.
console.warn(`Bridge info event ${this.props.ev.getId()} does not provide a 'bridgebot' key which` logger.warn(`Bridge info event ${this.props.ev.getId()} does not provide a 'bridgebot' key which`
+ "is deprecated behaviour. Using sender for now."); + "is deprecated behaviour. Using sender for now.");
content.bridgebot = this.props.ev.getSender(); content.bridgebot = this.props.ev.getSender();
} }

View file

@ -270,11 +270,11 @@ export default class SetIdServer extends React.Component<IProps, IState> {
); );
} catch (e) { } catch (e) {
currentServerReachable = false; currentServerReachable = false;
console.warn( logger.warn(
`Unable to reach identity server at ${currentClientIdServer} to check ` + `Unable to reach identity server at ${currentClientIdServer} to check ` +
`for 3PIDs during IS change flow`, `for 3PIDs during IS change flow`,
); );
console.warn(e); logger.warn(e);
} }
const boundThreepids = threepids.filter(tp => tp.bound); const boundThreepids = threepids.filter(tp => tp.bound);
let message; let message;

View file

@ -168,11 +168,11 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
threepids = await getThreepidsWithBindStatus(cli); threepids = await getThreepidsWithBindStatus(cli);
} catch (e) { } catch (e) {
const idServerUrl = MatrixClientPeg.get().getIdentityServerUrl(); const idServerUrl = MatrixClientPeg.get().getIdentityServerUrl();
console.warn( logger.warn(
`Unable to reach identity server at ${idServerUrl} to check ` + `Unable to reach identity server at ${idServerUrl} to check ` +
`for 3PIDs bindings in Settings`, `for 3PIDs bindings in Settings`,
); );
console.warn(e); logger.warn(e);
} }
this.setState({ this.setState({
emails: threepids.filter((a) => a.medium === 'email'), emails: threepids.filter((a) => a.medium === 'email'),
@ -218,11 +218,11 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
}, },
}); });
} catch (e) { } catch (e) {
console.warn( logger.warn(
`Unable to reach identity server at ${idServerUrl} to check ` + `Unable to reach identity server at ${idServerUrl} to check ` +
`for terms in Settings`, `for terms in Settings`,
); );
console.warn(e); logger.warn(e);
} }
} }

View file

@ -42,6 +42,8 @@ import CrossSigningPanel from "../../CrossSigningPanel";
import EventIndexPanel from "../../EventIndexPanel"; import EventIndexPanel from "../../EventIndexPanel";
import InlineSpinner from "../../../elements/InlineSpinner"; import InlineSpinner from "../../../elements/InlineSpinner";
import { logger } from "matrix-js-sdk/src/logger";
interface IIgnoredUserProps { interface IIgnoredUserProps {
userId: string; userId: string;
onUnignored: (userId: string) => void; onUnignored: (userId: string) => void;
@ -174,7 +176,7 @@ export default class SecurityUserSettingsTab extends React.Component<IProps, ISt
i--; i--;
} else { } else {
// Print out error with joining/leaving room // Print out error with joining/leaving room
console.warn(e); logger.warn(e);
} }
}); });
} }

View file

@ -227,7 +227,7 @@ export default async function createRoom(opts: IOpts): Promise<string | null> {
// but the server denies them that permission (via room_list_publication_rules). // but the server denies them that permission (via room_list_publication_rules).
// The check below responds by retrying without publishing the room. // The check below responds by retrying without publishing the room.
if (err.httpStatus === 403 && err.errcode === "M_UNKNOWN" && err.data.error === "Not allowed to publish room") { if (err.httpStatus === 403 && err.errcode === "M_UNKNOWN" && err.data.error === "Not allowed to publish room") {
console.warn("Failed to publish room, try again without publishing it"); logger.warn("Failed to publish room, try again without publishing it");
createOpts.visibility = Visibility.Private; createOpts.visibility = Visibility.Private;
return client.createRoom(createOpts); return client.createRoom(createOpts);
} else { } else {

View file

@ -583,7 +583,7 @@ export default class EventIndex extends EventEmitter {
if (eventId) { if (eventId) {
await indexManager.deleteEvent(eventId); await indexManager.deleteEvent(eventId);
} else { } else {
console.warn("EventIndex: Redaction event doesn't contain a valid associated event id", ev); logger.warn("EventIndex: Redaction event doesn't contain a valid associated event id", ev);
} }
} }

View file

@ -225,18 +225,18 @@ export class IntegrationManagers {
wkConfig = await result.json(); wkConfig = await result.json();
} catch (e) { } catch (e) {
logger.error(e); logger.error(e);
console.warn("Failed to locate integration manager"); logger.warn("Failed to locate integration manager");
return null; return null;
} }
if (!wkConfig || !wkConfig["m.integrations_widget"]) { if (!wkConfig || !wkConfig["m.integrations_widget"]) {
console.warn("Missing integrations widget on .well-known response"); logger.warn("Missing integrations widget on .well-known response");
return null; return null;
} }
const widget = wkConfig["m.integrations_widget"]; const widget = wkConfig["m.integrations_widget"];
if (!widget["url"] || !widget["data"] || !widget["data"]["api_url"]) { if (!widget["url"] || !widget["data"] || !widget["data"]["api_url"]) {
console.warn("Malformed .well-known response for integrations widget"); logger.warn("Malformed .well-known response for integrations widget");
return null; return null;
} }

View file

@ -89,11 +89,11 @@ function safeCounterpartTranslate(text: string, options?: object) {
count = options['count']; count = options['count'];
Object.keys(options).forEach((k) => { Object.keys(options).forEach((k) => {
if (options[k] === undefined) { if (options[k] === undefined) {
console.warn("safeCounterpartTranslate called with undefined interpolation name: " + k); logger.warn("safeCounterpartTranslate called with undefined interpolation name: " + k);
options[k] = 'undefined'; options[k] = 'undefined';
} }
if (options[k] === null) { if (options[k] === null) {
console.warn("safeCounterpartTranslate called with null interpolation name: " + k); logger.warn("safeCounterpartTranslate called with null interpolation name: " + k);
options[k] = 'null'; options[k] = 'null';
} }
}); });

View file

@ -16,6 +16,8 @@ limitations under the License.
import { PerformanceEntryNames } from "./entry-names"; import { PerformanceEntryNames } from "./entry-names";
import { logger } from "matrix-js-sdk/src/logger";
interface GetEntriesOptions { interface GetEntriesOptions {
name?: string; name?: string;
type?: string; type?: string;
@ -57,7 +59,7 @@ export default class PerformanceMonitor {
const key = this.buildKey(name, id); const key = this.buildKey(name, id);
if (performance.getEntriesByName(this.START_PREFIX + key).length > 0) { if (performance.getEntriesByName(this.START_PREFIX + key).length > 0) {
console.warn(`Recording already started for: ${name}`); logger.warn(`Recording already started for: ${name}`);
return; return;
} }
@ -77,7 +79,7 @@ export default class PerformanceMonitor {
} }
const key = this.buildKey(name, id); const key = this.buildKey(name, id);
if (performance.getEntriesByName(this.START_PREFIX + key).length === 0) { if (performance.getEntriesByName(this.START_PREFIX + key).length === 0) {
console.warn(`No recording started for: ${name}`); logger.warn(`No recording started for: ${name}`);
return; return;
} }

View file

@ -182,7 +182,7 @@ export default class SettingsStore {
*/ */
public static unwatchSetting(watcherReference: string) { public static unwatchSetting(watcherReference: string) {
if (!SettingsStore.watchers.has(watcherReference)) { if (!SettingsStore.watchers.has(watcherReference)) {
console.warn(`Ending non-existent watcher ID ${watcherReference}`); logger.warn(`Ending non-existent watcher ID ${watcherReference}`);
return; return;
} }

View file

@ -23,6 +23,8 @@ import { SettingLevel } from "../SettingLevel";
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor"; import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
import { PushRuleActionName } from "matrix-js-sdk/src/@types/PushRules"; import { PushRuleActionName } from "matrix-js-sdk/src/@types/PushRules";
import { logger } from "matrix-js-sdk/src/logger";
// .m.rule.master being enabled means all events match that push rule // .m.rule.master being enabled means all events match that push rule
// default action on this rule is dont_notify, but it could be something else // default action on this rule is dont_notify, but it could be something else
export function isPushNotifyDisabled(): boolean { export function isPushNotifyDisabled(): boolean {
@ -31,7 +33,7 @@ export function isPushNotifyDisabled(): boolean {
const masterRule = processor.getPushRuleById(".m.rule.master"); const masterRule = processor.getPushRuleById(".m.rule.master");
if (!masterRule) { if (!masterRule) {
console.warn("No master push rule! Notifications are disabled for this user."); logger.warn("No master push rule! Notifications are disabled for this user.");
return true; return true;
} }

View file

@ -17,6 +17,8 @@ limitations under the License.
import SettingsHandler from "./SettingsHandler"; import SettingsHandler from "./SettingsHandler";
import { MatrixClient } from "matrix-js-sdk/src/client"; import { MatrixClient } from "matrix-js-sdk/src/client";
import { logger } from "matrix-js-sdk/src/logger";
// Dev note: This whole class exists in the event someone logs out and back in - we want // Dev note: This whole class exists in the event someone logs out and back in - we want
// to make sure the right MatrixClient is listening for changes. // to make sure the right MatrixClient is listening for changes.
@ -48,6 +50,6 @@ export default abstract class MatrixClientBackedSettingsHandler extends Settings
} }
protected initMatrixClient(oldClient: MatrixClient, newClient: MatrixClient) { protected initMatrixClient(oldClient: MatrixClient, newClient: MatrixClient) {
console.warn("initMatrixClient not overridden"); logger.warn("initMatrixClient not overridden");
} }
} }

View file

@ -28,6 +28,8 @@ import GroupStore from "./GroupStore";
import dis from "../dispatcher/dispatcher"; import dis from "../dispatcher/dispatcher";
import { isNullOrUndefined } from "matrix-js-sdk/src/utils"; import { isNullOrUndefined } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";
interface IState { interface IState {
// nothing of value - we use account data // nothing of value - we use account data
} }
@ -134,7 +136,7 @@ export class CommunityPrototypeStore extends AsyncStoreWithClient<IState> {
// we use global account data because per-room account data on invites is unreliable // we use global account data because per-room account data on invites is unreliable
await this.matrixClient.setAccountData("im.vector.group_info." + room.roomId, profile); await this.matrixClient.setAccountData("im.vector.group_info." + room.roomId, profile);
} catch (e) { } catch (e) {
console.warn("Non-fatal error getting group information for invite:", e); logger.warn("Non-fatal error getting group information for invite:", e);
} }
} }
} else if (payload.action === "MatrixActions.accountData") { } else if (payload.action === "MatrixActions.accountData") {

View file

@ -98,7 +98,7 @@ class FlairStore extends EventEmitter {
}).catch((err) => { }).catch((err) => {
// Indicate whether the homeserver supports groups // Indicate whether the homeserver supports groups
if (err.errcode === 'M_UNRECOGNIZED') { if (err.errcode === 'M_UNRECOGNIZED') {
console.warn('Cannot display flair, server does not support groups'); logger.warn('Cannot display flair, server does not support groups');
groupSupport = false; groupSupport = false;
// Return silently to avoid spamming for non-supporting servers // Return silently to avoid spamming for non-supporting servers
return; return;

View file

@ -23,6 +23,8 @@ import { ActionPayload } from "../dispatcher/payloads";
import { Action } from '../dispatcher/actions'; import { Action } from '../dispatcher/actions';
import { SettingLevel } from "../settings/SettingLevel"; import { SettingLevel } from "../settings/SettingLevel";
import { logger } from "matrix-js-sdk/src/logger";
interface RightPanelStoreState { interface RightPanelStoreState {
// Whether or not to show the right panel at all. We split out rooms and groups // Whether or not to show the right panel at all. We split out rooms and groups
// because they're different flows for the user to follow. // because they're different flows for the user to follow.
@ -180,7 +182,7 @@ export default class RightPanelStore extends Store<ActionPayload> {
} }
} }
if (!RightPanelPhases[targetPhase]) { if (!RightPanelPhases[targetPhase]) {
console.warn(`Tried to switch right panel to unknown phase: ${targetPhase}`); logger.warn(`Tried to switch right panel to unknown phase: ${targetPhase}`);
return; return;
} }

View file

@ -867,7 +867,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
try { try {
await this.matrixClient.setRoomAccountData(space.roomId, EventType.SpaceOrder, { order }); await this.matrixClient.setRoomAccountData(space.roomId, EventType.SpaceOrder, { order });
} catch (e) { } catch (e) {
console.warn("Failed to set root space order", e); logger.warn("Failed to set root space order", e);
if (this.spaceOrderLocalEchoMap.get(space.roomId) === order) { if (this.spaceOrderLocalEchoMap.get(space.roomId) === order) {
this.spaceOrderLocalEchoMap.delete(space.roomId); this.spaceOrderLocalEchoMap.delete(space.roomId);
} }

View file

@ -126,7 +126,7 @@ export default class WidgetStore extends AsyncStoreWithClient<IState> {
// Sanity check for https://github.com/vector-im/element-web/issues/15705 // Sanity check for https://github.com/vector-im/element-web/issues/15705
const existingApp = this.widgetMap.get(widgetUid(app)); const existingApp = this.widgetMap.get(widgetUid(app));
if (existingApp) { if (existingApp) {
console.warn( logger.warn(
`Possible widget ID conflict for ${app.id} - wants to store in room ${app.roomId} ` + `Possible widget ID conflict for ${app.id} - wants to store in room ${app.roomId} ` +
`but is currently stored as ${existingApp.roomId} - letting the want win`, `but is currently stored as ${existingApp.roomId} - letting the want win`,
); );

View file

@ -20,6 +20,8 @@ import { AsyncStoreWithClient } from "../AsyncStoreWithClient";
import defaultDispatcher from "../../dispatcher/dispatcher"; import defaultDispatcher from "../../dispatcher/dispatcher";
import { ActionPayload } from "../../dispatcher/payloads"; import { ActionPayload } from "../../dispatcher/payloads";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {} interface IState {}
export default class RoomListLayoutStore extends AsyncStoreWithClient<IState> { export default class RoomListLayoutStore extends AsyncStoreWithClient<IState> {
@ -53,7 +55,7 @@ export default class RoomListLayoutStore extends AsyncStoreWithClient<IState> {
// Note: this primarily exists for debugging, and isn't really intended to be used by anything. // Note: this primarily exists for debugging, and isn't really intended to be used by anything.
public async resetLayouts() { public async resetLayouts() {
console.warn("Resetting layouts for room list"); logger.warn("Resetting layouts for room list");
for (const layout of this.layoutMap.values()) { for (const layout of this.layoutMap.values()) {
layout.reset(); layout.reset();
} }

View file

@ -162,7 +162,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
} else if (activeRoomId) { } else if (activeRoomId) {
const activeRoom = this.matrixClient.getRoom(activeRoomId); const activeRoom = this.matrixClient.getRoom(activeRoomId);
if (!activeRoom) { if (!activeRoom) {
console.warn(`${activeRoomId} is current in RVS but missing from client - clearing sticky room`); logger.warn(`${activeRoomId} is current in RVS but missing from client - clearing sticky room`);
this.algorithm.setStickyRoom(null); this.algorithm.setStickyRoom(null);
} else if (activeRoom !== this.algorithm.stickyRoom) { } else if (activeRoom !== this.algorithm.stickyRoom) {
this.algorithm.setStickyRoom(activeRoom); this.algorithm.setStickyRoom(activeRoom);
@ -226,7 +226,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
if (readReceiptChangeIsFor(payload.event, this.matrixClient)) { if (readReceiptChangeIsFor(payload.event, this.matrixClient)) {
const room = payload.room; const room = payload.room;
if (!room) { if (!room) {
console.warn(`Own read receipt was in unknown room ${room.roomId}`); logger.warn(`Own read receipt was in unknown room ${room.roomId}`);
return; return;
} }
await this.handleRoomUpdate(room, RoomUpdateCause.ReadReceipt); await this.handleRoomUpdate(room, RoomUpdateCause.ReadReceipt);
@ -258,8 +258,8 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
this.updateFn.trigger(); this.updateFn.trigger();
}; };
if (!room) { if (!room) {
console.warn(`Live timeline event ${eventPayload.event.getId()} received without associated room`); logger.warn(`Live timeline event ${eventPayload.event.getId()} received without associated room`);
console.warn(`Queuing failed room update for retry as a result.`); logger.warn(`Queuing failed room update for retry as a result.`);
setTimeout(async () => { setTimeout(async () => {
const updatedRoom = this.matrixClient.getRoom(roomId); const updatedRoom = this.matrixClient.getRoom(roomId);
await tryUpdate(updatedRoom); await tryUpdate(updatedRoom);
@ -276,7 +276,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
} }
const room = this.matrixClient.getRoom(roomId); const room = this.matrixClient.getRoom(roomId);
if (!room) { if (!room) {
console.warn(`Event ${eventPayload.event.getId()} was decrypted in an unknown room ${roomId}`); logger.warn(`Event ${eventPayload.event.getId()} was decrypted in an unknown room ${roomId}`);
return; return;
} }
await this.handleRoomUpdate(room, RoomUpdateCause.Timeline); await this.handleRoomUpdate(room, RoomUpdateCause.Timeline);
@ -289,7 +289,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
for (const roomId of roomIds) { for (const roomId of roomIds) {
const room = this.matrixClient.getRoom(roomId); const room = this.matrixClient.getRoom(roomId);
if (!room) { if (!room) {
console.warn(`${roomId} was found in DMs but the room is not in the store`); logger.warn(`${roomId} was found in DMs but the room is not in the store`);
continue; continue;
} }
@ -550,7 +550,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
* be used if the calling code will manually trigger the update. * be used if the calling code will manually trigger the update.
*/ */
public regenerateAllLists({ trigger = true }) { public regenerateAllLists({ trigger = true }) {
console.warn("Regenerating all room lists"); logger.warn("Regenerating all room lists");
const rooms = this.getPlausibleRooms(); const rooms = this.getPlausibleRooms();

View file

@ -19,6 +19,8 @@ import GroupFilterOrderStore from "../GroupFilterOrderStore";
import { CommunityFilterCondition } from "./filters/CommunityFilterCondition"; import { CommunityFilterCondition } from "./filters/CommunityFilterCondition";
import { arrayDiff, arrayHasDiff } from "../../utils/arrays"; import { arrayDiff, arrayHasDiff } from "../../utils/arrays";
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Watches for changes in groups to manage filters on the provided RoomListStore * Watches for changes in groups to manage filters on the provided RoomListStore
*/ */
@ -37,7 +39,7 @@ export class TagWatcher {
// Selected tags changed, do some filtering // Selected tags changed, do some filtering
if (!this.store.matrixClient) { if (!this.store.matrixClient) {
console.warn("Tag update without an associated matrix client - ignoring"); logger.warn("Tag update without an associated matrix client - ignoring");
return; return;
} }
@ -47,7 +49,7 @@ export class TagWatcher {
for (const tag of filterableTags) { for (const tag of filterableTags) {
const group = this.store.matrixClient.getGroup(tag); const group = this.store.matrixClient.getGroup(tag);
if (!group) { if (!group) {
console.warn(`Group selected with no group object available: ${tag}`); logger.warn(`Group selected with no group object available: ${tag}`);
continue; continue;
} }

View file

@ -36,6 +36,8 @@ import { getListAlgorithmInstance } from "./list-ordering";
import { VisibilityProvider } from "../filters/VisibilityProvider"; import { VisibilityProvider } from "../filters/VisibilityProvider";
import SpaceStore from "../../SpaceStore"; import SpaceStore from "../../SpaceStore";
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Fired when the Algorithm has determined a list has been updated. * Fired when the Algorithm has determined a list has been updated.
*/ */
@ -126,7 +128,7 @@ export class Algorithm extends EventEmitter {
try { try {
this.updateStickyRoom(val); this.updateStickyRoom(val);
} catch (e) { } catch (e) {
console.warn("Failed to update sticky room", e); logger.warn("Failed to update sticky room", e);
} }
} }
@ -241,7 +243,7 @@ export class Algorithm extends EventEmitter {
// to force the position to zero (top) to ensure we can properly handle it. // to force the position to zero (top) to ensure we can properly handle it.
const wasSticky = this._lastStickyRoom.room ? this._lastStickyRoom.room.roomId === val.roomId : false; const wasSticky = this._lastStickyRoom.room ? this._lastStickyRoom.room.roomId === val.roomId : false;
if (this._lastStickyRoom.tag && tag !== this._lastStickyRoom.tag && wasSticky && position < 0) { if (this._lastStickyRoom.tag && tag !== this._lastStickyRoom.tag && wasSticky && position < 0) {
console.warn(`Sticky room ${val.roomId} changed tags during sticky room handling`); logger.warn(`Sticky room ${val.roomId} changed tags during sticky room handling`);
position = 0; position = 0;
} }
@ -278,13 +280,13 @@ export class Algorithm extends EventEmitter {
if (this._stickyRoom.room !== val) { if (this._stickyRoom.room !== val) {
// Check the room IDs just in case // Check the room IDs just in case
if (this._stickyRoom.room.roomId === val.roomId) { if (this._stickyRoom.room.roomId === val.roomId) {
console.warn("Sticky room changed references"); logger.warn("Sticky room changed references");
} else { } else {
throw new Error("Sticky room changed while the sticky room was changing"); throw new Error("Sticky room changed while the sticky room was changing");
} }
} }
console.warn(`Sticky room changed tag & position from ${tag} / ${position} ` logger.warn(`Sticky room changed tag & position from ${tag} / ${position} `
+ `to ${this._stickyRoom.tag} / ${this._stickyRoom.position}`); + `to ${this._stickyRoom.tag} / ${this._stickyRoom.position}`);
tag = this._stickyRoom.tag; tag = this._stickyRoom.tag;
@ -322,7 +324,7 @@ export class Algorithm extends EventEmitter {
return; return;
} }
console.warn("Recalculating filtered room list"); logger.warn("Recalculating filtered room list");
const filters = Array.from(this.allowedByFilter.keys()); const filters = Array.from(this.allowedByFilter.keys());
const newMap: ITagMap = {}; const newMap: ITagMap = {};
for (const tagId of Object.keys(this.cachedRooms)) { for (const tagId of Object.keys(this.cachedRooms)) {
@ -491,7 +493,7 @@ export class Algorithm extends EventEmitter {
// We only log this if we're expecting to be publishing updates, which means that // We only log this if we're expecting to be publishing updates, which means that
// this could be an unexpected invocation. If we're inhibited, then this is probably // this could be an unexpected invocation. If we're inhibited, then this is probably
// an intentional invocation. // an intentional invocation.
console.warn("Resetting known rooms, initiating regeneration"); logger.warn("Resetting known rooms, initiating regeneration");
} }
// Before we go any further we need to clear (but remember) the sticky room to // Before we go any further we need to clear (but remember) the sticky room to
@ -657,18 +659,18 @@ export class Algorithm extends EventEmitter {
// pass the cause through as NewRoom, we'll fail to lie to the algorithm and thus // pass the cause through as NewRoom, we'll fail to lie to the algorithm and thus
// lose the room. // lose the room.
if (hasTags && !isForLastSticky) { if (hasTags && !isForLastSticky) {
console.warn(`${room.roomId} is reportedly new but is already known - assuming TagChange instead`); logger.warn(`${room.roomId} is reportedly new but is already known - assuming TagChange instead`);
cause = RoomUpdateCause.PossibleTagChange; cause = RoomUpdateCause.PossibleTagChange;
} }
// Check to see if the room is known first // Check to see if the room is known first
let knownRoomRef = this.rooms.includes(room); let knownRoomRef = this.rooms.includes(room);
if (hasTags && !knownRoomRef) { if (hasTags && !knownRoomRef) {
console.warn(`${room.roomId} might be a reference change - attempting to update reference`); logger.warn(`${room.roomId} might be a reference change - attempting to update reference`);
this.rooms = this.rooms.map(r => r.roomId === room.roomId ? room : r); this.rooms = this.rooms.map(r => r.roomId === room.roomId ? room : r);
knownRoomRef = this.rooms.includes(room); knownRoomRef = this.rooms.includes(room);
if (!knownRoomRef) { if (!knownRoomRef) {
console.warn(`${room.roomId} is still not referenced. It may be sticky.`); logger.warn(`${room.roomId} is still not referenced. It may be sticky.`);
} }
} }
@ -766,7 +768,7 @@ export class Algorithm extends EventEmitter {
const tags = this.roomIdsToTags[room.roomId]; const tags = this.roomIdsToTags[room.roomId];
if (!tags) { if (!tags) {
console.warn(`No tags known for "${room.name}" (${room.roomId})`); logger.warn(`No tags known for "${room.name}" (${room.roomId})`);
return false; return false;
} }

View file

@ -23,6 +23,8 @@ import { OrderingAlgorithm } from "./OrderingAlgorithm";
import { NotificationColor } from "../../../notifications/NotificationColor"; import { NotificationColor } from "../../../notifications/NotificationColor";
import { RoomNotificationStateStore } from "../../../notifications/RoomNotificationStateStore"; import { RoomNotificationStateStore } from "../../../notifications/RoomNotificationStateStore";
import { logger } from "matrix-js-sdk/src/logger";
interface ICategorizedRoomMap { interface ICategorizedRoomMap {
// @ts-ignore - TS wants this to be a string, but we know better // @ts-ignore - TS wants this to be a string, but we know better
[category: NotificationColor]: Room[]; [category: NotificationColor]: Room[];
@ -130,7 +132,7 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
} else if (cause === RoomUpdateCause.RoomRemoved) { } else if (cause === RoomUpdateCause.RoomRemoved) {
const roomIdx = this.getRoomIndex(room); const roomIdx = this.getRoomIndex(room);
if (roomIdx === -1) { if (roomIdx === -1) {
console.warn(`Tried to remove unknown room from ${this.tagId}: ${room.roomId}`); logger.warn(`Tried to remove unknown room from ${this.tagId}: ${room.roomId}`);
return false; // no change return false; // no change
} }
const oldCategory = this.getCategoryFromIndices(roomIdx, this.indices); const oldCategory = this.getCategoryFromIndices(roomIdx, this.indices);
@ -263,7 +265,7 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
if (indices[lastCat] > indices[thisCat]) { if (indices[lastCat] > indices[thisCat]) {
// "should never happen" disclaimer goes here // "should never happen" disclaimer goes here
console.warn( logger.warn(
`!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater ` + `!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater ` +
`than ${thisCat} (i:${indices[thisCat]}) - category indices are likely desynced from reality`); `than ${thisCat} (i:${indices[thisCat]}) - category indices are likely desynced from reality`);

View file

@ -20,6 +20,8 @@ import { OrderingAlgorithm } from "./OrderingAlgorithm";
import { RoomUpdateCause, TagID } from "../../models"; import { RoomUpdateCause, TagID } from "../../models";
import { Room } from "matrix-js-sdk/src/models/room"; import { Room } from "matrix-js-sdk/src/models/room";
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Uses the natural tag sorting algorithm order to determine tag ordering. No * Uses the natural tag sorting algorithm order to determine tag ordering. No
* additional behavioural changes are present. * additional behavioural changes are present.
@ -47,7 +49,7 @@ export class NaturalAlgorithm extends OrderingAlgorithm {
if (idx >= 0) { if (idx >= 0) {
this.cachedOrderedRooms.splice(idx, 1); this.cachedOrderedRooms.splice(idx, 1);
} else { } else {
console.warn(`Tried to remove unknown room from ${this.tagId}: ${room.roomId}`); logger.warn(`Tried to remove unknown room from ${this.tagId}: ${room.roomId}`);
} }
} }

View file

@ -18,6 +18,8 @@ import { Room } from "matrix-js-sdk/src/models/room";
import { RoomUpdateCause, TagID } from "../../models"; import { RoomUpdateCause, TagID } from "../../models";
import { SortAlgorithm } from "../models"; import { SortAlgorithm } from "../models";
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Represents a list ordering algorithm. Subclasses should populate the * Represents a list ordering algorithm. Subclasses should populate the
* `cachedOrderedRooms` field. * `cachedOrderedRooms` field.
@ -71,7 +73,7 @@ export abstract class OrderingAlgorithm {
protected getRoomIndex(room: Room): number { protected getRoomIndex(room: Room): number {
let roomIdx = this.cachedOrderedRooms.indexOf(room); let roomIdx = this.cachedOrderedRooms.indexOf(room);
if (roomIdx === -1) { // can only happen if the js-sdk's store goes sideways. if (roomIdx === -1) { // can only happen if the js-sdk's store goes sideways.
console.warn(`Degrading performance to find missing room in "${this.tagId}": ${room.roomId}`); logger.warn(`Degrading performance to find missing room in "${this.tagId}": ${room.roomId}`);
roomIdx = this.cachedOrderedRooms.findIndex(r => r.roomId === room.roomId); roomIdx = this.cachedOrderedRooms.findIndex(r => r.roomId === room.roomId);
} }
return roomIdx; return roomIdx;

View file

@ -20,6 +20,8 @@ import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixClientPeg } from '../MatrixClientPeg'; import { MatrixClientPeg } from '../MatrixClientPeg';
import { logger } from "matrix-js-sdk/src/logger";
/** /**
* Class that takes a Matrix Client and flips the m.direct map * Class that takes a Matrix Client and flips the m.direct map
* so the operation of mapping a room ID to which user it's a DM * so the operation of mapping a room ID to which user it's a DM
@ -196,7 +198,7 @@ export default class DMRoomMap {
// to avoid multiple devices fighting to correct // to avoid multiple devices fighting to correct
// the account data, only try to send the corrected // the account data, only try to send the corrected
// version once. // version once.
console.warn(`Invalid m.direct account data detected ` + logger.warn(`Invalid m.direct account data detected ` +
`(self-chats that shouldn't be), patching it up.`); `(self-chats that shouldn't be), patching it up.`);
if (neededPatching && !this.hasSentOutPatchDirectAccountDataPatch) { if (neededPatching && !this.hasSentOutPatchDirectAccountDataPatch) {
this.hasSentOutPatchDirectAccountDataPatch = true; this.hasSentOutPatchDirectAccountDataPatch = true;

View file

@ -41,7 +41,7 @@ function safariVersionCheck(ua: string): boolean {
} catch (err) { } catch (err) {
logger.error("Error in Safari COLR version check", err); logger.error("Error in Safari COLR version check", err);
} }
console.warn("Couldn't determine Safari version to check COLR font support, assuming no."); logger.warn("Couldn't determine Safari version to check COLR font support, assuming no.");
return false; return false;
} }

View file

@ -22,6 +22,8 @@ import { IMediaEventContent } from "../customisations/models/IMediaEventContent"
import { IDestroyable } from "./IDestroyable"; import { IDestroyable } from "./IDestroyable";
import { EventType, MsgType } from "matrix-js-sdk/src/@types/event"; import { EventType, MsgType } from "matrix-js-sdk/src/@types/event";
import { logger } from "matrix-js-sdk/src/logger";
// TODO: We should consider caching the blobs. https://github.com/vector-im/element-web/issues/17192 // TODO: We should consider caching the blobs. https://github.com/vector-im/element-web/issues/17192
export class MediaEventHelper implements IDestroyable { export class MediaEventHelper implements IDestroyable {
@ -91,7 +93,7 @@ export class MediaEventHelper implements IDestroyable {
return decryptFile(content.info.thumbnail_file, content.info.thumbnail_info); return decryptFile(content.info.thumbnail_file, content.info.thumbnail_info);
} else { } else {
// "Should never happen" // "Should never happen"
console.warn("Media claims to have thumbnail and is encrypted, but no thumbnail_file found"); logger.warn("Media claims to have thumbnail and is encrypted, but no thumbnail_file found");
return Promise.resolve(null); return Promise.resolve(null);
} }
} }

View file

@ -22,6 +22,8 @@ import { IContent } from "matrix-js-sdk/src/models/event";
import { bodyToHtml, checkBlockNode, IOptsReturnString } from "../HtmlUtils"; import { bodyToHtml, checkBlockNode, IOptsReturnString } from "../HtmlUtils";
import { logger } from "matrix-js-sdk/src/logger";
const decodeEntities = (function() { const decodeEntities = (function() {
let textarea = null; let textarea = null;
return function(str: string): string { return function(str: string): string {
@ -218,7 +220,7 @@ function renderDifferenceInDOM(originalRootNode: Node, diff: IDiff, diffMathPatc
} }
default: default:
// Should not happen (modifyComment, ???) // Should not happen (modifyComment, ???)
console.warn("MessageDiffUtils::editBodyDiffToHtml: diff action not supported atm", diff); logger.warn("MessageDiffUtils::editBodyDiffToHtml: diff action not supported atm", diff);
} }
} }

View file

@ -219,7 +219,7 @@ export default class MultiInviter {
case "M_PROFILE_NOT_FOUND": case "M_PROFILE_NOT_FOUND":
if (!ignoreProfile) { if (!ignoreProfile) {
// Invite without the profile check // Invite without the profile check
console.warn(`User ${address} does not have a profile - inviting anyways automatically`); logger.warn(`User ${address} does not have a profile - inviting anyways automatically`);
this.doInvite(address, true).then(resolve, reject); this.doInvite(address, true).then(resolve, reject);
return; return;
} }

View file

@ -138,7 +138,7 @@ export async function upgradeRoom(
} }
} catch (e) { } catch (e) {
// These errors are not critical to the room upgrade itself // These errors are not critical to the room upgrade itself
console.warn("Failed to update parent spaces during room upgrade", e); logger.warn("Failed to update parent spaces during room upgrade", e);
} }
} }

View file

@ -55,30 +55,30 @@ export default class WidgetUtils {
*/ */
static canUserModifyWidgets(roomId: string): boolean { static canUserModifyWidgets(roomId: string): boolean {
if (!roomId) { if (!roomId) {
console.warn('No room ID specified'); logger.warn('No room ID specified');
return false; return false;
} }
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.get();
if (!client) { if (!client) {
console.warn('User must be be logged in'); logger.warn('User must be be logged in');
return false; return false;
} }
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
if (!room) { if (!room) {
console.warn(`Room ID ${roomId} is not recognised`); logger.warn(`Room ID ${roomId} is not recognised`);
return false; return false;
} }
const me = client.credentials.userId; const me = client.credentials.userId;
if (!me) { if (!me) {
console.warn('Failed to get user ID'); logger.warn('Failed to get user ID');
return false; return false;
} }
if (room.getMyMembership() !== "join") { if (room.getMyMembership() !== "join") {
console.warn(`User ${me} is not in room ${roomId}`); logger.warn(`User ${me} is not in room ${roomId}`);
return false; return false;
} }

View file

@ -28,6 +28,8 @@ import ElementPermalinkConstructor from "./ElementPermalinkConstructor";
import matrixLinkify from "../../linkify-matrix"; import matrixLinkify from "../../linkify-matrix";
import SdkConfig from "../../SdkConfig"; import SdkConfig from "../../SdkConfig";
import { logger } from "matrix-js-sdk/src/logger";
// The maximum number of servers to pick when working out which servers // The maximum number of servers to pick when working out which servers
// to add to permalinks. The servers are appended as ?via=example.org // to add to permalinks. The servers are appended as ?via=example.org
const MAX_SERVER_CANDIDATES = 3; const MAX_SERVER_CANDIDATES = 3;
@ -109,7 +111,7 @@ export class RoomPermalinkCreator {
// currentState, at least potentially at the early stages of joining a room. // currentState, at least potentially at the early stages of joining a room.
// To avoid breaking everything, we'll just warn rather than throw as well as // To avoid breaking everything, we'll just warn rather than throw as well as
// not bother updating the various aspects of the share link. // not bother updating the various aspects of the share link.
console.warn("Tried to load a permalink creator with no room state"); logger.warn("Tried to load a permalink creator with no room state");
return; return;
} }
this.updateAllowedServers(); this.updateAllowedServers();