Use MatrixClientPeg::safeGet in src/{stores,hooks,components/structures}/* (#10988)

This commit is contained in:
Michael Telatynski 2023-06-15 15:11:49 +01:00 committed by GitHub
parent 707fd9ccf0
commit dd46db4817
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
34 changed files with 139 additions and 130 deletions

View file

@ -74,7 +74,7 @@ class FilePanel extends React.Component<IProps, IState> {
if (room?.roomId !== this.props.roomId) return;
if (toStartOfTimeline || !data || !data.liveEvent || ev.isRedacted()) return;
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
client.decryptEventIfNeeded(ev);
if (ev.isBeingDecrypted()) {
@ -109,11 +109,11 @@ class FilePanel extends React.Component<IProps, IState> {
}
public async componentDidMount(): Promise<void> {
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
await this.updateTimelineSet(this.props.roomId);
if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;
if (!client.isRoomEncrypted(this.props.roomId)) return;
// The timelineSets filter makes sure that encrypted events that contain
// URLs never get added to the timeline, even if they are live events.
@ -133,7 +133,7 @@ class FilePanel extends React.Component<IProps, IState> {
const client = MatrixClientPeg.get();
if (client === null) return;
if (!MatrixClientPeg.get().isRoomEncrypted(this.props.roomId)) return;
if (!client.isRoomEncrypted(this.props.roomId)) return;
if (EventIndexPeg.get() !== null) {
client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);
@ -142,9 +142,9 @@ class FilePanel extends React.Component<IProps, IState> {
}
public async fetchFileEventsServer(room: Room): Promise<EventTimelineSet> {
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
const filter = new Filter(client.credentials.userId);
const filter = new Filter(client.getSafeUserId());
filter.setDefinition({
room: {
timeline: {
@ -163,7 +163,7 @@ class FilePanel extends React.Component<IProps, IState> {
direction: Direction,
limit: number,
): Promise<boolean> => {
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
const eventIndex = EventIndexPeg.get();
const roomId = this.props.roomId;
@ -185,7 +185,7 @@ class FilePanel extends React.Component<IProps, IState> {
};
public async updateTimelineSet(roomId: string): Promise<void> {
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
const room = client.getRoom(roomId);
const eventIndex = EventIndexPeg.get();
@ -221,7 +221,7 @@ class FilePanel extends React.Component<IProps, IState> {
}
public render(): React.ReactNode {
if (MatrixClientPeg.get().isGuest()) {
if (MatrixClientPeg.safeGet().isGuest()) {
return (
<BaseCard className="mx_FilePanel mx_RoomView_messageListWrapper" onClose={this.props.onClose}>
<div className="mx_RoomView_empty">
@ -256,7 +256,7 @@ class FilePanel extends React.Component<IProps, IState> {
</div>
);
const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.get().isRoomEncrypted(this.props.roomId);
const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.safeGet().isRoomEncrypted(this.props.roomId);
if (this.state.timelineSet) {
return (

View file

@ -129,7 +129,7 @@ export default class LegacyCallEventGrouper extends EventEmitter {
public get callWasMissed(): boolean {
return (
this.state === CallState.Ended &&
![...this.events].some((event) => event.sender?.userId === MatrixClientPeg.get().getUserId())
![...this.events].some((event) => event.sender?.userId === MatrixClientPeg.safeGet().getUserId())
);
}

View file

@ -32,6 +32,7 @@ import { throttle } from "lodash";
import { CryptoEvent } from "matrix-js-sdk/src/crypto";
import { RoomType } from "matrix-js-sdk/src/@types/event";
import { DecryptionError } from "matrix-js-sdk/src/crypto/algorithms";
import { IKeyBackupInfo } from "matrix-js-sdk/src/crypto/keybackup";
// focus-visible is a Polyfill for the :focus-visible CSS pseudo-attribute used by various components
import "focus-visible";
@ -355,7 +356,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
private async postLoginSetup(): Promise<void> {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const cryptoEnabled = cli.isCryptoEnabled();
if (!cryptoEnabled) {
this.onLoggedIn();
@ -574,11 +575,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
if (payload.event_type === "m.identity_server") {
const fullUrl = payload.event_content ? payload.event_content["base_url"] : null;
if (!fullUrl) {
MatrixClientPeg.get().setIdentityServerUrl(undefined);
MatrixClientPeg.safeGet().setIdentityServerUrl(undefined);
localStorage.removeItem("mx_is_access_token");
localStorage.removeItem("mx_is_url");
} else {
MatrixClientPeg.get().setIdentityServerUrl(fullUrl);
MatrixClientPeg.safeGet().setIdentityServerUrl(fullUrl);
localStorage.removeItem("mx_is_access_token"); // clear token
localStorage.setItem("mx_is_url", fullUrl); // XXX: Do we still need this?
}
@ -625,7 +626,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.notifyNewScreen("forgot_password");
break;
case "start_chat":
createRoom(MatrixClientPeg.get(), {
createRoom(MatrixClientPeg.safeGet(), {
dmUserId: payload.user_id,
});
break;
@ -647,7 +648,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// FIXME: controller shouldn't be loading a view :(
const modal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
MatrixClientPeg.get()
MatrixClientPeg.safeGet()
.leave(payload.room_id)
.then(
() => {
@ -755,7 +756,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.viewSomethingBehindModal();
break;
case "view_invite": {
const room = MatrixClientPeg.get().getRoom(payload.roomId);
const room = MatrixClientPeg.safeGet().getRoom(payload.roomId);
if (room?.isSpaceRoom()) {
showSpaceInvite(room);
} else {
@ -794,7 +795,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
Modal.createDialog(DialPadModal, {}, "mx_Dialog_dialPadWrapper");
break;
case Action.OnLoggedIn:
this.stores.client = MatrixClientPeg.get();
this.stores.client = MatrixClientPeg.safeGet();
if (
// Skip this handling for token login as that always calls onLoggedIn itself
!this.tokenLogin &&
@ -935,7 +936,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
let presentedId = roomInfo.room_alias || roomInfo.room_id!;
const room = MatrixClientPeg.get().getRoom(roomInfo.room_id);
const room = MatrixClientPeg.safeGet().getRoom(roomInfo.room_id);
if (room) {
// Not all timeline events are decrypted ahead of time anymore
// Only the critical ones for a typical UI are
@ -1062,14 +1063,14 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
const [shouldCreate, opts] = await modal.finished;
if (shouldCreate) {
createRoom(MatrixClientPeg.get(), opts!);
createRoom(MatrixClientPeg.safeGet(), opts!);
}
}
private chatCreateOrReuse(userId: string): void {
const snakedConfig = new SnakedObject<IConfigOptions>(this.props.config);
// Use a deferred action to reshow the dialog once the user has registered
if (MatrixClientPeg.get().isGuest()) {
if (MatrixClientPeg.safeGet().isGuest()) {
// No point in making 2 DMs with welcome bot. This assumes view_set_mxid will
// result in a new DM with the welcome user.
if (userId !== snakedConfig.get("welcome_user_id")) {
@ -1098,7 +1099,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// TODO: Immutable DMs replaces this
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
const dmRoom = findDMForUser(client, userId);
if (dmRoom) {
@ -1116,7 +1117,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
private leaveRoomWarnings(roomId: string): JSX.Element[] {
const roomToLeave = MatrixClientPeg.get().getRoom(roomId);
const roomToLeave = MatrixClientPeg.safeGet().getRoom(roomId);
const isSpace = roomToLeave?.isSpaceRoom();
// Show a warning if there are additional complications.
const warnings: JSX.Element[] = [];
@ -1154,7 +1155,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
private leaveRoom(roomId: string): void {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const roomToLeave = cli.getRoom(roomId);
const warnings = this.leaveRoomWarnings(roomId);
@ -1188,8 +1189,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
private forgetRoom(roomId: string): void {
const room = MatrixClientPeg.get().getRoom(roomId);
MatrixClientPeg.get()
const room = MatrixClientPeg.safeGet().getRoom(roomId);
MatrixClientPeg.safeGet()
.forget(roomId)
.then(() => {
// Switch to home page if we're currently viewing the forgotten room
@ -1212,7 +1213,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
private async copyRoom(roomId: string): Promise<void> {
const roomLink = makeRoomPermalink(MatrixClientPeg.get(), roomId);
const roomLink = makeRoomPermalink(MatrixClientPeg.safeGet(), roomId);
const success = await copyPlaintext(roomLink);
if (!success) {
Modal.createDialog(ErrorDialog, {
@ -1246,7 +1247,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
const welcomeUserRooms = DMRoomMap.shared().getDMRoomsForUserId(welcomeUserId);
if (welcomeUserRooms.length === 0) {
const roomId = await createRoom(MatrixClientPeg.get(), {
const roomId = await createRoom(MatrixClientPeg.safeGet(), {
dmUserId: snakedConfig.get("welcome_user_id"),
// Only view the welcome user if we're NOT looking at a room
andView: !this.state.currentRoomId,
@ -1262,11 +1263,11 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// the saved sync to be loaded).
const saveWelcomeUser = (ev: MatrixEvent): void => {
if (ev.getType() === EventType.Direct && ev.getContent()[welcomeUserId]) {
MatrixClientPeg.get().store.save(true);
MatrixClientPeg.get().removeListener(ClientEvent.AccountData, saveWelcomeUser);
MatrixClientPeg.safeGet().store.save(true);
MatrixClientPeg.safeGet().removeListener(ClientEvent.AccountData, saveWelcomeUser);
}
};
MatrixClientPeg.get().on(ClientEvent.AccountData, saveWelcomeUser);
MatrixClientPeg.safeGet().on(ClientEvent.AccountData, saveWelcomeUser);
return roomId;
}
@ -1413,7 +1414,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// Before defaulting to directory, show the last viewed room
this.viewLastRoom();
} else {
if (MatrixClientPeg.get().isGuest()) {
if (MatrixClientPeg.safeGet().isGuest()) {
dis.dispatch({ action: "view_welcome_page" });
} else {
dis.dispatch({ action: Action.ViewHomePage });
@ -1468,7 +1469,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// to do the first sync
this.firstSyncComplete = false;
this.firstSyncPromise = defer();
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
// Allow the JS SDK to reap timeline events. This reduces the amount of
// memory consumed as the JS SDK stores multiple distinct copies of room
@ -1588,7 +1589,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
cli.on(MatrixEventEvent.Decrypted, (e, err) => dft.eventDecrypted(e, err as DecryptionError));
cli.on(ClientEvent.Room, (room) => {
if (MatrixClientPeg.get().isCryptoEnabled()) {
if (cli.isCryptoEnabled()) {
const blacklistEnabled = SettingsStore.getValueAt(
SettingLevel.ROOM_DEVICE,
"blacklistUnverifiedDevices",
@ -1618,15 +1619,15 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
});
cli.on(CryptoEvent.KeyBackupFailed, async (errcode): Promise<void> => {
let haveNewVersion;
let newVersionInfo;
let haveNewVersion: boolean | undefined;
let newVersionInfo: IKeyBackupInfo | null = null;
// if key backup is still enabled, there must be a new backup in place
if (MatrixClientPeg.get().getKeyBackupEnabled()) {
if (cli.getKeyBackupEnabled()) {
haveNewVersion = true;
} else {
// otherwise check the server to see if there's a new one
try {
newVersionInfo = await MatrixClientPeg.get().getKeyBackupVersion();
newVersionInfo = await cli.getKeyBackupVersion();
if (newVersionInfo !== null) haveNewVersion = true;
} catch (e) {
logger.error("Saw key backup error but failed to check backup version!", e);
@ -1639,7 +1640,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
import(
"../../async-components/views/dialogs/security/NewRecoveryMethodDialog"
) as unknown as Promise<typeof NewRecoveryMethodDialog>,
{ newVersionInfo },
{ newVersionInfo: newVersionInfo! },
);
} else {
Modal.createDialogAsync(
@ -1686,7 +1687,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
* @private
*/
private onClientStarted(): void {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
if (cli.isCryptoEnabled()) {
const blacklistEnabled = SettingsStore.getValueAt(SettingLevel.DEVICE, "blacklistUnverifiedDevices");
@ -1734,7 +1735,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
params: params,
});
} else if (screen === "soft_logout") {
if (cli.getUserId() && !Lifecycle.isSoftLogout()) {
if (!!cli?.getUserId() && !Lifecycle.isSoftLogout()) {
// Logged in - visit a room
this.viewLastRoom();
} else {
@ -2057,7 +2058,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
{...this.props}
{...this.state}
ref={this.loggedInView}
matrixClient={MatrixClientPeg.get()}
matrixClient={MatrixClientPeg.safeGet()}
onRegistered={this.onRegistered}
currentRoomId={this.state.currentRoomId}
/>

View file

@ -473,7 +473,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
}
}
if (MatrixClientPeg.get().isUserIgnored(mxEv.getSender()!)) {
if (MatrixClientPeg.safeGet().isUserIgnored(mxEv.getSender()!)) {
return false; // ignored = no show (only happens if the ignore happens after an event was received)
}
@ -743,7 +743,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
lastInSection =
willWantDateSeparator ||
mxEv.getSender() !== nextEv.getSender() ||
getEventDisplayInfo(MatrixClientPeg.get(), nextEv, this.showHiddenEvents).isInfoMessage ||
getEventDisplayInfo(MatrixClientPeg.safeGet(), nextEv, this.showHiddenEvents).isInfoMessage ||
!shouldFormContinuation(mxEv, nextEv, this.showHiddenEvents, this.context.timelineRenderingType);
}
@ -779,7 +779,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
// We only want to consider "last successful" if the event is sent by us, otherwise of course
// it's successful: we received it.
isLastSuccessful = isLastSuccessful && mxEv.getSender() === MatrixClientPeg.get().getUserId();
isLastSuccessful = isLastSuccessful && mxEv.getSender() === MatrixClientPeg.safeGet().getUserId();
const callEventGrouper = this.props.callEventGroupers.get(mxEv.getContent().call_id);
// use txnId as key if available so that we don't remount during sending
@ -833,7 +833,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
// Get a list of read receipts that should be shown next to this event
// Receipts are objects which have a 'userId', 'roomMember' and 'ts'.
private getReadReceiptsForEvent(event: MatrixEvent): IReadReceiptProps[] | null {
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUserId = MatrixClientPeg.safeGet().credentials.userId;
// get list of read receipts, sorted most recent first
const { room } = this.props;
@ -856,7 +856,7 @@ export default class MessagePanel extends React.Component<IProps, IState> {
if (!r.userId || !isSupportedReceiptType(r.type) || r.userId === myUserId) {
return; // ignore non-read receipts and receipts from self.
}
if (MatrixClientPeg.get().isUserIgnored(r.userId)) {
if (MatrixClientPeg.safeGet().isUserIgnored(r.userId)) {
return; // ignore ignored users
}
const member = room.getMember(r.userId);
@ -1301,7 +1301,7 @@ class MainGrouper extends BaseGrouper {
public add({ event: ev, shouldShow }: EventAndShouldShow): void {
if (ev.getType() === EventType.RoomMember) {
// We can ignore any events that don't actually have a message to display
if (!hasText(ev, MatrixClientPeg.get(), this.panel.showHiddenEvents)) return;
if (!hasText(ev, MatrixClientPeg.safeGet(), this.panel.showHiddenEvents)) return;
}
this.readMarker = this.readMarker || this.panel.readMarkerForEvent(ev.getId()!, ev === this.lastShownEvent);
if (!this.panel.showHiddenEvents && !shouldShow) {

View file

@ -63,8 +63,8 @@ export default class NotificationPanel extends React.PureComponent<IProps, IStat
</div>
);
let content;
const timelineSet = MatrixClientPeg.get().getNotifTimelineSet();
let content: JSX.Element;
const timelineSet = MatrixClientPeg.safeGet().getNotifTimelineSet();
if (timelineSet) {
// wrap a TimelinePanel with the jump-to-event bits turned off.
content = (

View file

@ -139,8 +139,8 @@ class PipContainerInner extends React.Component<IProps, IState> {
LegacyCallHandler.instance.addListener(LegacyCallHandlerEvent.CallChangeRoom, this.updateCalls);
LegacyCallHandler.instance.addListener(LegacyCallHandlerEvent.CallState, this.updateCalls);
SdkContextClass.instance.roomViewStore.addListener(UPDATE_EVENT, this.onRoomViewStoreUpdate);
MatrixClientPeg.get().on(CallEvent.RemoteHoldUnhold, this.onCallRemoteHold);
const room = MatrixClientPeg.get()?.getRoom(this.state.viewedRoomId);
MatrixClientPeg.safeGet().on(CallEvent.RemoteHoldUnhold, this.onCallRemoteHold);
const room = MatrixClientPeg.safeGet().getRoom(this.state.viewedRoomId);
if (room) {
WidgetLayoutStore.instance.on(WidgetLayoutStore.emissionForRoom(room), this.updateCalls);
}
@ -239,7 +239,7 @@ class PipContainerInner extends React.Component<IProps, IState> {
let notDocked = false;
// Sanity check the room - the widget may have been destroyed between render cycles, and
// thus no room is associated anymore.
if (persistentWidgetId && persistentRoomId && MatrixClientPeg.get().getRoom(persistentRoomId)) {
if (persistentWidgetId && persistentRoomId && MatrixClientPeg.safeGet().getRoom(persistentRoomId)) {
notDocked = !ActiveWidgetStore.instance.isDocked(persistentWidgetId, persistentRoomId);
fromAnotherRoom = this.state.viewedRoomId !== persistentRoomId;
}
@ -318,7 +318,7 @@ class PipContainerInner extends React.Component<IProps, IState> {
pipContent.push(({ onStartMoving }) => (
<WidgetPip
widgetId={this.state.persistentWidgetId!}
room={MatrixClientPeg.get().getRoom(this.state.persistentRoomId ?? undefined)!}
room={MatrixClientPeg.safeGet().getRoom(this.state.persistentRoomId ?? undefined)!}
viewingRoom={this.state.viewedRoomId === this.state.persistentRoomId}
onStartMoving={onStartMoving}
movePersistedElement={this.props.movePersistedElement}

View file

@ -329,7 +329,7 @@ export default class ThreadView extends React.Component<IProps, IState> {
Array.from(dataTransfer.files),
roomId,
this.threadRelation,
MatrixClientPeg.get(),
MatrixClientPeg.safeGet(),
TimelineRenderingType.Thread,
);
} else {

View file

@ -291,7 +291,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
readMarkerEventId: this.initialReadMarkerId,
backPaginating: false,
forwardPaginating: false,
clientSyncState: MatrixClientPeg.get().getSyncState(),
clientSyncState: MatrixClientPeg.safeGet().getSyncState(),
isTwelveHour: SettingsStore.getValue("showTwelveHourTimestamps"),
alwaysShowTimestamps: SettingsStore.getValue("alwaysShowTimestamps"),
readMarkerInViewThresholdMs: SettingsStore.getValue("readMarkerInViewThresholdMs"),
@ -299,7 +299,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
};
this.dispatcherRef = dis.register(this.onAction);
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
cli.on(RoomEvent.Timeline, this.onRoomTimeline);
cli.on(RoomEvent.TimelineReset, this.onRoomTimelineReset);
cli.on(RoomEvent.Redaction, this.onRoomRedaction);
@ -788,7 +788,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// read-marker when a remote echo of an event we have just sent takes
// more than the timeout on userActiveRecently.
//
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUserId = MatrixClientPeg.safeGet().credentials.userId;
callRMUpdated = false;
if (ev.getSender() !== myUserId && !UserActivity.sharedInstance().userActiveRecently()) {
updatedState.readMarkerVisible = true;
@ -881,7 +881,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
if (!this.hasTimelineSetFor(member.roomId)) return;
// ignore events for other users
if (member.userId != MatrixClientPeg.get().credentials?.userId) return;
if (member.userId != MatrixClientPeg.safeGet().credentials?.userId) return;
// We could skip an update if the power level change didn't cross the
// threshold for `VISIBILITY_CHANGE_TYPE`.
@ -1276,7 +1276,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
}
// now think about advancing it
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUserId = MatrixClientPeg.safeGet().credentials.userId;
for (i++; i < events.length; i++) {
const ev = events[i];
if (ev.getSender() !== myUserId) {
@ -1557,7 +1557,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
* @param {boolean?} scrollIntoView whether to scroll the event into view.
*/
private loadTimeline(eventId?: string, pixelOffset?: number, offsetBase?: number, scrollIntoView = true): void {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
this.timelineWindow = new TimelineWindow(cli, this.props.timelineSet, { windowLimit: this.props.timelineCap });
this.overlayTimelineWindow = this.props.overlayTimelineSet
? new TimelineWindow(cli, this.props.overlayTimelineSet, { windowLimit: this.props.timelineCap })
@ -1748,7 +1748,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
arrayFastClone(events)
.reverse()
.forEach((event) => {
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
client.decryptEventIfNeeded(event);
});
@ -1796,7 +1796,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
* such events were found, then it returns 0.
*/
private checkForPreJoinUISI(events: MatrixEvent[]): number {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const room = this.props.timelineSet.room;
const isThreadTimeline = [TimelineRenderingType.Thread, TimelineRenderingType.ThreadsList].includes(
@ -1921,7 +1921,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
const messagePanelNode = ReactDOM.findDOMNode(messagePanel) as Element;
if (!messagePanelNode) return null; // sometimes this happens for fresh rooms/post-sync
const wrapperRect = messagePanelNode.getBoundingClientRect();
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUserId = MatrixClientPeg.safeGet().credentials.userId;
const isNodeInView = (node?: HTMLElement): boolean => {
if (node) {
@ -2121,7 +2121,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
canBackPaginate={this.state.canBackPaginate && this.state.firstVisibleEventIndex === 0}
showUrlPreview={this.props.showUrlPreview}
showReadReceipts={this.props.showReadReceipts}
ourUserId={MatrixClientPeg.get().getSafeUserId()}
ourUserId={MatrixClientPeg.safeGet().getSafeUserId()}
stickyBottom={stickyBottom}
onScroll={this.onMessageListScroll}
onFillRequest={this.onMessageListFillRequest}

View file

@ -291,7 +291,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
if (!this.state.contextMenuPosition) return null;
let topSection: JSX.Element | undefined;
if (MatrixClientPeg.get().isGuest()) {
if (MatrixClientPeg.safeGet().isGuest()) {
topSection = (
<div className="mx_UserMenu_contextMenu_header mx_UserMenu_contextMenu_guestPrompts">
{_t(
@ -372,7 +372,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
</IconizedContextMenuOptionList>
);
if (MatrixClientPeg.get().isGuest()) {
if (MatrixClientPeg.safeGet().isGuest()) {
primaryOptionList = (
<IconizedContextMenuOptionList>
{homeButton}
@ -399,7 +399,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
</span>
<span className="mx_UserMenu_contextMenu_userId">
{UserIdentifierCustomisations.getDisplayUserIdentifier(
MatrixClientPeg.get().getSafeUserId(),
MatrixClientPeg.safeGet().getSafeUserId(),
{
withDisplayName: true,
},
@ -428,7 +428,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
public render(): React.ReactNode {
const avatarSize = 32; // should match border-radius of the avatar
const userId = MatrixClientPeg.get().getSafeUserId();
const userId = MatrixClientPeg.safeGet().getSafeUserId();
const displayName = OwnProfileStore.instance.displayName || userId;
const avatarUrl = OwnProfileStore.instance.getHttpAvatarUrl(avatarSize);

View file

@ -142,7 +142,7 @@ export default class ViewSource extends React.Component<IProps, IState> {
}
private canSendStateEvent(mxEvent: MatrixEvent): boolean {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(mxEvent.getRoomId());
return !!room?.currentState.mayClientSendStateEvent(mxEvent.getType(), cli);
}
@ -155,7 +155,7 @@ export default class ViewSource extends React.Component<IProps, IState> {
const eventId = mxEvent.getId()!;
const canEdit = mxEvent.isState()
? this.canSendStateEvent(mxEvent)
: canEditContent(MatrixClientPeg.get(), this.props.mxEvent);
: canEditContent(MatrixClientPeg.safeGet(), this.props.mxEvent);
return (
<BaseDialog className="mx_ViewSource" onFinished={this.props.onFinished} title={_t("View Source")}>
<div className="mx_ViewSource_header">

View file

@ -420,7 +420,7 @@ export default class Registration extends React.Component<IProps, IState> {
if (!this.props.brand) {
return Promise.resolve();
}
const matrixClient = MatrixClientPeg.get();
const matrixClient = MatrixClientPeg.safeGet();
return matrixClient.getPushers().then(
(resp) => {
const pushers = resp.pushers;

View file

@ -87,7 +87,7 @@ export default class SetupEncryptionBody extends React.Component<IProps, IState>
};
private onVerifyClick = (): void => {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const userId = cli.getSafeUserId();
const requestPromise = cli.requestVerification(userId);
@ -142,7 +142,7 @@ export default class SetupEncryptionBody extends React.Component<IProps, IState>
};
public render(): React.ReactNode {
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
const { phase, lostKeys } = this.state;
if (this.state.verificationRequest && cli.getUser(this.state.verificationRequest.otherUserId)) {

View file

@ -94,7 +94,7 @@ export default class SoftLogout extends React.Component<IProps, IState> {
this.initLogin();
const cli = MatrixClientPeg.get();
const cli = MatrixClientPeg.safeGet();
if (cli.isCryptoEnabled()) {
cli.countSessionsNeedingBackup().then((remaining) => {
this.setState({ keyBackupNeeded: remaining > 0 });
@ -124,7 +124,7 @@ export default class SoftLogout extends React.Component<IProps, IState> {
// Note: we don't use the existing Login class because it is heavily flow-based. We don't
// care about login flows here, unless it is the single flow we support.
const client = MatrixClientPeg.get();
const client = MatrixClientPeg.safeGet();
const flows = (await client.loginFlows()).flows;
const loginViews = flows.map((f) => STATIC_FLOWS_TO_VIEWS[f.type]);
@ -148,16 +148,17 @@ export default class SoftLogout extends React.Component<IProps, IState> {
this.setState({ busy: true });
const hsUrl = MatrixClientPeg.get().getHomeserverUrl();
const isUrl = MatrixClientPeg.get().getIdentityServerUrl();
const cli = MatrixClientPeg.safeGet();
const hsUrl = cli.getHomeserverUrl();
const isUrl = cli.getIdentityServerUrl();
const loginType = "m.login.password";
const loginParams = {
identifier: {
type: "m.id.user",
user: MatrixClientPeg.get().getUserId(),
user: cli.getUserId(),
},
password: this.state.password,
device_id: MatrixClientPeg.get().getDeviceId() ?? undefined,
device_id: cli.getDeviceId() ?? undefined,
};
let credentials: IMatrixClientCreds;
@ -196,11 +197,11 @@ export default class SoftLogout extends React.Component<IProps, IState> {
return;
}
const isUrl = localStorage.getItem(SSO_ID_SERVER_URL_KEY) || MatrixClientPeg.get().getIdentityServerUrl();
const isUrl = localStorage.getItem(SSO_ID_SERVER_URL_KEY) || MatrixClientPeg.safeGet().getIdentityServerUrl();
const loginType = "m.login.token";
const loginParams = {
token: this.props.realQueryParams["loginToken"],
device_id: MatrixClientPeg.get().getDeviceId() ?? undefined,
device_id: MatrixClientPeg.safeGet().getDeviceId() ?? undefined,
};
let credentials: IMatrixClientCreds;
@ -262,7 +263,7 @@ export default class SoftLogout extends React.Component<IProps, IState> {
<div>
{introText ? <p>{introText}</p> : null}
<SSOButtons
matrixClient={MatrixClientPeg.get()}
matrixClient={MatrixClientPeg.safeGet()}
flow={flow}
loginType={loginType}
fragmentAfterLogin={this.props.fragmentAfterLogin}