Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Use MatrixClientPeg::safeGet in src/{stores,hooks,components/structur…
Browse files Browse the repository at this point in the history
…es}/*
  • Loading branch information
t3chguy committed Jun 15, 2023
1 parent 280f6a9 commit f199443
Show file tree
Hide file tree
Showing 32 changed files with 134 additions and 130 deletions.
20 changes: 10 additions & 10 deletions src/components/structures/FilePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down Expand Up @@ -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.
Expand All @@ -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);
Expand All @@ -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: {
Expand All @@ -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;

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

Expand Down Expand Up @@ -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">
Expand Down Expand Up @@ -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 (
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/LegacyCallEventGrouper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
);
}

Expand Down
63 changes: 32 additions & 31 deletions src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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?
}
Expand Down Expand Up @@ -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;
Expand All @@ -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(
() => {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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[] = [];
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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
Expand All @@ -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, {
Expand Down Expand Up @@ -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,
Expand All @@ -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;
}
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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);
Expand All @@ -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(
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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}
/>
Expand Down
12 changes: 6 additions & 6 deletions src/components/structures/MessagePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit f199443

Please sign in to comment.