Replace console.warn with logger.warn

Related https://github.com/vector-im/element-web/issues/18425
pull/21833/head
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 RoomViewStore from './stores/RoomViewStore';
import { logger } from "matrix-js-sdk/src/logger";
type Listener = (isActive: boolean) => void;
/**
@ -54,7 +56,7 @@ export class ActiveRoomObserver {
this.listeners[roomId].splice(i, 1);
}
} 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
const match = hashRegex.exec(hash);
if (!match) {
console.warn(`Unexpected hash location "${hash}"`);
logger.warn(`Unexpected hash location "${hash}"`);
return '#/<unexpected hash location>';
}
@ -322,7 +322,7 @@ export class Analytics {
}
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
}

View File

@ -61,7 +61,7 @@ export default class AsyncWrapper extends React.Component<IProps, IState> {
: result as ComponentType;
this.setState({ component });
}).catch((e) => {
console.warn('AsyncWrapper promise failed', e);
logger.warn('AsyncWrapper promise failed', 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) {
const startTime = CountlyAnalytics.getTimestamp();
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;
});
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, false, false, { msgtype: "m.sticker" });

View File

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

View File

@ -111,7 +111,7 @@ export async function loadSession(opts: ILoadSessionOpts = {}): Promise<boolean>
const defaultDeviceDisplayName = opts.defaultDeviceDisplayName;
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;
}
@ -188,7 +188,7 @@ export function attemptTokenLogin(
const homeserver = localStorage.getItem(SSO_HOMESERVER_URL_KEY);
const identityServer = localStorage.getItem(SSO_ID_SERVER_URL_KEY);
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, {
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, " +
@ -523,7 +523,7 @@ export function hydrateSession(credentials: IMatrixClientCreds): Promise<MatrixC
const overwrite = credentials.userId !== oldUserId || credentials.deviceId !== oldDeviceId;
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);
@ -602,10 +602,10 @@ async function doSetLoggedIn(
// make sure we don't think that it's a fresh login any more
sessionStorage.removeItem("mx_fresh_login");
} 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 {
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' });
@ -650,7 +650,7 @@ async function persistCredentials(credentials: IMatrixClientCreds): Promise<void
encryptedAccessToken = await encryptAES(credentials.accessToken, encrKey, "access_token");
encrKey.fill(0);
} catch (e) {
console.warn("Could not encrypt access token", e);
logger.warn("Could not encrypt access token", e);
}
try {
// 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 MatrixClientPeg.start();
} else {
console.warn("Caller requested only auxiliary services be started");
logger.warn("Caller requested only auxiliary services be started");
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
// 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);

View File

@ -20,6 +20,8 @@ import { SettingLevel } from "./settings/SettingLevel";
import EventEmitter from 'events';
import { MatrixClientPeg } from "./MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
// XXX: MediaDeviceKind is a union type, so we make our own enum
export enum MediaDeviceKindEnum {
AudioOutput = "audiooutput",
@ -63,7 +65,7 @@ export default class MediaDeviceHandler extends EventEmitter {
devices.forEach((device) => output[device.kind].push(device));
return output;
} 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) {
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;
}
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;
}
@ -181,7 +181,7 @@ export const Notifier = {
}
await audioElement.play();
} 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);
break;
default:
console.warn("Unhandled postMessage event with action '" + event.data.action +"'");
logger.warn("Unhandled postMessage event with action '" + event.data.action +"'");
break;
}
};

View File

@ -283,7 +283,7 @@ async function onSecretRequested(
}
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 = {
@ -388,7 +388,7 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f
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");
logger.warn("Not setting dehydration key: no SSSS key found");
} else {
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 EditorModel from "./editor/model";
import { logger } from "matrix-js-sdk/src/logger";
interface IHistoryItem {
parts: SerializedPart[];
replyEventId?: string;
@ -42,7 +44,7 @@ export default class SendHistoryManager {
try {
this.history.push(JSON.parse(itemJSON));
} catch (e) {
console.warn("Throwing away unserialisable history", e);
logger.warn("Throwing away unserialisable history", e);
break;
}
++index;

View File

@ -27,6 +27,8 @@ import { SetRightPanelPhasePayload } from './dispatcher/payloads/SetRightPanelPh
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { MatrixClientPeg } from "./MatrixClientPeg";
import { logger } from "matrix-js-sdk/src/logger";
// 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
// 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;
}
} 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 });
}
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
// very well.
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);

View File

@ -26,6 +26,8 @@ import { isVoiceMessage } from "../utils/EventUtils";
import RoomViewStore from "../stores/RoomViewStore";
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
* was at for each playback, what order the playbacks were played in, and triggers subsequent
@ -114,7 +116,7 @@ export class PlaybackQueue {
if (next) {
const instance = this.playbacks.get(next);
if (!instance) {
console.warn(
logger.warn(
"Voice message queue desync: Missing playback for next message: "
+ `Current=${this.currentPlaybackId} Last=${last} Next=${next}`,
);
@ -173,7 +175,7 @@ export class PlaybackQueue {
}
}
} else {
console.warn(
logger.warn(
"Voice message queue desync: Expected playback stop to be last in order. "
+ `Current=${this.currentPlaybackId} Last=${last} EventID=${mxEvent.getId()}`,
);

View File

@ -27,6 +27,8 @@ import MatrixClientContext from "../../contexts/MatrixClientContext";
import AutoHideScrollbar from "./AutoHideScrollbar";
import { ActionPayload } from "../../dispatcher/payloads";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
// URL to request embedded page content from
url?: string;
@ -79,7 +81,7 @@ export default class EmbeddedPage extends React.PureComponent<IProps, IState> {
}
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") });
return;
}

View File

@ -917,7 +917,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
let waitFor = Promise.resolve(null);
if (!this.firstSyncComplete) {
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;
}
waitFor = this.firstSyncPromise.promise;
@ -973,7 +973,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// Wait for the first sync to complete
if (!this.firstSyncComplete) {
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;
}
await this.firstSyncPromise.promise;
@ -1475,7 +1475,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
Modal.closeCurrentModal('Session.logged_out');
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();
return;
}

View File

@ -133,7 +133,7 @@ export default class RoomDirectory extends React.Component<IProps, IState> {
}
this.setState({ protocolsLoading: false });
}, (err) => {
console.warn(`error loading third party protocols: ${err}`);
logger.warn(`error loading third party protocols: ${err}`);
this.setState({ protocolsLoading: false });
if (MatrixClientPeg.get().isGuest()) {
// 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
// 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;
@ -1266,7 +1266,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// Somehow, it seems to be possible for live events to not have
// a timeline, even though that should not happen. :(
// https://github.com/vector-im/element-web/issues/12120
console.warn(
logger.warn(
`Event ${events[i].getId()} in room ${room.roomId} is live, ` +
`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);
viaMap.set(roomId, servers);
} 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 />`
+ groupSummary.profile.long_description,
} 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);

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.
// We'll try to log something in an vain attempt to record what happened (storage
// 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") });
}).catch(e => {
if (e && e.httpStatus === 401 && e.data) {

View File

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

View File

@ -33,6 +33,8 @@ import {
} from "./HostSignupDialogTypes";
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
const HOST_SIGNUP_KEY = "host_signup";
interface IProps {}
@ -146,7 +148,7 @@ export default class HostSignupDialog extends React.PureComponent<IProps, IState
private async sendAccountDetails() {
const openIdToken = await MatrixClientPeg.get().getOpenIdToken();
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({
completed: true,
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) {
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;
}
}
@ -479,7 +479,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
for (const userId in rooms) {
// Filter out user IDs that are already in the room / should be excluded
if (excludedTargetIds.has(userId)) {
console.warn(`[Invite:Recents] Excluding ${userId} from recents`);
logger.warn(`[Invite:Recents] Excluding ${userId} from recents`);
continue;
}
@ -487,7 +487,7 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
const member = room.getMember(userId);
if (!member) {
// 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;
}
@ -507,13 +507,13 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
}
if (!lastEventTs) {
// 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;
}
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
recents.sort((a, b) => b.lastActive - a.lastActive);
@ -873,8 +873,8 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
});
}
} catch (e) {
console.warn("Non-fatal error trying to make an invite for a user ID");
console.warn(e);
logger.warn("Non-fatal error trying to make an invite for a user ID");
logger.warn(e);
// Add a result anyways, just without a profile. We stick it at the
// 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 childContentProtocol = u.protocol;
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);
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: 'stickerpicker_close' });
} else {
console.warn('Ignoring sticker message. Invalid capability');
logger.warn('Ignoring sticker message. Invalid capability');
}
break;
}

View File

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

View File

@ -20,6 +20,8 @@ import ICanvasEffect from '../../../effects/ICanvasEffect';
import { CHAT_EFFECTS } from '../../../effects';
import UIStore, { UI_EVENTS } from "../../../stores/UIStore";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
roomWidth: number;
}
@ -38,7 +40,7 @@ const EffectsOverlay: FunctionComponent<IProps> = ({ roomWidth }) => {
effect = new Effect(options);
effectsRef.current[name] = effect;
} 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;

View File

@ -33,6 +33,8 @@ import SettingsStore from "../../../settings/SettingsStore";
import { mediaFromMxc } from "../../../customisations/Media";
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 thing to click on for the user to filter the visible rooms in the RoomList to:
// - Rooms that are part of the group
@ -85,7 +87,7 @@ export default class TagTile extends React.Component {
if (this.unmounted) return;
this.setState({ profile });
}).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 { PlaybackQueue } from "../../../audio/PlaybackQueue";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
error?: Error;
playback?: Playback;
@ -49,12 +51,12 @@ export default class MAudioBody extends React.PureComponent<IBodyProps, IState>
buffer = await blob.arrayBuffer();
} catch (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
}
} catch (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
}

View File

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

View File

@ -34,6 +34,8 @@ import { IBodyProps } from "./IBodyProps";
import classNames from 'classnames';
import { CSSTransition, SwitchTransition } from 'react-transition-group';
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
decryptedUrl?: string;
decryptedThumbnailUrl?: string;
@ -275,7 +277,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
});
} catch (err) {
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.
this.setState({
error: err,

View File

@ -180,7 +180,7 @@ export default class MVideoBody extends React.PureComponent<IBodyProps, IState>
});
}
} 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.
this.setState({
error: err,

View File

@ -236,7 +236,7 @@ export default class VerificationPanel extends React.PureComponent<IProps, IStat
if (!device) {
// This can happen if the device is logged out while we're still showing verification
// 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!");
} else {
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 { MessagePreviewStore } from '../../../stores/room-list/MessagePreviewStore';
import { logger } from "matrix-js-sdk/src/logger";
const eventTileTypes = {
[EventType.RoomMessage]: 'messages.MessageEvent',
[EventType.Sticker]: 'messages.MessageEvent',
@ -974,7 +976,7 @@ export default class EventTile extends React.Component<IProps, IState> {
// before trying to instantiate us
if (!tileHandler) {
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">
<div className="mx_EventTile_line">
{ _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 { 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 INITIAL_LOAD_NUM_MEMBERS = 30;
@ -184,7 +186,7 @@ export default class MemberList extends React.Component<IProps, IState> {
try {
searchQuery = window.localStorage.getItem(getSearchQueryLSKey(this.props.roomId));
} 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
@ -433,7 +435,7 @@ export default class MemberList extends React.Component<IProps, IState> {
try {
window.localStorage.setItem(getSearchQueryLSKey(this.props.roomId), searchQuery);
} 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({

View File

@ -26,6 +26,8 @@ import { replaceableComponent } from "../../../utils/replaceableComponent";
import MemberAvatar from '../avatars/MemberAvatar';
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
// the RoomMember to show the RR for
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
// the docs for `offsetParent` say it may be null if `display` is
// `none`, but I can't see why that would happen.
console.warn(
logger.warn(
`ReadReceiptMarker for ${this.props.fallbackUserId} in has no offsetParent`,
);
startTopOffset = 0;

View File

@ -29,6 +29,8 @@ import { getEventDisplayInfo, isVoiceMessage } from '../../../utils/EventUtils';
import MFileBody from "../messages/MFileBody";
import MVoiceMessageBody from "../messages/MVoiceMessageBody";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
mxEvent: MatrixEvent;
permalinkCreator?: RoomPermalinkCreator;
@ -107,7 +109,7 @@ export default class ReplyTile extends React.PureComponent<IProps> {
// before trying to instantiate us
if (!tileHandler) {
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">
{ _t('This event could not be displayed') }
</div>;

View File

@ -50,6 +50,8 @@ import IconizedContextMenu, {
import { CommunityPrototypeStore, IRoomProfile } from "../../../stores/CommunityPrototypeStore";
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
room: Room;
showMessagePreview: boolean;
@ -299,7 +301,7 @@ export default class RoomTile extends React.PureComponent<IProps, IState> {
0,
));
} 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) {

View File

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

View File

@ -27,6 +27,8 @@ import { isUrlPermitted } from '../../../HtmlUtils';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { mediaFromMxc } from "../../../customisations/Media";
import { logger } from "matrix-js-sdk/src/logger";
interface IProps {
ev: MatrixEvent;
room: Room;
@ -75,13 +77,13 @@ export default class BridgeTile extends React.PureComponent<IProps> {
const content: IBridgeStateEvent = this.props.ev.getContent();
// Validate
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;
}
if (!content.bridgebot) {
// 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.
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.");
content.bridgebot = this.props.ev.getSender();
}

View File

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

View File

@ -168,11 +168,11 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
threepids = await getThreepidsWithBindStatus(cli);
} catch (e) {
const idServerUrl = MatrixClientPeg.get().getIdentityServerUrl();
console.warn(
logger.warn(
`Unable to reach identity server at ${idServerUrl} to check ` +
`for 3PIDs bindings in Settings`,
);
console.warn(e);
logger.warn(e);
}
this.setState({
emails: threepids.filter((a) => a.medium === 'email'),
@ -218,11 +218,11 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
},
});
} catch (e) {
console.warn(
logger.warn(
`Unable to reach identity server at ${idServerUrl} to check ` +
`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 InlineSpinner from "../../../elements/InlineSpinner";
import { logger } from "matrix-js-sdk/src/logger";
interface IIgnoredUserProps {
userId: string;
onUnignored: (userId: string) => void;
@ -174,7 +176,7 @@ export default class SecurityUserSettingsTab extends React.Component<IProps, ISt
i--;
} else {
// 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).
// 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") {
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;
return client.createRoom(createOpts);
} else {

View File

@ -583,7 +583,7 @@ export default class EventIndex extends EventEmitter {
if (eventId) {
await indexManager.deleteEvent(eventId);
} 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();
} catch (e) {
logger.error(e);
console.warn("Failed to locate integration manager");
logger.warn("Failed to locate integration manager");
return null;
}
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;
}
const widget = wkConfig["m.integrations_widget"];
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;
}

View File

@ -89,11 +89,11 @@ function safeCounterpartTranslate(text: string, options?: object) {
count = options['count'];
Object.keys(options).forEach((k) => {
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';
}
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';
}
});

View File

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

View File

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

View File

@ -23,6 +23,8 @@ import { SettingLevel } from "../SettingLevel";
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
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
// default action on this rule is dont_notify, but it could be something else
export function isPushNotifyDisabled(): boolean {
@ -31,7 +33,7 @@ export function isPushNotifyDisabled(): boolean {
const masterRule = processor.getPushRuleById(".m.rule.master");
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;
}

View File

@ -17,6 +17,8 @@ limitations under the License.
import SettingsHandler from "./SettingsHandler";
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
// 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) {
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 { isNullOrUndefined } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";
interface IState {
// 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
await this.matrixClient.setAccountData("im.vector.group_info." + room.roomId, profile);
} 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") {

View File

@ -98,7 +98,7 @@ class FlairStore extends EventEmitter {
}).catch((err) => {
// Indicate whether the homeserver supports groups
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;
// Return silently to avoid spamming for non-supporting servers
return;

View File

@ -23,6 +23,8 @@ import { ActionPayload } from "../dispatcher/payloads";
import { Action } from '../dispatcher/actions';
import { SettingLevel } from "../settings/SettingLevel";
import { logger } from "matrix-js-sdk/src/logger";
interface RightPanelStoreState {
// 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.
@ -180,7 +182,7 @@ export default class RightPanelStore extends Store<ActionPayload> {
}
}
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;
}

View File

@ -867,7 +867,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient<IState> {
try {
await this.matrixClient.setRoomAccountData(space.roomId, EventType.SpaceOrder, { order });
} 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) {
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
const existingApp = this.widgetMap.get(widgetUid(app));
if (existingApp) {
console.warn(
logger.warn(
`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`,
);

View File

@ -20,6 +20,8 @@ import { AsyncStoreWithClient } from "../AsyncStoreWithClient";
import defaultDispatcher from "../../dispatcher/dispatcher";
import { ActionPayload } from "../../dispatcher/payloads";
import { logger } from "matrix-js-sdk/src/logger";
interface 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.
public async resetLayouts() {
console.warn("Resetting layouts for room list");
logger.warn("Resetting layouts for room list");
for (const layout of this.layoutMap.values()) {
layout.reset();
}

View File

@ -162,7 +162,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
} else if (activeRoomId) {
const activeRoom = this.matrixClient.getRoom(activeRoomId);
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);
} else if (activeRoom !== this.algorithm.stickyRoom) {
this.algorithm.setStickyRoom(activeRoom);
@ -226,7 +226,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
if (readReceiptChangeIsFor(payload.event, this.matrixClient)) {
const room = payload.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;
}
await this.handleRoomUpdate(room, RoomUpdateCause.ReadReceipt);
@ -258,8 +258,8 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
this.updateFn.trigger();
};
if (!room) {
console.warn(`Live timeline event ${eventPayload.event.getId()} received without associated room`);
console.warn(`Queuing failed room update for retry as a result.`);
logger.warn(`Live timeline event ${eventPayload.event.getId()} received without associated room`);
logger.warn(`Queuing failed room update for retry as a result.`);
setTimeout(async () => {
const updatedRoom = this.matrixClient.getRoom(roomId);
await tryUpdate(updatedRoom);
@ -276,7 +276,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
}
const room = this.matrixClient.getRoom(roomId);
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;
}
await this.handleRoomUpdate(room, RoomUpdateCause.Timeline);
@ -289,7 +289,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
for (const roomId of roomIds) {
const room = this.matrixClient.getRoom(roomId);
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;
}
@ -550,7 +550,7 @@ export class RoomListStoreClass extends AsyncStoreWithClient<IState> {
* be used if the calling code will manually trigger the update.
*/
public regenerateAllLists({ trigger = true }) {
console.warn("Regenerating all room lists");
logger.warn("Regenerating all room lists");
const rooms = this.getPlausibleRooms();

View File

@ -19,6 +19,8 @@ import GroupFilterOrderStore from "../GroupFilterOrderStore";
import { CommunityFilterCondition } from "./filters/CommunityFilterCondition";
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
*/
@ -37,7 +39,7 @@ export class TagWatcher {
// Selected tags changed, do some filtering
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;
}
@ -47,7 +49,7 @@ export class TagWatcher {
for (const tag of filterableTags) {
const group = this.store.matrixClient.getGroup(tag);
if (!group) {
console.warn(`Group selected with no group object available: ${tag}`);
logger.warn(`Group selected with no group object available: ${tag}`);
continue;
}

View File

@ -36,6 +36,8 @@ import { getListAlgorithmInstance } from "./list-ordering";
import { VisibilityProvider } from "../filters/VisibilityProvider";
import SpaceStore from "../../SpaceStore";
import { logger } from "matrix-js-sdk/src/logger";
/**
* Fired when the Algorithm has determined a list has been updated.
*/
@ -126,7 +128,7 @@ export class Algorithm extends EventEmitter {
try {
this.updateStickyRoom(val);
} 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.
const wasSticky = this._lastStickyRoom.room ? this._lastStickyRoom.room.roomId === val.roomId : false;
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;
}
@ -278,13 +280,13 @@ export class Algorithm extends EventEmitter {
if (this._stickyRoom.room !== val) {
// Check the room IDs just in case
if (this._stickyRoom.room.roomId === val.roomId) {
console.warn("Sticky room changed references");
logger.warn("Sticky room changed references");
} else {
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}`);
tag = this._stickyRoom.tag;
@ -322,7 +324,7 @@ export class Algorithm extends EventEmitter {
return;
}
console.warn("Recalculating filtered room list");
logger.warn("Recalculating filtered room list");
const filters = Array.from(this.allowedByFilter.keys());
const newMap: ITagMap = {};
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
// this could be an unexpected invocation. If we're inhibited, then this is probably
// 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
@ -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
// lose the room.
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;
}
// Check to see if the room is known first
let knownRoomRef = this.rooms.includes(room);
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);
knownRoomRef = this.rooms.includes(room);
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];
if (!tags) {
console.warn(`No tags known for "${room.name}" (${room.roomId})`);
logger.warn(`No tags known for "${room.name}" (${room.roomId})`);
return false;
}

View File

@ -23,6 +23,8 @@ import { OrderingAlgorithm } from "./OrderingAlgorithm";
import { NotificationColor } from "../../../notifications/NotificationColor";
import { RoomNotificationStateStore } from "../../../notifications/RoomNotificationStateStore";
import { logger } from "matrix-js-sdk/src/logger";
interface ICategorizedRoomMap {
// @ts-ignore - TS wants this to be a string, but we know better
[category: NotificationColor]: Room[];
@ -130,7 +132,7 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
} else if (cause === RoomUpdateCause.RoomRemoved) {
const roomIdx = this.getRoomIndex(room);
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
}
const oldCategory = this.getCategoryFromIndices(roomIdx, this.indices);
@ -263,7 +265,7 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
if (indices[lastCat] > indices[thisCat]) {
// "should never happen" disclaimer goes here
console.warn(
logger.warn(
`!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater ` +
`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 { 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
* additional behavioural changes are present.
@ -47,7 +49,7 @@ export class NaturalAlgorithm extends OrderingAlgorithm {
if (idx >= 0) {
this.cachedOrderedRooms.splice(idx, 1);
} 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 { SortAlgorithm } from "../models";
import { logger } from "matrix-js-sdk/src/logger";
/**
* Represents a list ordering algorithm. Subclasses should populate the
* `cachedOrderedRooms` field.
@ -71,7 +73,7 @@ export abstract class OrderingAlgorithm {
protected getRoomIndex(room: Room): number {
let roomIdx = this.cachedOrderedRooms.indexOf(room);
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);
}
return roomIdx;

View File

@ -20,6 +20,8 @@ import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixClientPeg } from '../MatrixClientPeg';
import { logger } from "matrix-js-sdk/src/logger";
/**
* 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
@ -196,7 +198,7 @@ export default class DMRoomMap {
// to avoid multiple devices fighting to correct
// the account data, only try to send the corrected
// 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.`);
if (neededPatching && !this.hasSentOutPatchDirectAccountDataPatch) {
this.hasSentOutPatchDirectAccountDataPatch = true;

View File

@ -41,7 +41,7 @@ function safariVersionCheck(ua: string): boolean {
} catch (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;
}

View File

@ -22,6 +22,8 @@ import { IMediaEventContent } from "../customisations/models/IMediaEventContent"
import { IDestroyable } from "./IDestroyable";
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
export class MediaEventHelper implements IDestroyable {
@ -91,7 +93,7 @@ export class MediaEventHelper implements IDestroyable {
return decryptFile(content.info.thumbnail_file, content.info.thumbnail_info);
} else {
// "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);
}
}

View File

@ -22,6 +22,8 @@ import { IContent } from "matrix-js-sdk/src/models/event";
import { bodyToHtml, checkBlockNode, IOptsReturnString } from "../HtmlUtils";
import { logger } from "matrix-js-sdk/src/logger";
const decodeEntities = (function() {
let textarea = null;
return function(str: string): string {
@ -218,7 +220,7 @@ function renderDifferenceInDOM(originalRootNode: Node, diff: IDiff, diffMathPatc
}
default:
// 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":
if (!ignoreProfile) {
// 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);
return;
}

View File

@ -138,7 +138,7 @@ export async function upgradeRoom(
}
} catch (e) {
// 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 {
if (!roomId) {
console.warn('No room ID specified');
logger.warn('No room ID specified');
return false;
}
const client = MatrixClientPeg.get();
if (!client) {
console.warn('User must be be logged in');
logger.warn('User must be be logged in');
return false;
}
const room = client.getRoom(roomId);
if (!room) {
console.warn(`Room ID ${roomId} is not recognised`);
logger.warn(`Room ID ${roomId} is not recognised`);
return false;
}
const me = client.credentials.userId;
if (!me) {
console.warn('Failed to get user ID');
logger.warn('Failed to get user ID');
return false;
}
if (room.getMyMembership() !== "join") {
console.warn(`User ${me} is not in room ${roomId}`);
logger.warn(`User ${me} is not in room ${roomId}`);
return false;
}

View File

@ -28,6 +28,8 @@ import ElementPermalinkConstructor from "./ElementPermalinkConstructor";
import matrixLinkify from "../../linkify-matrix";
import SdkConfig from "../../SdkConfig";
import { logger } from "matrix-js-sdk/src/logger";
// The maximum number of servers to pick when working out which servers
// to add to permalinks. The servers are appended as ?via=example.org
const MAX_SERVER_CANDIDATES = 3;
@ -109,7 +111,7 @@ export class RoomPermalinkCreator {
// 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
// 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;
}
this.updateAllowedServers();