Use MatrixClientPeg::safeGet in src/components/views/* (#10987)

This commit is contained in:
Michael Telatynski 2023-06-15 08:46:19 +01:00 committed by GitHub
parent 4243847f4f
commit 280f6a9d93
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
81 changed files with 265 additions and 250 deletions

View file

@ -166,7 +166,7 @@ export default class DecoratedRoomAvatar extends React.PureComponent<IProps, ISt
if (otherUserId && this.props.room.getJoinedMemberCount() === 2) { if (otherUserId && this.props.room.getJoinedMemberCount() === 2) {
// Track presence, if available // Track presence, if available
if (isPresenceEnabled(this.props.room.client)) { if (isPresenceEnabled(this.props.room.client)) {
this.dmUser = MatrixClientPeg.get().getUser(otherUserId); this.dmUser = MatrixClientPeg.safeGet().getUser(otherUserId);
icon = this.getPresenceIcon(); icon = this.getPresenceIcon();
} }
} else { } else {

View file

@ -65,7 +65,7 @@ export default class RoomAvatar extends React.Component<IProps, IState> {
} }
public componentDidMount(): void { public componentDidMount(): void {
MatrixClientPeg.get().on(RoomStateEvent.Events, this.onRoomStateEvents); MatrixClientPeg.safeGet().on(RoomStateEvent.Events, this.onRoomStateEvents);
} }
public componentWillUnmount(): void { public componentWillUnmount(): void {

View file

@ -144,7 +144,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
} }
public componentDidMount(): void { public componentDidMount(): void {
MatrixClientPeg.get().on(RoomMemberEvent.PowerLevel, this.checkPermissions); MatrixClientPeg.safeGet().on(RoomMemberEvent.PowerLevel, this.checkPermissions);
// re-check the permissions on send progress (`maySendRedactionForEvent` only returns true for events that have // re-check the permissions on send progress (`maySendRedactionForEvent` only returns true for events that have
// been fully sent and echoed back, and we want to ensure the "Remove" option is added once that happens.) // been fully sent and echoed back, and we want to ensure the "Remove" option is added once that happens.)
@ -162,7 +162,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
} }
private checkPermissions = (): void => { private checkPermissions = (): void => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.mxEvent.getRoomId()); const room = cli.getRoom(this.props.mxEvent.getRoomId());
// We explicitly decline to show the redact option on ACL events as it has a potential // We explicitly decline to show the redact option on ACL events as it has a potential
@ -184,7 +184,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
}; };
private isPinned(): boolean { private isPinned(): boolean {
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
const pinnedEvent = room?.currentState.getStateEvents(EventType.RoomPinnedEvents, ""); const pinnedEvent = room?.currentState.getStateEvents(EventType.RoomPinnedEvents, "");
if (!pinnedEvent) return false; if (!pinnedEvent) return false;
const content = pinnedEvent.getContent(); const content = pinnedEvent.getContent();
@ -195,13 +195,13 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
return ( return (
M_POLL_START.matches(mxEvent.getType()) && M_POLL_START.matches(mxEvent.getType()) &&
this.state.canRedact && this.state.canRedact &&
!isPollEnded(mxEvent, MatrixClientPeg.get()) !isPollEnded(mxEvent, MatrixClientPeg.safeGet())
); );
} }
private onResendReactionsClick = (): void => { private onResendReactionsClick = (): void => {
for (const reaction of this.getUnsentReactions()) { for (const reaction of this.getUnsentReactions()) {
Resend.resend(MatrixClientPeg.get(), reaction); Resend.resend(MatrixClientPeg.safeGet(), reaction);
} }
this.closeMenu(); this.closeMenu();
}; };
@ -253,7 +253,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
}; };
private onPinClick = (): void => { private onPinClick = (): void => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.mxEvent.getRoomId()); const room = cli.getRoom(this.props.mxEvent.getRoomId());
if (!room) return; if (!room) return;
const eventId = this.props.mxEvent.getId(); const eventId = this.props.mxEvent.getId();
@ -318,7 +318,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
private onEditClick = (): void => { private onEditClick = (): void => {
editEvent( editEvent(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
this.props.mxEvent, this.props.mxEvent,
this.context.timelineRenderingType, this.context.timelineRenderingType,
this.props.getRelationsForEvent, this.props.getRelationsForEvent,
@ -345,7 +345,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
}; };
private onEndPollClick = (): void => { private onEndPollClick = (): void => {
const matrixClient = MatrixClientPeg.get(); const matrixClient = MatrixClientPeg.safeGet();
Modal.createDialog( Modal.createDialog(
EndPollDialog, EndPollDialog,
{ {
@ -359,7 +359,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
}; };
private getReactions(filter: (e: MatrixEvent) => boolean): MatrixEvent[] { private getReactions(filter: (e: MatrixEvent) => boolean): MatrixEvent[] {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.mxEvent.getRoomId()); const room = cli.getRoom(this.props.mxEvent.getRoomId());
const eventId = this.props.mxEvent.getId(); const eventId = this.props.mxEvent.getId();
return ( return (
@ -386,7 +386,7 @@ export default class MessageContextMenu extends React.Component<IProps, IState>
}; };
public render(): React.ReactNode { public render(): React.ReactNode {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const me = cli.getUserId(); const me = cli.getUserId();
const { mxEvent, rightClick, link, eventTileOps, reactions, collapseReplyChain, ...other } = this.props; const { mxEvent, rightClick, link, eventTileOps, reactions, collapseReplyChain, ...other } = this.props;
delete other.getRelationsForEvent; delete other.getRelationsForEvent;

View file

@ -84,7 +84,7 @@ const ThreadListContextMenu: React.FC<ThreadListContextMenuProps> = ({
onMenuToggle?.(menuDisplayed); onMenuToggle?.(menuDisplayed);
}, [menuDisplayed, onMenuToggle]); }, [menuDisplayed, onMenuToggle]);
const room = MatrixClientPeg.get().getRoom(mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(mxEvent.getRoomId());
const isMainSplitTimelineShown = !!room && !WidgetLayoutStore.instance.hasMaximisedWidget(room); const isMainSplitTimelineShown = !!room && !WidgetLayoutStore.instance.hasMaximisedWidget(room);
return ( return (
<React.Fragment> <React.Fragment>

View file

@ -75,7 +75,7 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
joinRule = JoinRule.Restricted; joinRule = JoinRule.Restricted;
} }
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
this.state = { this.state = {
isPublic: this.props.defaultPublic || false, isPublic: this.props.defaultPublic || false,
isEncrypted: this.props.defaultEncrypted ?? privateShouldBeEncrypted(cli), isEncrypted: this.props.defaultEncrypted ?? privateShouldBeEncrypted(cli),
@ -222,7 +222,7 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
let aliasField: JSX.Element | undefined; let aliasField: JSX.Element | undefined;
if (this.state.joinRule === JoinRule.Public) { if (this.state.joinRule === JoinRule.Public) {
const domain = MatrixClientPeg.get().getDomain()!; const domain = MatrixClientPeg.safeGet().getDomain()!;
aliasField = ( aliasField = (
<div className="mx_CreateRoomDialog_aliasContainer"> <div className="mx_CreateRoomDialog_aliasContainer">
<RoomAliasField <RoomAliasField
@ -285,7 +285,7 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
let e2eeSection: JSX.Element | undefined; let e2eeSection: JSX.Element | undefined;
if (this.state.joinRule !== JoinRule.Public) { if (this.state.joinRule !== JoinRule.Public) {
let microcopy: string; let microcopy: string;
if (privateShouldBeEncrypted(MatrixClientPeg.get())) { if (privateShouldBeEncrypted(MatrixClientPeg.safeGet())) {
if (this.state.canChangeEncryption) { if (this.state.canChangeEncryption) {
microcopy = isVideoRoom microcopy = isVideoRoom
? _t("You can't disable this later. The room will be encrypted but the embedded call will not.") ? _t("You can't disable this later. The room will be encrypted but the embedded call will not.")

View file

@ -125,7 +125,7 @@ export default class DeactivateAccountDialog extends React.Component<IProps, ISt
// XXX: this should be returning a promise to maintain the state inside the state machine correct // XXX: this should be returning a promise to maintain the state inside the state machine correct
// but given that a deactivation is followed by a local logout and all object instances being thrown away // but given that a deactivation is followed by a local logout and all object instances being thrown away
// this isn't done. // this isn't done.
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.deactivateAccount(auth, this.state.shouldErase) .deactivateAccount(auth, this.state.shouldErase)
.then((r) => { .then((r) => {
// Deactivation worked - logout & close this dialog // Deactivation worked - logout & close this dialog
@ -158,7 +158,7 @@ export default class DeactivateAccountDialog extends React.Component<IProps, ISt
} }
private initAuth(shouldErase: boolean): void { private initAuth(shouldErase: boolean): void {
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.deactivateAccount(null, shouldErase) .deactivateAccount(null, shouldErase)
.then((r) => { .then((r) => {
// If we got here, oops. The server didn't require any auth. // If we got here, oops. The server didn't require any auth.
@ -190,7 +190,7 @@ export default class DeactivateAccountDialog extends React.Component<IProps, ISt
<div> <div>
{this.state.bodyText} {this.state.bodyText}
<InteractiveAuth <InteractiveAuth
matrixClient={MatrixClientPeg.get()} matrixClient={MatrixClientPeg.safeGet()}
authData={this.state.authData} authData={this.state.authData}
// XXX: onUIAuthComplete breaches the expected method contract, it gets away with it because it // XXX: onUIAuthComplete breaches the expected method contract, it gets away with it because it
// knows the entire app is about to die as a result of the account deactivation. // knows the entire app is about to die as a result of the account deactivation.

View file

@ -86,7 +86,7 @@ export default class IncomingSasDialog extends React.Component<IProps, IState> {
private async fetchOpponentProfile(): Promise<void> { private async fetchOpponentProfile(): Promise<void> {
try { try {
const prof = await MatrixClientPeg.get().getProfileInfo(this.props.verifier.userId); const prof = await MatrixClientPeg.safeGet().getProfileInfo(this.props.verifier.userId);
this.setState({ this.setState({
opponentProfile: prof, opponentProfile: prof,
}); });
@ -143,7 +143,7 @@ export default class IncomingSasDialog extends React.Component<IProps, IState> {
}; };
private renderPhaseStart(): ReactNode { private renderPhaseStart(): ReactNode {
const isSelf = this.props.verifier.userId === MatrixClientPeg.get().getUserId(); const isSelf = this.props.verifier.userId === MatrixClientPeg.safeGet().getUserId();
let profile; let profile;
const oppProfile = this.state.opponentProfile; const oppProfile = this.state.opponentProfile;
@ -233,7 +233,7 @@ export default class IncomingSasDialog extends React.Component<IProps, IState> {
sas={this.showSasEvent.sas} sas={this.showSasEvent.sas}
onCancel={this.onCancelClick} onCancel={this.onCancelClick}
onDone={this.onSasMatchesClick} onDone={this.onSasMatchesClick}
isSelf={this.props.verifier.userId === MatrixClientPeg.get().getUserId()} isSelf={this.props.verifier.userId === MatrixClientPeg.safeGet().getUserId()}
inDialog={true} inDialog={true}
/> />
); );

View file

@ -373,12 +373,12 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
this.profilesStore = SdkContextClass.instance.userProfilesStore; this.profilesStore = SdkContextClass.instance.userProfilesStore;
const alreadyInvited = new Set([MatrixClientPeg.get().getUserId()!]); const alreadyInvited = new Set([MatrixClientPeg.safeGet().getUserId()!]);
const welcomeUserId = SdkConfig.get("welcome_user_id"); const welcomeUserId = SdkConfig.get("welcome_user_id");
if (welcomeUserId) alreadyInvited.add(welcomeUserId); if (welcomeUserId) alreadyInvited.add(welcomeUserId);
if (isRoomInvite(props)) { if (isRoomInvite(props)) {
const room = MatrixClientPeg.get().getRoom(props.roomId); const room = MatrixClientPeg.safeGet().getRoom(props.roomId);
if (!room) throw new Error("Room ID given to InviteDialog does not look like a room"); if (!room) throw new Error("Room ID given to InviteDialog does not look like a room");
room.getMembersWithMembership("invite").forEach((m) => alreadyInvited.add(m.userId)); room.getMembersWithMembership("invite").forEach((m) => alreadyInvited.add(m.userId));
room.getMembersWithMembership("join").forEach((m) => alreadyInvited.add(m.userId)); room.getMembersWithMembership("join").forEach((m) => alreadyInvited.add(m.userId));
@ -395,7 +395,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
numSuggestionsShown: INITIAL_ROOMS_SHOWN, numSuggestionsShown: INITIAL_ROOMS_SHOWN,
serverResultsMixin: [], serverResultsMixin: [],
threepidResultsMixin: [], threepidResultsMixin: [],
canUseIdentityServer: !!MatrixClientPeg.get().getIdentityServerUrl(), canUseIdentityServer: !!MatrixClientPeg.safeGet().getIdentityServerUrl(),
tryingIdentityServer: false, tryingIdentityServer: false,
consultFirst: false, consultFirst: false,
dialPadValue: "", dialPadValue: "",
@ -407,7 +407,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
} }
public componentDidMount(): void { public componentDidMount(): void {
this.encryptionByDefault = privateShouldBeEncrypted(MatrixClientPeg.get()); this.encryptionByDefault = privateShouldBeEncrypted(MatrixClientPeg.safeGet());
if (this.props.initialText) { if (this.props.initialText) {
this.updateSuggestions(this.props.initialText); this.updateSuggestions(this.props.initialText);
@ -428,7 +428,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
// Also pull in all the rooms tagged as DefaultTagID.DM so we don't miss anything. Sometimes the // Also pull in all the rooms tagged as DefaultTagID.DM so we don't miss anything. Sometimes the
// room list doesn't tag the room for the DMRoomMap, but does for the room list. // room list doesn't tag the room for the DMRoomMap, but does for the room list.
const dmTaggedRooms = RoomListStore.instance.orderedLists[DefaultTagID.DM] || []; const dmTaggedRooms = RoomListStore.instance.orderedLists[DefaultTagID.DM] || [];
const myUserId = MatrixClientPeg.get().getUserId(); const myUserId = MatrixClientPeg.safeGet().getUserId();
for (const dmRoom of dmTaggedRooms) { for (const dmRoom of dmTaggedRooms) {
const otherMembers = dmRoom.getJoinedMembers().filter((u) => u.userId !== myUserId); const otherMembers = dmRoom.getJoinedMembers().filter((u) => u.userId !== myUserId);
for (const member of otherMembers) { for (const member of otherMembers) {
@ -491,7 +491,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
} }
private buildSuggestions(excludedTargetIds: Set<string>): { userId: string; user: Member }[] { private buildSuggestions(excludedTargetIds: Set<string>): { userId: string; user: Member }[] {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const activityScores = buildActivityScores(cli); const activityScores = buildActivityScores(cli);
const memberScores = buildMemberScores(cli); const memberScores = buildMemberScores(cli);
@ -560,7 +560,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
this.setBusy(true); this.setBusy(true);
try { try {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const targets = this.convertFilter(); const targets = this.convertFilter();
await startDmOnFirstMessage(cli, targets); await startDmOnFirstMessage(cli, targets);
this.props.onFinished(true); this.props.onFinished(true);
@ -601,7 +601,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
const targets = this.convertFilter(); const targets = this.convertFilter();
const targetIds = targets.map((t) => t.userId); const targetIds = targets.map((t) => t.userId);
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.roomId); const room = cli.getRoom(this.props.roomId);
if (!room) { if (!room) {
logger.error("Failed to find the room to invite users to"); logger.error("Failed to find the room to invite users to");
@ -694,7 +694,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
}; };
private updateSuggestions = async (term: string): Promise<void> => { private updateSuggestions = async (term: string): Promise<void> => {
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.searchUserDirectory({ term }) .searchUserDirectory({ term })
.then(async (r): Promise<void> => { .then(async (r): Promise<void> => {
if (term !== this.state.filterText) { if (term !== this.state.filterText) {
@ -774,7 +774,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
if (term !== this.state.filterText) return; // abandon hope if (term !== this.state.filterText) return; // abandon hope
const lookup = await MatrixClientPeg.get().lookupThreePid("email", term, token); const lookup = await MatrixClientPeg.safeGet().lookupThreePid("email", term, token);
if (term !== this.state.filterText) return; // abandon hope if (term !== this.state.filterText) return; // abandon hope
if (!lookup || !lookup.mxid) { if (!lookup || !lookup.mxid) {
@ -986,7 +986,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
// Update the IS in account data. Actually using it may trigger terms. // Update the IS in account data. Actually using it may trigger terms.
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
setToDefaultIdentityServer(MatrixClientPeg.get()); setToDefaultIdentityServer(MatrixClientPeg.safeGet());
this.setState({ canUseIdentityServer: true, tryingIdentityServer: false }); this.setState({ canUseIdentityServer: true, tryingIdentityServer: false });
}; };
@ -1289,7 +1289,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
const hasSelection = const hasSelection =
this.state.targets.length > 0 || (this.state.filterText && this.state.filterText.includes("@")); this.state.targets.length > 0 || (this.state.filterText && this.state.filterText.includes("@"));
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const userId = cli.getUserId()!; const userId = cli.getUserId()!;
if (this.props.kind === InviteKind.Dm) { if (this.props.kind === InviteKind.Dm) {
title = _t("Direct Messages"); title = _t("Direct Messages");
@ -1332,11 +1332,11 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
<p>{_t("If you can't see who you're looking for, send them your invite link below.")}</p> <p>{_t("If you can't see who you're looking for, send them your invite link below.")}</p>
</div> </div>
); );
const link = makeUserPermalink(MatrixClientPeg.get().getUserId()!); const link = makeUserPermalink(MatrixClientPeg.safeGet().getSafeUserId());
footer = ( footer = (
<div className="mx_InviteDialog_footer"> <div className="mx_InviteDialog_footer">
<h3>{_t("Or send invite link")}</h3> <h3>{_t("Or send invite link")}</h3>
<CopyableText getTextToCopy={() => makeUserPermalink(MatrixClientPeg.get().getUserId()!)}> <CopyableText getTextToCopy={() => makeUserPermalink(MatrixClientPeg.safeGet().getSafeUserId())}>
<a className="mx_InviteDialog_footer_link" href={link} onClick={this.onLinkClick}> <a className="mx_InviteDialog_footer_link" href={link} onClick={this.onLinkClick}>
{link} {link}
</a> </a>

View file

@ -50,7 +50,7 @@ export default class LogoutDialog extends React.Component<IProps, IState> {
public constructor(props: IProps) { public constructor(props: IProps) {
super(props); super(props);
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const shouldLoadBackupStatus = cli.isCryptoEnabled() && !cli.getKeyBackupEnabled(); const shouldLoadBackupStatus = cli.isCryptoEnabled() && !cli.getKeyBackupEnabled();
this.state = { this.state = {
@ -66,7 +66,7 @@ export default class LogoutDialog extends React.Component<IProps, IState> {
private async loadBackupStatus(): Promise<void> { private async loadBackupStatus(): Promise<void> {
try { try {
const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupInfo = await MatrixClientPeg.safeGet().getKeyBackupVersion();
this.setState({ this.setState({
loading: false, loading: false,
backupInfo, backupInfo,
@ -86,7 +86,7 @@ export default class LogoutDialog extends React.Component<IProps, IState> {
typeof ExportE2eKeysDialog typeof ExportE2eKeysDialog
>, >,
{ {
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
}, },
); );
}; };

View file

@ -67,7 +67,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
const opts = { from: this.state.nextBatch ?? undefined }; const opts = { from: this.state.nextBatch ?? undefined };
const roomId = this.props.mxEvent.getRoomId()!; const roomId = this.props.mxEvent.getRoomId()!;
const eventId = this.props.mxEvent.getId()!; const eventId = this.props.mxEvent.getId()!;
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const { resolve, reject, promise } = defer<boolean>(); const { resolve, reject, promise } = defer<boolean>();
let result: Awaited<ReturnType<MatrixClient["relations"]>>; let result: Awaited<ReturnType<MatrixClient["relations"]>>;
@ -102,7 +102,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
private locallyRedactEventsIfNeeded(newEvents: MatrixEvent[]): void { private locallyRedactEventsIfNeeded(newEvents: MatrixEvent[]): void {
const roomId = this.props.mxEvent.getRoomId(); const roomId = this.props.mxEvent.getRoomId();
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
if (!room) return; if (!room) return;
const pendingEvents = room.getPendingEvents(); const pendingEvents = room.getPendingEvents();

View file

@ -71,7 +71,7 @@ export default class ModalWidgetDialog extends React.PureComponent<IProps, IStat
this.widget = new ElementWidget({ this.widget = new ElementWidget({
...this.props.widgetDefinition, ...this.props.widgetDefinition,
creatorUserId: MatrixClientPeg.get().getSafeUserId(), creatorUserId: MatrixClientPeg.safeGet().getSafeUserId(),
id: `modal_${this.props.sourceWidgetId}`, id: `modal_${this.props.sourceWidgetId}`,
}); });
this.possibleButtons = (this.props.widgetDefinition.buttons || []).map((b) => b.id); this.possibleButtons = (this.props.widgetDefinition.buttons || []).map((b) => b.id);
@ -130,7 +130,7 @@ export default class ModalWidgetDialog extends React.PureComponent<IProps, IStat
public render(): React.ReactNode { public render(): React.ReactNode {
const templated = this.widget.getCompleteUrl({ const templated = this.widget.getCompleteUrl({
widgetRoomId: this.props.widgetRoomId, widgetRoomId: this.props.widgetRoomId,
currentUserId: MatrixClientPeg.get().getSafeUserId(), currentUserId: MatrixClientPeg.safeGet().getSafeUserId(),
userDisplayName: OwnProfileStore.instance.displayName ?? undefined, userDisplayName: OwnProfileStore.instance.displayName ?? undefined,
userHttpAvatarUrl: OwnProfileStore.instance.getHttpAvatarUrl() ?? undefined, userHttpAvatarUrl: OwnProfileStore.instance.getHttpAvatarUrl() ?? undefined,
clientId: ELEMENT_CLIENT_ID, clientId: ELEMENT_CLIENT_ID,

View file

@ -107,7 +107,7 @@ export default class ReportEventDialog extends React.Component<IProps, IState> {
// Does the room support it, too? // Does the room support it, too?
// Extract state events to determine whether we should display // Extract state events to determine whether we should display
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const room = client.getRoom(props.mxEvent.getRoomId()); const room = client.getRoom(props.mxEvent.getRoomId());
for (const stateEventType of MODERATED_BY_STATE_EVENT_TYPE) { for (const stateEventType of MODERATED_BY_STATE_EVENT_TYPE) {
@ -237,7 +237,7 @@ export default class ReportEventDialog extends React.Component<IProps, IState> {
}); });
try { try {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const ev = this.props.mxEvent; const ev = this.props.mxEvent;
if (this.moderation && this.state.nature !== NonStandardValue.Admin) { if (this.moderation && this.state.nature !== NonStandardValue.Admin) {
const nature = this.state.nature; const nature = this.state.nature;
@ -312,7 +312,7 @@ export default class ReportEventDialog extends React.Component<IProps, IState> {
if (this.moderation) { if (this.moderation) {
// Display report-to-moderator dialog. // Display report-to-moderator dialog.
// We let the user pick a nature. // We let the user pick a nature.
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const homeServerName = SdkConfig.get("validated_server_config")!.hsName; const homeServerName = SdkConfig.get("validated_server_config")!.hsName;
let subtitle: string; let subtitle: string;
switch (this.state.nature) { switch (this.state.nature) {

View file

@ -73,7 +73,7 @@ class RoomSettingsDialog extends React.Component<IProps, IState> {
public componentDidMount(): void { public componentDidMount(): void {
this.dispatcherRef = dis.register(this.onAction); this.dispatcherRef = dis.register(this.onAction);
MatrixClientPeg.get().on(RoomEvent.Name, this.onRoomName); MatrixClientPeg.safeGet().on(RoomEvent.Name, this.onRoomName);
this.onRoomName(); this.onRoomName();
} }
@ -89,7 +89,7 @@ class RoomSettingsDialog extends React.Component<IProps, IState> {
dis.unregister(this.dispatcherRef); dis.unregister(this.dispatcherRef);
} }
MatrixClientPeg.get().removeListener(RoomEvent.Name, this.onRoomName); MatrixClientPeg.get()?.removeListener(RoomEvent.Name, this.onRoomName);
} }
/** /**
@ -98,7 +98,7 @@ class RoomSettingsDialog extends React.Component<IProps, IState> {
* @throws when room is not found * @throws when room is not found
*/ */
private getRoom(): Room { private getRoom(): Room {
const room = MatrixClientPeg.get().getRoom(this.props.roomId)!; const room = MatrixClientPeg.safeGet().getRoom(this.props.roomId)!;
// something is really wrong if we encounter this // something is really wrong if we encounter this
if (!room) { if (!room) {

View file

@ -60,7 +60,7 @@ export default class RoomUpgradeWarningDialog extends React.Component<IProps, IS
public constructor(props: IProps) { public constructor(props: IProps) {
super(props); super(props);
const room = MatrixClientPeg.get().getRoom(this.props.roomId); const room = MatrixClientPeg.safeGet().getRoom(this.props.roomId);
const joinRules = room?.currentState.getStateEvents(EventType.RoomJoinRules, ""); const joinRules = room?.currentState.getStateEvents(EventType.RoomJoinRules, "");
this.isPrivate = joinRules?.getContent()["join_rule"] !== JoinRule.Public ?? true; this.isPrivate = joinRules?.getContent()["join_rule"] !== JoinRule.Public ?? true;
this.currentVersion = room?.getVersion(); this.currentVersion = room?.getVersion();

View file

@ -72,7 +72,7 @@ export default class SetEmailDialog extends React.Component<IProps, IState> {
}); });
return; return;
} }
this.addThreepid = new AddThreepid(MatrixClientPeg.get()); this.addThreepid = new AddThreepid(MatrixClientPeg.safeGet());
this.addThreepid.addEmailAddress(emailAddress).then( this.addThreepid.addEmailAddress(emailAddress).then(
() => { () => {
Modal.createDialog(QuestionDialog, { Modal.createDialog(QuestionDialog, {

View file

@ -63,7 +63,7 @@ async function proxyHealthCheck(endpoint: string, hsUrl?: string): Promise<void>
} }
export const SlidingSyncOptionsDialog: React.FC<{ onFinished(enabled: boolean): void }> = ({ onFinished }) => { export const SlidingSyncOptionsDialog: React.FC<{ onFinished(enabled: boolean): void }> = ({ onFinished }) => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const currentProxy = SettingsStore.getValue("feature_sliding_sync_proxy_url"); const currentProxy = SettingsStore.getValue("feature_sliding_sync_proxy_url");
const hasNativeSupport = useAsyncMemo( const hasNativeSupport = useAsyncMemo(
() => () =>
@ -87,7 +87,7 @@ export const SlidingSyncOptionsDialog: React.FC<{ onFinished(enabled: boolean):
const validProxy = withValidation<undefined, { error?: Error }>({ const validProxy = withValidation<undefined, { error?: Error }>({
async deriveData({ value }): Promise<{ error?: Error }> { async deriveData({ value }): Promise<{ error?: Error }> {
try { try {
await proxyHealthCheck(value!, MatrixClientPeg.get().baseUrl); await proxyHealthCheck(value!, MatrixClientPeg.safeGet().baseUrl);
return {}; return {};
} catch (error) { } catch (error) {
return { error }; return { error };

View file

@ -34,7 +34,7 @@ const UntrustedDeviceDialog: React.FC<IProps> = ({ device, user, onFinished }) =
let askToVerifyText: string; let askToVerifyText: string;
let newSessionText: string; let newSessionText: string;
if (MatrixClientPeg.get().getUserId() === user.userId) { if (MatrixClientPeg.safeGet().getUserId() === user.userId) {
newSessionText = _t("You signed in to a new session without verifying it:"); newSessionText = _t("You signed in to a new session without verifying it:");
askToVerifyText = _t("Verify your other session using one of the options below."); askToVerifyText = _t("Verify your other session using one of the options below.");
} else { } else {

View file

@ -48,7 +48,7 @@ export default class VerificationRequestDialog extends React.Component<IProps, I
public render(): React.ReactNode { public render(): React.ReactNode {
const request = this.state.verificationRequest; const request = this.state.verificationRequest;
const otherUserId = request?.otherUserId; const otherUserId = request?.otherUserId;
const member = this.props.member || (otherUserId ? MatrixClientPeg.get().getUser(otherUserId) : null); const member = this.props.member || (otherUserId ? MatrixClientPeg.safeGet().getUser(otherUserId) : null);
const title = request?.isSelfVerification ? _t("Verify other device") : _t("Verification Request"); const title = request?.isSelfVerification ? _t("Verify other device") : _t("Verification Request");
if (!member) return null; if (!member) return null;

View file

@ -107,7 +107,7 @@ export default class AccessSecretStorageDialog extends React.PureComponent<IProp
} }
try { try {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const decodedKey = cli.keyBackupKeyFromRecoveryKey(this.state.recoveryKey); const decodedKey = cli.keyBackupKeyFromRecoveryKey(this.state.recoveryKey);
const correct = await cli.checkSecretStorageKey(decodedKey, this.props.keyInfo); const correct = await cli.checkSecretStorageKey(decodedKey, this.props.keyInfo);
this.setState({ this.setState({
@ -235,7 +235,7 @@ export default class AccessSecretStorageDialog extends React.PureComponent<IProp
// Force reset secret storage (which resets the key backup) // Force reset secret storage (which resets the key backup)
await accessSecretStorage(async (): Promise<void> => { await accessSecretStorage(async (): Promise<void> => {
// Now reset cross-signing so everything Just Works™ again. // Now reset cross-signing so everything Just Works™ again.
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
await cli.bootstrapCrossSigning({ await cli.bootstrapCrossSigning({
authUploadDeviceSigningKeys: async (makeRequest): Promise<void> => { authUploadDeviceSigningKeys: async (makeRequest): Promise<void> => {
const { finished } = Modal.createDialog(InteractiveAuthDialog, { const { finished } = Modal.createDialog(InteractiveAuthDialog, {

View file

@ -73,7 +73,7 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps
private async queryKeyUploadAuth(): Promise<void> { private async queryKeyUploadAuth(): Promise<void> {
try { try {
await MatrixClientPeg.get().uploadDeviceSigningKeys(undefined, {} as CrossSigningKeys); await MatrixClientPeg.safeGet().uploadDeviceSigningKeys(undefined, {} as CrossSigningKeys);
// We should never get here: the server should always require // We should never get here: the server should always require
// UI auth to upload device signing keys. If we do, we upload // UI auth to upload device signing keys. If we do, we upload
// no keys which would be a no-op. // no keys which would be a no-op.
@ -98,11 +98,11 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps
type: "m.login.password", type: "m.login.password",
identifier: { identifier: {
type: "m.id.user", type: "m.id.user",
user: MatrixClientPeg.get().getUserId(), user: MatrixClientPeg.safeGet().getUserId(),
}, },
// TODO: Remove `user` once servers support proper UIA // TODO: Remove `user` once servers support proper UIA
// See https://github.com/matrix-org/synapse/issues/5665 // See https://github.com/matrix-org/synapse/issues/5665
user: MatrixClientPeg.get().getUserId(), user: MatrixClientPeg.safeGet().getUserId(),
password: this.state.accountPassword, password: this.state.accountPassword,
}); });
} else if (this.props.tokenLogin) { } else if (this.props.tokenLogin) {
@ -126,7 +126,7 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps
const { finished } = Modal.createDialog(InteractiveAuthDialog, { const { finished } = Modal.createDialog(InteractiveAuthDialog, {
title: _t("Setting up keys"), title: _t("Setting up keys"),
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
makeRequest, makeRequest,
aestheticsForStagePhases: { aestheticsForStagePhases: {
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics, [SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
@ -145,9 +145,8 @@ export default class CreateCrossSigningDialog extends React.PureComponent<IProps
error: null, error: null,
}); });
const cli = MatrixClientPeg.get();
try { try {
const cli = MatrixClientPeg.safeGet();
await cli.bootstrapCrossSigning({ await cli.bootstrapCrossSigning({
authUploadDeviceSigningKeys: this.doBootstrapUIAuth, authUploadDeviceSigningKeys: this.doBootstrapUIAuth,
}); });

View file

@ -131,7 +131,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
private onRecoveryKeyChange = (e: ChangeEvent<HTMLInputElement>): void => { private onRecoveryKeyChange = (e: ChangeEvent<HTMLInputElement>): void => {
this.setState({ this.setState({
recoveryKey: e.target.value, recoveryKey: e.target.value,
recoveryKeyValid: MatrixClientPeg.get().isValidRecoveryKey(e.target.value), recoveryKeyValid: MatrixClientPeg.safeGet().isValidRecoveryKey(e.target.value),
}); });
}; };
@ -145,7 +145,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
try { try {
// We do still restore the key backup: we must ensure that the key backup key // We do still restore the key backup: we must ensure that the key backup key
// is the right one and restoring it is currently the only way we can do this. // is the right one and restoring it is currently the only way we can do this.
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithPassword( const recoverInfo = await MatrixClientPeg.safeGet().restoreKeyBackupWithPassword(
this.state.passPhrase, this.state.passPhrase,
undefined, undefined,
undefined, undefined,
@ -153,7 +153,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
{ progressCallback: this.progressCallback }, { progressCallback: this.progressCallback },
); );
if (this.props.keyCallback) { if (this.props.keyCallback) {
const key = await MatrixClientPeg.get().keyBackupKeyFromPassword( const key = await MatrixClientPeg.safeGet().keyBackupKeyFromPassword(
this.state.passPhrase, this.state.passPhrase,
this.state.backupInfo, this.state.backupInfo,
); );
@ -186,7 +186,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
restoreType: RestoreType.RecoveryKey, restoreType: RestoreType.RecoveryKey,
}); });
try { try {
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithRecoveryKey( const recoverInfo = await MatrixClientPeg.safeGet().restoreKeyBackupWithRecoveryKey(
this.state.recoveryKey, this.state.recoveryKey,
undefined, undefined,
undefined, undefined,
@ -194,7 +194,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
{ progressCallback: this.progressCallback }, { progressCallback: this.progressCallback },
); );
if (this.props.keyCallback) { if (this.props.keyCallback) {
const key = MatrixClientPeg.get().keyBackupKeyFromRecoveryKey(this.state.recoveryKey); const key = MatrixClientPeg.safeGet().keyBackupKeyFromRecoveryKey(this.state.recoveryKey);
this.props.keyCallback(key); this.props.keyCallback(key);
} }
if (!this.props.showSummary) { if (!this.props.showSummary) {
@ -230,7 +230,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
// `accessSecretStorage` may prompt for storage access as needed. // `accessSecretStorage` may prompt for storage access as needed.
await accessSecretStorage(async (): Promise<void> => { await accessSecretStorage(async (): Promise<void> => {
if (!this.state.backupInfo) return; if (!this.state.backupInfo) return;
await MatrixClientPeg.get().restoreKeyBackupWithSecretStorage( await MatrixClientPeg.safeGet().restoreKeyBackupWithSecretStorage(
this.state.backupInfo, this.state.backupInfo,
undefined, undefined,
undefined, undefined,
@ -252,7 +252,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
private async restoreWithCachedKey(backupInfo: IKeyBackupInfo | null): Promise<boolean> { private async restoreWithCachedKey(backupInfo: IKeyBackupInfo | null): Promise<boolean> {
if (!backupInfo) return false; if (!backupInfo) return false;
try { try {
const recoverInfo = await MatrixClientPeg.get().restoreKeyBackupWithCache( const recoverInfo = await MatrixClientPeg.safeGet().restoreKeyBackupWithCache(
undefined /* targetRoomId */, undefined /* targetRoomId */,
undefined /* targetSessionId */, undefined /* targetSessionId */,
backupInfo, backupInfo,
@ -274,7 +274,7 @@ export default class RestoreKeyBackupDialog extends React.PureComponent<IProps,
loadError: null, loadError: null,
}); });
try { try {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const backupInfo = await cli.getKeyBackupVersion(); const backupInfo = await cli.getKeyBackupVersion();
const has4S = await cli.hasSecretStorageKey(); const has4S = await cli.hasSecretStorageKey();
const backupKeyStored = has4S ? await cli.isKeyBackupKeyStored() : null; const backupKeyStored = has4S ? await cli.isKeyBackupKeyStored() : null;

View file

@ -171,7 +171,7 @@ const toPublicRoomResult = (publicRoom: IPublicRoomsChunkRoom): IPublicRoomResul
}); });
const toRoomResult = (room: Room): IRoomResult => { const toRoomResult = (room: Room): IRoomResult => {
const myUserId = MatrixClientPeg.get().getUserId(); const myUserId = MatrixClientPeg.safeGet().getUserId();
const otherUserId = DMRoomMap.shared().getUserIdForRoomId(room.roomId); const otherUserId = DMRoomMap.shared().getUserIdForRoomId(room.roomId);
if (otherUserId) { if (otherUserId) {
@ -281,7 +281,7 @@ interface IDirectoryOpts {
const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = null, onFinished }) => { const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = null, onFinished }) => {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null); const scrollContainerRef = useRef<HTMLDivElement>(null);
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const rovingContext = useContext(RovingTabIndexContext); const rovingContext = useContext(RovingTabIndexContext);
const [query, _setQuery] = useState(initialText); const [query, _setQuery] = useState(initialText);
const [recentSearches, clearRecentSearches] = useRecentSearches(); const [recentSearches, clearRecentSearches] = useRecentSearches();

View file

@ -42,7 +42,7 @@ const validServer = withValidation<undefined, { error?: MatrixError }>({
deriveData: async ({ value }): Promise<{ error?: MatrixError }> => { deriveData: async ({ value }): Promise<{ error?: MatrixError }> => {
try { try {
// check if we can successfully load this server's room directory // check if we can successfully load this server's room directory
await MatrixClientPeg.get().publicRooms({ await MatrixClientPeg.safeGet().publicRooms({
limit: 1, limit: 1,
server: value ?? undefined, server: value ?? undefined,
}); });

View file

@ -57,7 +57,7 @@ export default class AppPermission extends React.Component<IProps, IState> {
const urlInfo = this.parseWidgetUrl(); const urlInfo = this.parseWidgetUrl();
// The second step is to find the user's profile so we can show it on the prompt // The second step is to find the user's profile so we can show it on the prompt
const room = MatrixClientPeg.get().getRoom(this.props.roomId); const room = MatrixClientPeg.safeGet().getRoom(this.props.roomId);
let roomMember: RoomMember | null = null; let roomMember: RoomMember | null = null;
if (room) roomMember = room.getMember(this.props.creatorUserId); if (room) roomMember = room.getMember(this.props.creatorUserId);

View file

@ -60,8 +60,8 @@ export default class ErrorBoundary extends React.PureComponent<Props, IState> {
private onClearCacheAndReload = (): void => { private onClearCacheAndReload = (): void => {
if (!PlatformPeg.get()) return; if (!PlatformPeg.get()) return;
MatrixClientPeg.get().stopClient(); MatrixClientPeg.safeGet().stopClient();
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.store.deleteAllData() .store.deleteAllData()
.then(() => { .then(() => {
PlatformPeg.get()?.reload(); PlatformPeg.get()?.reload();

View file

@ -162,7 +162,7 @@ export default class PersistedElement extends React.Component<IProps> {
private renderApp(): void { private renderApp(): void {
const content = ( const content = (
<MatrixClientContext.Provider value={MatrixClientPeg.get()}> <MatrixClientContext.Provider value={MatrixClientPeg.safeGet()}>
<div ref={this.collectChild} style={this.props.style}> <div ref={this.collectChild} style={this.props.style}>
{this.props.children} {this.props.children}
</div> </div>

View file

@ -106,7 +106,7 @@ export const Pill: React.FC<PillProps> = ({ type: propType, url, inMessage, room
mx_RoomPill: type === PillType.RoomMention, mx_RoomPill: type === PillType.RoomMention,
mx_SpacePill: type === "space", mx_SpacePill: type === "space",
mx_UserPill: type === PillType.UserMention, mx_UserPill: type === PillType.UserMention,
mx_UserPill_me: resourceId === MatrixClientPeg.get().getUserId(), mx_UserPill_me: resourceId === MatrixClientPeg.safeGet().getUserId(),
mx_EventPill: type === PillType.EventInOtherRoom || type === PillType.EventInSameRoom, mx_EventPill: type === PillType.EventInOtherRoom || type === PillType.EventInSameRoom,
}); });
@ -158,7 +158,7 @@ export const Pill: React.FC<PillProps> = ({ type: propType, url, inMessage, room
return ( return (
<bdi> <bdi>
<MatrixClientContext.Provider value={MatrixClientPeg.get()}> <MatrixClientContext.Provider value={MatrixClientPeg.safeGet()}>
{inMessage && url ? ( {inMessage && url ? (
<a <a
className={classes} className={classes}

View file

@ -95,7 +95,7 @@ export default class ReplyChain extends React.Component<IProps, IState> {
} }
private get matrixClient(): MatrixClient { private get matrixClient(): MatrixClient {
return MatrixClientPeg.get(); return MatrixClientPeg.safeGet();
} }
public componentDidMount(): void { public componentDidMount(): void {

View file

@ -77,7 +77,7 @@ class ReactionPicker extends React.Component<IProps, IState> {
if (!this.props.reactions) { if (!this.props.reactions) {
return {}; return {};
} }
const userId = MatrixClientPeg.get().getUserId()!; const userId = MatrixClientPeg.safeGet().getSafeUserId();
const myAnnotations = this.props.reactions.getAnnotationsBySender()?.[userId] ?? new Set<MatrixEvent>(); const myAnnotations = this.props.reactions.getAnnotationsBySender()?.[userId] ?? new Set<MatrixEvent>();
return Object.fromEntries( return Object.fromEntries(
[...myAnnotations] [...myAnnotations]
@ -99,7 +99,7 @@ class ReactionPicker extends React.Component<IProps, IState> {
if (myReactions.hasOwnProperty(reaction)) { if (myReactions.hasOwnProperty(reaction)) {
if (this.props.mxEvent.isRedacted() || !this.context.canSelfRedact) return false; if (this.props.mxEvent.isRedacted() || !this.context.canSelfRedact) return false;
MatrixClientPeg.get().redactEvent(this.props.mxEvent.getRoomId()!, myReactions[reaction]); MatrixClientPeg.safeGet().redactEvent(this.props.mxEvent.getRoomId()!, myReactions[reaction]);
dis.dispatch<FocusComposerPayload>({ dis.dispatch<FocusComposerPayload>({
action: Action.FocusAComposer, action: Action.FocusAComposer,
context: this.context.timelineRenderingType, context: this.context.timelineRenderingType,
@ -107,7 +107,7 @@ class ReactionPicker extends React.Component<IProps, IState> {
// Tell the emoji picker not to bump this in the more frequently used list. // Tell the emoji picker not to bump this in the more frequently used list.
return false; return false;
} else { } else {
MatrixClientPeg.get().sendEvent(this.props.mxEvent.getRoomId()!, EventType.Reaction, { MatrixClientPeg.safeGet().sendEvent(this.props.mxEvent.getRoomId()!, EventType.Reaction, {
"m.relates_to": { "m.relates_to": {
rel_type: RelationType.Annotation, rel_type: RelationType.Annotation,
event_id: this.props.mxEvent.getId(), event_id: this.props.mxEvent.getId(),

View file

@ -125,7 +125,7 @@ export default class DateSeparator extends React.Component<IProps, IState> {
const roomIdForJumpRequest = this.props.roomId; const roomIdForJumpRequest = this.props.roomId;
try { try {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const { event_id: eventId, origin_server_ts: originServerTs } = await cli.timestampToEvent( const { event_id: eventId, origin_server_ts: originServerTs } = await cli.timestampToEvent(
roomIdForJumpRequest, roomIdForJumpRequest,
unixTimestamp, unixTimestamp,

View file

@ -36,7 +36,7 @@ const ALGORITHM = "m.megolm.v1.aes-sha2";
const EncryptionEvent = forwardRef<HTMLDivElement, IProps>(({ mxEvent, timestamp }, ref) => { const EncryptionEvent = forwardRef<HTMLDivElement, IProps>(({ mxEvent, timestamp }, ref) => {
const cli = useContext(MatrixClientContext); const cli = useContext(MatrixClientContext);
const roomId = mxEvent.getRoomId()!; const roomId = mxEvent.getRoomId()!;
const isRoomEncrypted = MatrixClientPeg.get().isRoomEncrypted(roomId); const isRoomEncrypted = MatrixClientPeg.safeGet().isRoomEncrypted(roomId);
const prevContent = mxEvent.getPrevContent() as IRoomEncryption; const prevContent = mxEvent.getPrevContent() as IRoomEncryption;
const content = mxEvent.getContent<IRoomEncryption>(); const content = mxEvent.getContent<IRoomEncryption>();

View file

@ -160,7 +160,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
}; };
private clearError = (): void => { private clearError = (): void => {
MatrixClientPeg.get().off(ClientEvent.Sync, this.reconnectedListener); MatrixClientPeg.get()?.off(ClientEvent.Sync, this.reconnectedListener);
this.setState({ imgError: false }); this.setState({ imgError: false });
}; };
@ -177,7 +177,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
this.setState({ this.setState({
imgError: true, imgError: true,
}); });
MatrixClientPeg.get().on(ClientEvent.Sync, this.reconnectedListener); MatrixClientPeg.safeGet().on(ClientEvent.Sync, this.reconnectedListener);
}; };
private onImageLoad = (): void => { private onImageLoad = (): void => {
@ -373,7 +373,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
public componentWillUnmount(): void { public componentWillUnmount(): void {
this.unmounted = true; this.unmounted = true;
MatrixClientPeg.get().off(ClientEvent.Sync, this.reconnectedListener); MatrixClientPeg.get()?.off(ClientEvent.Sync, this.reconnectedListener);
this.clearBlurhashTimeout(); this.clearBlurhashTimeout();
if (this.sizeWatcher) SettingsStore.unwatchSetting(this.sizeWatcher); if (this.sizeWatcher) SettingsStore.unwatchSetting(this.sizeWatcher);
if (this.state.isAnimated && this.state.thumbUrl) { if (this.state.isAnimated && this.state.thumbUrl) {

View file

@ -37,7 +37,7 @@ export default class MJitsiWidgetEvent extends React.PureComponent<IProps> {
const url = this.props.mxEvent.getContent()["url"]; const url = this.props.mxEvent.getContent()["url"];
const prevUrl = this.props.mxEvent.getPrevContent()["url"]; const prevUrl = this.props.mxEvent.getPrevContent()["url"];
const senderName = this.props.mxEvent.sender?.name || this.props.mxEvent.getSender(); const senderName = this.props.mxEvent.sender?.name || this.props.mxEvent.getSender();
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
if (!room) return null; if (!room) return null;
const widgetId = this.props.mxEvent.getStateKey(); const widgetId = this.props.mxEvent.getStateKey();
const widget = WidgetStore.instance.getRoom(room.roomId, true).widgets.find((w) => w.id === widgetId); const widget = WidgetStore.instance.getRoom(room.roomId, true).widgets.find((w) => w.id === widgetId);

View file

@ -42,7 +42,7 @@ export default class MKeyVerificationConclusion extends React.Component<IProps>
if (request) { if (request) {
request.on(VerificationRequestEvent.Change, this.onRequestChanged); request.on(VerificationRequestEvent.Change, this.onRequestChanged);
} }
MatrixClientPeg.get().on(CryptoEvent.UserTrustStatusChanged, this.onTrustChanged); MatrixClientPeg.safeGet().on(CryptoEvent.UserTrustStatusChanged, this.onTrustChanged);
} }
public componentWillUnmount(): void { public componentWillUnmount(): void {
@ -89,7 +89,7 @@ export default class MKeyVerificationConclusion extends React.Component<IProps>
} }
// User isn't actually verified // User isn't actually verified
if (!MatrixClientPeg.get().checkUserTrust(request.otherUserId).isCrossSigningVerified()) { if (!MatrixClientPeg.safeGet().checkUserTrust(request.otherUserId).isCrossSigningVerified()) {
return false; return false;
} }
@ -104,7 +104,7 @@ export default class MKeyVerificationConclusion extends React.Component<IProps>
return null; return null;
} }
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const myUserId = client.getUserId(); const myUserId = client.getUserId();
let title: string | undefined; let title: string | undefined;

View file

@ -55,7 +55,7 @@ export default class MKeyVerificationRequest extends React.Component<IProps> {
let member: User | undefined; let member: User | undefined;
const { verificationRequest } = this.props.mxEvent; const { verificationRequest } = this.props.mxEvent;
if (verificationRequest) { if (verificationRequest) {
member = MatrixClientPeg.get().getUser(verificationRequest.otherUserId) ?? undefined; member = MatrixClientPeg.safeGet().getUser(verificationRequest.otherUserId) ?? undefined;
} }
RightPanelStore.instance.setCards([ RightPanelStore.instance.setCards([
{ phase: RightPanelPhases.RoomSummary }, { phase: RightPanelPhases.RoomSummary },
@ -92,7 +92,7 @@ export default class MKeyVerificationRequest extends React.Component<IProps> {
}; };
private acceptedLabel(userId: string): string { private acceptedLabel(userId: string): string {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const myUserId = client.getUserId(); const myUserId = client.getUserId();
if (userId === myUserId) { if (userId === myUserId) {
return _t("You accepted"); return _t("You accepted");
@ -104,7 +104,7 @@ export default class MKeyVerificationRequest extends React.Component<IProps> {
} }
private cancelledLabel(userId: string): string { private cancelledLabel(userId: string): string {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const myUserId = client.getUserId(); const myUserId = client.getUserId();
const cancellationCode = this.props.mxEvent.verificationRequest?.cancellationCode; const cancellationCode = this.props.mxEvent.verificationRequest?.cancellationCode;
const declined = cancellationCode === "m.user"; const declined = cancellationCode === "m.user";
@ -128,7 +128,7 @@ export default class MKeyVerificationRequest extends React.Component<IProps> {
} }
public render(): React.ReactNode { public render(): React.ReactNode {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const { mxEvent } = this.props; const { mxEvent } = this.props;
const request = mxEvent.verificationRequest; const request = mxEvent.verificationRequest;

View file

@ -118,7 +118,7 @@ export function pollAlreadyHasVotes(mxEvent: MatrixEvent, getRelationsForEvent?:
} }
export function launchPollEditor(mxEvent: MatrixEvent, getRelationsForEvent?: GetRelationsForEvent): void { export function launchPollEditor(mxEvent: MatrixEvent, getRelationsForEvent?: GetRelationsForEvent): void {
const room = MatrixClientPeg.get().getRoom(mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(mxEvent.getRoomId());
if (pollAlreadyHasVotes(mxEvent, getRelationsForEvent)) { if (pollAlreadyHasVotes(mxEvent, getRelationsForEvent)) {
Modal.createDialog(ErrorDialog, { Modal.createDialog(ErrorDialog, {
title: _t("Can't edit poll"), title: _t("Can't edit poll"),

View file

@ -311,7 +311,7 @@ export default class MessageActionBar extends React.PureComponent<IMessageAction
this.props.mxEvent.on(MatrixEventEvent.Status, this.onSent); this.props.mxEvent.on(MatrixEventEvent.Status, this.onSent);
} }
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
client.decryptEventIfNeeded(this.props.mxEvent); client.decryptEventIfNeeded(this.props.mxEvent);
if (this.props.mxEvent.isBeingDecrypted()) { if (this.props.mxEvent.isBeingDecrypted()) {
@ -364,7 +364,7 @@ export default class MessageActionBar extends React.PureComponent<IMessageAction
e.stopPropagation(); e.stopPropagation();
editEvent( editEvent(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
this.props.mxEvent, this.props.mxEvent,
this.context.timelineRenderingType, this.context.timelineRenderingType,
this.props.getRelationsForEvent, this.props.getRelationsForEvent,
@ -417,19 +417,19 @@ export default class MessageActionBar extends React.PureComponent<IMessageAction
ev.preventDefault(); ev.preventDefault();
ev.stopPropagation(); ev.stopPropagation();
this.runActionOnFailedEv((tarEv) => Resend.resend(MatrixClientPeg.get(), tarEv)); this.runActionOnFailedEv((tarEv) => Resend.resend(MatrixClientPeg.safeGet(), tarEv));
}; };
private onCancelClick = (ev: ButtonEvent): void => { private onCancelClick = (ev: ButtonEvent): void => {
this.runActionOnFailedEv( this.runActionOnFailedEv(
(tarEv) => Resend.removeFromQueue(MatrixClientPeg.get(), tarEv), (tarEv) => Resend.removeFromQueue(MatrixClientPeg.safeGet(), tarEv),
(testEv) => canCancel(testEv.status), (testEv) => canCancel(testEv.status),
); );
}; };
public render(): React.ReactNode { public render(): React.ReactNode {
const toolbarOpts: JSX.Element[] = []; const toolbarOpts: JSX.Element[] = [];
if (canEditContent(MatrixClientPeg.get(), this.props.mxEvent)) { if (canEditContent(MatrixClientPeg.safeGet(), this.props.mxEvent)) {
toolbarOpts.push( toolbarOpts.push(
<RovingAccessibleTooltipButton <RovingAccessibleTooltipButton
className="mx_MessageActionBar_iconButton" className="mx_MessageActionBar_iconButton"

View file

@ -33,7 +33,7 @@ interface IProps {
export default class RoomAvatarEvent extends React.Component<IProps> { export default class RoomAvatarEvent extends React.Component<IProps> {
private onAvatarClick = (): void => { private onAvatarClick = (): void => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const ev = this.props.mxEvent; const ev = this.props.mxEvent;
const httpUrl = mediaFromMxc(ev.getContent().url).srcHttp; const httpUrl = mediaFromMxc(ev.getContent().url).srcHttp;
if (!httpUrl) return; if (!httpUrl) return;
@ -63,7 +63,7 @@ export default class RoomAvatarEvent extends React.Component<IProps> {
); );
} }
const room = MatrixClientPeg.get().getRoom(ev.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(ev.getRoomId());
// Provide all arguments to RoomAvatar via oobData because the avatar is historic // Provide all arguments to RoomAvatar via oobData because the avatar is historic
const oobData = { const oobData = {
avatarUrl: ev.getContent().url, avatarUrl: ev.getContent().url,

View file

@ -87,7 +87,7 @@ export const RoomPredecessorTile: React.FC<IProps> = ({ mxEvent, timestamp }) =>
return <div />; return <div />;
} }
const prevRoom = MatrixClientPeg.get().getRoom(predecessor.roomId); const prevRoom = MatrixClientPeg.safeGet().getRoom(predecessor.roomId);
// We need either the previous room, or some servers to find it with. // We need either the previous room, or some servers to find it with.
// Otherwise, we must bail out here // Otherwise, we must bail out here

View file

@ -93,7 +93,7 @@ export default class TextualBody extends React.Component<IBodyProps, IState> {
this.activateSpoilers([content]); this.activateSpoilers([content]);
HtmlUtils.linkifyElement(content); HtmlUtils.linkifyElement(content);
pillifyLinks(MatrixClientPeg.get(), [content], this.props.mxEvent, this.pills); pillifyLinks(MatrixClientPeg.safeGet(), [content], this.props.mxEvent, this.pills);
this.calculateUrlPreview(); this.calculateUrlPreview();

View file

@ -31,7 +31,7 @@ export default class TextualEvent extends React.Component<IProps> {
public render(): React.ReactNode { public render(): React.ReactNode {
const text = TextForEvent.textForEvent( const text = TextForEvent.textForEvent(
this.props.mxEvent, this.props.mxEvent,
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
true, true,
this.context?.showHiddenEvents, this.context?.showHiddenEvents,
); );

View file

@ -42,7 +42,7 @@ export default class ViewSourceEvent extends React.PureComponent<IProps, IState>
public componentDidMount(): void { public componentDidMount(): void {
const { mxEvent } = this.props; const { mxEvent } = this.props;
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
client.decryptEventIfNeeded(mxEvent); client.decryptEventIfNeeded(mxEvent);
if (mxEvent.isBeingDecrypted()) { if (mxEvent.isBeingDecrypted()) {

View file

@ -52,7 +52,7 @@ export default class RoomProfileSettings extends React.Component<IProps, IState>
public constructor(props: IProps) { public constructor(props: IProps) {
super(props); super(props);
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const room = client.getRoom(props.roomId); const room = client.getRoom(props.roomId);
if (!room) throw new Error(`Expected a room for ID: ${props.roomId}`); if (!room) throw new Error(`Expected a room for ID: ${props.roomId}`);
@ -124,7 +124,7 @@ export default class RoomProfileSettings extends React.Component<IProps, IState>
if (!this.isSaveEnabled()) return; if (!this.isSaveEnabled()) return;
this.setState({ profileFieldsTouched: {} }); this.setState({ profileFieldsTouched: {} });
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const newState: Partial<IState> = {}; const newState: Partial<IState> = {};
// TODO: What do we do about errors? // TODO: What do we do about errors?

View file

@ -45,7 +45,7 @@ export default class RoomPublishSetting extends React.PureComponent<IProps, ISta
const valueBefore = this.state.isRoomPublished; const valueBefore = this.state.isRoomPublished;
const newValue = !valueBefore; const newValue = !valueBefore;
this.setState({ isRoomPublished: newValue }); this.setState({ isRoomPublished: newValue });
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
client client
.setRoomDirectoryVisibility(this.props.roomId, newValue ? Visibility.Public : Visibility.Private) .setRoomDirectoryVisibility(this.props.roomId, newValue ? Visibility.Public : Visibility.Private)
@ -56,14 +56,14 @@ export default class RoomPublishSetting extends React.PureComponent<IProps, ISta
}; };
public componentDidMount(): void { public componentDidMount(): void {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
client.getRoomDirectoryVisibility(this.props.roomId).then((result) => { client.getRoomDirectoryVisibility(this.props.roomId).then((result) => {
this.setState({ isRoomPublished: result.visibility === "public" }); this.setState({ isRoomPublished: result.visibility === "public" });
}); });
} }
public render(): React.ReactNode { public render(): React.ReactNode {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const room = client.getRoom(this.props.roomId); const room = client.getRoom(this.props.roomId);
const isRoomPublishable = room && room.getJoinRule() !== JoinRule.Invite; const isRoomPublishable = room && room.getJoinRule() !== JoinRule.Invite;

View file

@ -43,7 +43,7 @@ export default class UrlPreviewSettings extends React.Component<IProps> {
public render(): ReactNode { public render(): ReactNode {
const roomId = this.props.room.roomId; const roomId = this.props.room.roomId;
const isEncrypted = MatrixClientPeg.get().isRoomEncrypted(roomId); const isEncrypted = MatrixClientPeg.safeGet().isRoomEncrypted(roomId);
let previewsForAccount: ReactNode | undefined; let previewsForAccount: ReactNode | undefined;
let previewsForRoom: ReactNode | undefined; let previewsForRoom: ReactNode | undefined;

View file

@ -65,7 +65,7 @@ export default class AuxPanel extends React.Component<IProps, IState> {
} }
public componentDidMount(): void { public componentDidMount(): void {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
if (SettingsStore.getValue("feature_state_counters")) { if (SettingsStore.getValue("feature_state_counters")) {
cli.on(RoomStateEvent.Events, this.onRoomStateEvents); cli.on(RoomStateEvent.Events, this.onRoomStateEvents);
} }

View file

@ -182,7 +182,7 @@ class EditMessageComposer extends React.Component<IEditMessageComposerProps, ISt
events: this.events, events: this.events,
isForward: false, isForward: false,
fromEventId: this.props.editState.getEvent().getId(), fromEventId: this.props.editState.getEvent().getId(),
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
}); });
if (previousEvent) { if (previousEvent) {
dis.dispatch({ dis.dispatch({
@ -202,7 +202,7 @@ class EditMessageComposer extends React.Component<IEditMessageComposerProps, ISt
events: this.events, events: this.events,
isForward: true, isForward: true,
fromEventId: this.props.editState.getEvent().getId(), fromEventId: this.props.editState.getEvent().getId(),
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
}); });
if (nextEvent) { if (nextEvent) {
dis.dispatch({ dis.dispatch({
@ -342,7 +342,7 @@ class EditMessageComposer extends React.Component<IEditMessageComposerProps, ISt
if (cmd) { if (cmd) {
const threadId = editedEvent?.getThread()?.id || null; const threadId = editedEvent?.getThread()?.id || null;
const [content, commandSuccessful] = await runSlashCommand( const [content, commandSuccessful] = await runSlashCommand(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
cmd, cmd,
args, args,
roomId, roomId,

View file

@ -307,12 +307,12 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
if (!this.props.mxEvent) return false; if (!this.props.mxEvent) return false;
// Sanity check (should never happen, but we shouldn't explode if it does) // Sanity check (should never happen, but we shouldn't explode if it does)
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
if (!room) return false; if (!room) return false;
// Quickly check to see if the event was sent by us. If it wasn't, it won't qualify for // Quickly check to see if the event was sent by us. If it wasn't, it won't qualify for
// special read receipts. // special read receipts.
const myUserId = MatrixClientPeg.get().getUserId(); const myUserId = MatrixClientPeg.safeGet().getUserId();
if (this.props.mxEvent.getSender() !== myUserId) return false; if (this.props.mxEvent.getSender() !== myUserId) return false;
// Finally, determine if the type is relevant to the user. This notably excludes state // Finally, determine if the type is relevant to the user. This notably excludes state
@ -344,7 +344,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
// If anyone has read the event besides us, we don't want to show a sent receipt. // If anyone has read the event besides us, we don't want to show a sent receipt.
const receipts = this.props.readReceipts || []; const receipts = this.props.readReceipts || [];
const myUserId = MatrixClientPeg.get().getUserId(); const myUserId = MatrixClientPeg.safeGet().getUserId();
if (receipts.some((r) => r.userId !== myUserId)) return false; if (receipts.some((r) => r.userId !== myUserId)) return false;
// Finally, we should show a receipt. // Finally, we should show a receipt.
@ -366,7 +366,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
public componentDidMount(): void { public componentDidMount(): void {
this.suppressReadReceiptAnimation = false; this.suppressReadReceiptAnimation = false;
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
if (!this.props.forExport) { if (!this.props.forExport) {
client.on(CryptoEvent.DeviceVerificationChanged, this.onDeviceVerificationChanged); client.on(CryptoEvent.DeviceVerificationChanged, this.onDeviceVerificationChanged);
client.on(CryptoEvent.UserTrustStatusChanged, this.onUserVerificationChanged); client.on(CryptoEvent.UserTrustStatusChanged, this.onUserVerificationChanged);
@ -431,7 +431,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
} }
// If we're not listening for receipts and expect to be, register a listener. // If we're not listening for receipts and expect to be, register a listener.
if (!this.isListeningForReceipts && (this.shouldShowSentReceipt || this.shouldShowSendingReceipt)) { if (!this.isListeningForReceipts && (this.shouldShowSentReceipt || this.shouldShowSendingReceipt)) {
MatrixClientPeg.get().on(RoomEvent.Receipt, this.onRoomReceipt); MatrixClientPeg.safeGet().on(RoomEvent.Receipt, this.onRoomReceipt);
this.isListeningForReceipts = true; this.isListeningForReceipts = true;
} }
// re-check the sender verification as outgoing events progress through the send process. // re-check the sender verification as outgoing events progress through the send process.
@ -443,7 +443,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
private onNewThread = (thread: Thread): void => { private onNewThread = (thread: Thread): void => {
if (thread.id === this.props.mxEvent.getId()) { if (thread.id === this.props.mxEvent.getId()) {
this.updateThread(thread); this.updateThread(thread);
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
room?.off(ThreadEvent.New, this.onNewThread); room?.off(ThreadEvent.New, this.onNewThread);
} }
}; };
@ -457,7 +457,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
* when we are at the sync stage * when we are at the sync stage
*/ */
if (!thread) { if (!thread) {
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
thread = room?.findThreadForEvent(this.props.mxEvent) ?? undefined; thread = room?.findThreadForEvent(this.props.mxEvent) ?? undefined;
} }
return thread ?? null; return thread ?? null;
@ -519,7 +519,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
private onRoomReceipt = (ev: MatrixEvent, room: Room): void => { private onRoomReceipt = (ev: MatrixEvent, room: Room): void => {
// ignore events for other rooms // ignore events for other rooms
const tileRoom = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const tileRoom = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
if (room !== tileRoom) return; if (room !== tileRoom) return;
if (!this.shouldShowSentReceipt && !this.shouldShowSendingReceipt && !this.isListeningForReceipts) { if (!this.shouldShowSentReceipt && !this.shouldShowSendingReceipt && !this.isListeningForReceipts) {
@ -531,7 +531,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
this.forceUpdate(() => { this.forceUpdate(() => {
// Per elsewhere in this file, we can remove the listener once we will have no further purpose for it. // Per elsewhere in this file, we can remove the listener once we will have no further purpose for it.
if (!this.shouldShowSentReceipt && !this.shouldShowSendingReceipt) { if (!this.shouldShowSentReceipt && !this.shouldShowSendingReceipt) {
MatrixClientPeg.get().removeListener(RoomEvent.Receipt, this.onRoomReceipt); MatrixClientPeg.safeGet().removeListener(RoomEvent.Receipt, this.onRoomReceipt);
this.isListeningForReceipts = false; this.isListeningForReceipts = false;
} }
}); });
@ -574,7 +574,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
return; return;
} }
const encryptionInfo = MatrixClientPeg.get().getEventEncryptionInfo(mxEvent); const encryptionInfo = MatrixClientPeg.safeGet().getEventEncryptionInfo(mxEvent);
const senderId = mxEvent.getSender(); const senderId = mxEvent.getSender();
if (!senderId) { if (!senderId) {
// something definitely wrong is going on here // something definitely wrong is going on here
@ -582,7 +582,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
return; return;
} }
const userTrust = MatrixClientPeg.get().checkUserTrust(senderId); const userTrust = MatrixClientPeg.safeGet().checkUserTrust(senderId);
if (encryptionInfo.mismatchedSender) { if (encryptionInfo.mismatchedSender) {
// something definitely wrong is going on here // something definitely wrong is going on here
@ -601,7 +601,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
const eventSenderTrust = const eventSenderTrust =
senderId && senderId &&
encryptionInfo.sender && encryptionInfo.sender &&
(await MatrixClientPeg.get() (await MatrixClientPeg.safeGet()
.getCrypto() .getCrypto()
?.getDeviceVerificationStatus(senderId, encryptionInfo.sender.deviceId)); ?.getDeviceVerificationStatus(senderId, encryptionInfo.sender.deviceId));
@ -686,7 +686,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
if (this.context.timelineRenderingType === TimelineRenderingType.Notification) return false; if (this.context.timelineRenderingType === TimelineRenderingType.Notification) return false;
if (this.context.timelineRenderingType === TimelineRenderingType.ThreadsList) return false; if (this.context.timelineRenderingType === TimelineRenderingType.ThreadsList) return false;
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const actions = cli.getPushActionsForEvent(this.props.mxEvent.replacingEvent() || this.props.mxEvent); const actions = cli.getPushActionsForEvent(this.props.mxEvent.replacingEvent() || this.props.mxEvent);
// get the actions for the previous version of the event too if it is an edit // get the actions for the previous version of the event too if it is an edit
const previousActions = this.props.mxEvent.replacingEvent() const previousActions = this.props.mxEvent.replacingEvent()
@ -697,7 +697,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
} }
// don't show self-highlights from another of our clients // don't show self-highlights from another of our clients
if (this.props.mxEvent.getSender() === MatrixClientPeg.get().credentials.userId) { if (this.props.mxEvent.getSender() === cli.credentials.userId) {
return false; return false;
} }
@ -754,7 +754,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
} }
} }
if (MatrixClientPeg.get().isRoomEncrypted(ev.getRoomId()!)) { if (MatrixClientPeg.safeGet().isRoomEncrypted(ev.getRoomId()!)) {
// else if room is encrypted // else if room is encrypted
// and event is being encrypted or is not_sent (Unknown Devices/Network Error) // and event is being encrypted or is not_sent (Unknown Devices/Network Error)
if (ev.status === EventStatus.ENCRYPTING) { if (ev.status === EventStatus.ENCRYPTING) {
@ -904,7 +904,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
noBubbleEvent, noBubbleEvent,
isSeeingThroughMessageHiddenForModeration, isSeeingThroughMessageHiddenForModeration,
} = getEventDisplayInfo( } = getEventDisplayInfo(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
this.props.mxEvent, this.props.mxEvent,
this.context.showHiddenEvents, this.context.showHiddenEvents,
this.shouldHideEvent(), this.shouldHideEvent(),
@ -1186,7 +1186,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
} }
// Use `getSender()` because searched events might not have a proper `sender`. // Use `getSender()` because searched events might not have a proper `sender`.
const isOwnEvent = this.props.mxEvent?.getSender() === MatrixClientPeg.get().getUserId(); const isOwnEvent = this.props.mxEvent?.getSender() === MatrixClientPeg.safeGet().getUserId();
switch (this.context.timelineRenderingType) { switch (this.context.timelineRenderingType) {
case TimelineRenderingType.Thread: { case TimelineRenderingType.Thread: {
@ -1242,7 +1242,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
} }
case TimelineRenderingType.Notification: case TimelineRenderingType.Notification:
case TimelineRenderingType.ThreadsList: { case TimelineRenderingType.ThreadsList: {
const room = MatrixClientPeg.get().getRoom(this.props.mxEvent.getRoomId()); const room = MatrixClientPeg.safeGet().getRoom(this.props.mxEvent.getRoomId());
// tab-index=-1 to allow it to be focusable but do not add tab stop for it, primarily for screen readers // tab-index=-1 to allow it to be focusable but do not add tab stop for it, primarily for screen readers
return React.createElement( return React.createElement(
this.props.as || "li", this.props.as || "li",

View file

@ -84,7 +84,7 @@ export default class MemberList extends React.Component<IProps, IState> {
} }
private listenForMembersChanges(): void { private listenForMembersChanges(): void {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
cli.on(RoomStateEvent.Update, this.onRoomStateUpdate); cli.on(RoomStateEvent.Update, this.onRoomStateUpdate);
cli.on(RoomMemberEvent.Name, this.onRoomMemberName); cli.on(RoomMemberEvent.Name, this.onRoomMemberName);
cli.on(RoomStateEvent.Events, this.onRoomStateEvent); cli.on(RoomStateEvent.Events, this.onRoomStateEvent);
@ -121,7 +121,7 @@ export default class MemberList extends React.Component<IProps, IState> {
} }
private get canInvite(): boolean { private get canInvite(): boolean {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.roomId); const room = cli.getRoom(this.props.roomId);
return ( return (
@ -284,7 +284,7 @@ export default class MemberList extends React.Component<IProps, IState> {
// The HS may have already converted these into m.room.member invites so // The HS may have already converted these into m.room.member invites so
// we shouldn't add them if the 3pid invite state key (token) is in the // we shouldn't add them if the 3pid invite state key (token) is in the
// member invite (content.third_party_invite.signed.token) // member invite (content.third_party_invite.signed.token)
const room = MatrixClientPeg.get().getRoom(this.props.roomId); const room = MatrixClientPeg.safeGet().getRoom(this.props.roomId);
if (room) { if (room) {
return room.currentState.getStateEvents("m.room.third_party_invite").filter(function (e) { return room.currentState.getStateEvents("m.room.third_party_invite").filter(function (e) {
@ -348,7 +348,7 @@ export default class MemberList extends React.Component<IProps, IState> {
); );
} }
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.roomId); const room = cli.getRoom(this.props.roomId);
let inviteButton: JSX.Element | undefined; let inviteButton: JSX.Element | undefined;
@ -442,7 +442,7 @@ export default class MemberList extends React.Component<IProps, IState> {
private onInviteButtonClick = (ev: ButtonEvent): void => { private onInviteButtonClick = (ev: ButtonEvent): void => {
PosthogTrackers.trackInteraction("WebRightPanelMemberListInviteButton", ev); PosthogTrackers.trackInteraction("WebRightPanelMemberListInviteButton", ev);
if (MatrixClientPeg.get().isGuest()) { if (MatrixClientPeg.safeGet().isGuest()) {
dis.dispatch({ action: "require_registration" }); dis.dispatch({ action: "require_registration" });
return; return;
} }

View file

@ -62,7 +62,7 @@ export default class MemberTile extends React.Component<IProps, IState> {
} }
public componentDidMount(): void { public componentDidMount(): void {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const { roomId } = this.props.member; const { roomId } = this.props.member;
if (roomId) { if (roomId) {
@ -97,7 +97,7 @@ export default class MemberTile extends React.Component<IProps, IState> {
if (ev.getRoomId() !== roomId) return; if (ev.getRoomId() !== roomId) return;
// The room is encrypted now. // The room is encrypted now.
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
cli.removeListener(RoomStateEvent.Events, this.onRoomStateEvents); cli.removeListener(RoomStateEvent.Events, this.onRoomStateEvents);
this.setState({ this.setState({
isRoomEncrypted: true, isRoomEncrypted: true,
@ -116,7 +116,7 @@ export default class MemberTile extends React.Component<IProps, IState> {
}; };
private async updateE2EStatus(): Promise<void> { private async updateE2EStatus(): Promise<void> {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const { userId } = this.props.member; const { userId } = this.props.member;
const isMe = userId === cli.getUserId(); const isMe = userId === cli.getUserId();
const userTrust = cli.checkUserTrust(userId); const userTrust = cli.checkUserTrust(userId);

View file

@ -243,7 +243,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
private waitForOwnMember(): void { private waitForOwnMember(): void {
// If we have the member already, do that // If we have the member already, do that
const me = this.props.room.getMember(MatrixClientPeg.get().getUserId()!); const me = this.props.room.getMember(MatrixClientPeg.safeGet().getUserId()!);
if (me) { if (me) {
this.setState({ me }); this.setState({ me });
return; return;
@ -252,7 +252,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
// The members should already be loading, and loadMembersIfNeeded // The members should already be loading, and loadMembersIfNeeded
// will return the promise for the existing operation // will return the promise for the existing operation
this.props.room.loadMembersIfNeeded().then(() => { this.props.room.loadMembersIfNeeded().then(() => {
const me = this.props.room.getMember(MatrixClientPeg.get().getSafeUserId()) ?? undefined; const me = this.props.room.getMember(MatrixClientPeg.safeGet().getSafeUserId()) ?? undefined;
this.setState({ me }); this.setState({ me });
}); });
} }
@ -271,7 +271,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
ev.preventDefault(); ev.preventDefault();
const replacementRoomId = this.context.tombstone?.getContent()["replacement_room"]; const replacementRoomId = this.context.tombstone?.getContent()["replacement_room"];
const replacementRoom = MatrixClientPeg.get().getRoom(replacementRoomId); const replacementRoom = MatrixClientPeg.safeGet().getRoom(replacementRoomId);
let createEventId: string | undefined; let createEventId: string | undefined;
if (replacementRoom) { if (replacementRoom) {
const createEvent = replacementRoom.currentState.getStateEvents(EventType.RoomCreate, ""); const createEvent = replacementRoom.currentState.getStateEvents(EventType.RoomCreate, "");
@ -527,7 +527,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
const continuesLink = replacementRoomId ? ( const continuesLink = replacementRoomId ? (
<a <a
href={makeRoomPermalink(MatrixClientPeg.get(), replacementRoomId)} href={makeRoomPermalink(MatrixClientPeg.safeGet(), replacementRoomId)}
className="mx_MessageComposer_roomReplaced_link" className="mx_MessageComposer_roomReplaced_link"
onClick={this.onTombstoneClick} onClick={this.onTombstoneClick}
> >
@ -636,7 +636,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
onStartVoiceBroadcastClick={() => { onStartVoiceBroadcastClick={() => {
setUpVoiceBroadcastPreRecording( setUpVoiceBroadcastPreRecording(
this.props.room, this.props.room,
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
SdkContextClass.instance.voiceBroadcastPlaybacksStore, SdkContextClass.instance.voiceBroadcastPlaybacksStore,
SdkContextClass.instance.voiceBroadcastRecordingsStore, SdkContextClass.instance.voiceBroadcastRecordingsStore,
SdkContextClass.instance.voiceBroadcastPreRecordingStore, SdkContextClass.instance.voiceBroadcastPreRecordingStore,

View file

@ -309,7 +309,7 @@ class PollButton extends React.PureComponent<IPollButtonProps> {
this.context?.(); // close overflow menu this.context?.(); // close overflow menu
const canSend = this.props.room.currentState.maySendEvent( const canSend = this.props.room.currentState.maySendEvent(
M_POLL_START.name, M_POLL_START.name,
MatrixClientPeg.get().getUserId()!, MatrixClientPeg.safeGet().getSafeUserId(),
); );
if (!canSend) { if (!canSend) {
Modal.createDialog(ErrorDialog, { Modal.createDialog(ErrorDialog, {

View file

@ -278,8 +278,11 @@ const NewRoomIntro: React.FC = () => {
"like email invites.", "like email invites.",
); );
let subButton; let subButton: JSX.Element | undefined;
if (room.currentState.mayClientSendStateEvent(EventType.RoomEncryption, MatrixClientPeg.get()) && !isLocalRoom) { if (
room.currentState.mayClientSendStateEvent(EventType.RoomEncryption, MatrixClientPeg.safeGet()) &&
!isLocalRoom
) {
subButton = ( subButton = (
<AccessibleButton kind="link_inline" onClick={openRoomSettings}> <AccessibleButton kind="link_inline" onClick={openRoomSettings}>
{_t("Enable encryption in settings.")} {_t("Enable encryption in settings.")}

View file

@ -111,7 +111,7 @@ export default class ReplyTile extends React.PureComponent<IProps> {
const evType = mxEvent.getType(); const evType = mxEvent.getType();
const { hasRenderer, isInfoMessage, isSeeingThroughMessageHiddenForModeration } = getEventDisplayInfo( const { hasRenderer, isInfoMessage, isSeeingThroughMessageHiddenForModeration } = getEventDisplayInfo(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
mxEvent, mxEvent,
false /* Replies are never hidden, so this should be fine */, false /* Replies are never hidden, so this should be fine */,
); );

View file

@ -222,7 +222,7 @@ const UntaggedAuxButton: React.FC<IAuxButtonProps> = ({ tabIndex }) => {
if (menuDisplayed && activeSpace) { if (menuDisplayed && activeSpace) {
const canAddRooms = activeSpace.currentState.maySendStateEvent( const canAddRooms = activeSpace.currentState.maySendStateEvent(
EventType.SpaceChild, EventType.SpaceChild,
MatrixClientPeg.get().getUserId()!, MatrixClientPeg.safeGet().getSafeUserId(),
); );
contextMenuContent = ( contextMenuContent = (

View file

@ -136,19 +136,19 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
this.setState({ busy: true }); this.setState({ busy: true });
try { try {
// Gather the account 3PIDs // Gather the account 3PIDs
const account3pids = await MatrixClientPeg.get().getThreePids(); const account3pids = await MatrixClientPeg.safeGet().getThreePids();
this.setState({ this.setState({
accountEmails: account3pids.threepids.filter((b) => b.medium === "email").map((b) => b.address), accountEmails: account3pids.threepids.filter((b) => b.medium === "email").map((b) => b.address),
}); });
// If we have an IS connected, use that to lookup the email and // If we have an IS connected, use that to lookup the email and
// check the bound MXID. // check the bound MXID.
if (!MatrixClientPeg.get().getIdentityServerUrl()) { if (!MatrixClientPeg.safeGet().getIdentityServerUrl()) {
this.setState({ busy: false }); this.setState({ busy: false });
return; return;
} }
const authClient = new IdentityAuthClient(); const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken(); const identityAccessToken = await authClient.getAccessToken();
const result = await MatrixClientPeg.get().lookupThreePid( const result = await MatrixClientPeg.safeGet().lookupThreePid(
"email", "email",
this.props.invitedEmail, this.props.invitedEmail,
identityAccessToken!, identityAccessToken!,
@ -162,7 +162,7 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
} }
private getMessageCase(): MessageCase { private getMessageCase(): MessageCase {
const isGuest = MatrixClientPeg.get().isGuest(); const isGuest = MatrixClientPeg.safeGet().isGuest();
if (isGuest) { if (isGuest) {
return MessageCase.NotLoggedIn; return MessageCase.NotLoggedIn;
@ -192,9 +192,9 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
return MessageCase.OtherThreePIDError; return MessageCase.OtherThreePIDError;
} else if (this.state.accountEmails && !this.state.accountEmails.includes(this.props.invitedEmail)) { } else if (this.state.accountEmails && !this.state.accountEmails.includes(this.props.invitedEmail)) {
return MessageCase.InvitedEmailNotFoundInAccount; return MessageCase.InvitedEmailNotFoundInAccount;
} else if (!MatrixClientPeg.get().getIdentityServerUrl()) { } else if (!MatrixClientPeg.safeGet().getIdentityServerUrl()) {
return MessageCase.InvitedEmailNoIdentityServer; return MessageCase.InvitedEmailNoIdentityServer;
} else if (this.state.invitedEmailMxid != MatrixClientPeg.get().getUserId()) { } else if (this.state.invitedEmailMxid != MatrixClientPeg.safeGet().getUserId()) {
return MessageCase.InvitedEmailMismatch; return MessageCase.InvitedEmailMismatch;
} }
} }
@ -232,7 +232,7 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
} }
private getMyMember(): RoomMember | null { private getMyMember(): RoomMember | null {
return this.props.room?.getMember(MatrixClientPeg.get().getUserId()!) ?? null; return this.props.room?.getMember(MatrixClientPeg.safeGet().getSafeUserId()) ?? null;
} }
private getInviteMember(): RoomMember | null { private getInviteMember(): RoomMember | null {
@ -240,7 +240,7 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
if (!room) { if (!room) {
return null; return null;
} }
const myUserId = MatrixClientPeg.get().getUserId()!; const myUserId = MatrixClientPeg.safeGet().getSafeUserId();
const inviteEvent = room.currentState.getMember(myUserId); const inviteEvent = room.currentState.getMember(myUserId);
if (!inviteEvent) { if (!inviteEvent) {
return null; return null;
@ -504,7 +504,7 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
primaryActionLabel = _t("Accept"); primaryActionLabel = _t("Accept");
} }
const myUserId = MatrixClientPeg.get().getUserId()!; const myUserId = MatrixClientPeg.safeGet().getSafeUserId();
const member = this.props.room?.currentState.getMember(myUserId); const member = this.props.room?.currentState.getMember(myUserId);
const memberEventContent = member?.events.member?.getContent(); const memberEventContent = member?.events.member?.getContent();

View file

@ -285,7 +285,7 @@ export class RoomTile extends React.PureComponent<ClassProps, State> {
private renderNotificationsMenu(isActive: boolean): React.ReactElement | null { private renderNotificationsMenu(isActive: boolean): React.ReactElement | null {
if ( if (
MatrixClientPeg.get().isGuest() || MatrixClientPeg.safeGet().isGuest() ||
this.props.tag === DefaultTagID.Archived || this.props.tag === DefaultTagID.Archived ||
!this.showContextMenu || !this.showContextMenu ||
this.props.isMinimized this.props.isMinimized

View file

@ -336,7 +336,7 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
? findEditableEvent({ ? findEditableEvent({
events, events,
isForward: false, isForward: false,
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
}) })
: undefined; : undefined;
if (editEvent) { if (editEvent) {
@ -404,7 +404,7 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
if (events[i].getType() === EventType.RoomMessage) { if (events[i].getType() === EventType.RoomMessage) {
let shouldReact = true; let shouldReact = true;
const lastMessage = events[i]; const lastMessage = events[i];
const userId = MatrixClientPeg.get().getSafeUserId(); const userId = MatrixClientPeg.safeGet().getSafeUserId();
const messageReactions = this.props.room.relations.getChildEventsForEvent( const messageReactions = this.props.room.relations.getChildEventsForEvent(
lastMessage.getId()!, lastMessage.getId()!,
RelationType.Annotation, RelationType.Annotation,
@ -421,7 +421,7 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
shouldReact = !myReactionKeys.includes(reaction); shouldReact = !myReactionKeys.includes(reaction);
} }
if (shouldReact) { if (shouldReact) {
MatrixClientPeg.get().sendEvent(lastMessage.getRoomId()!, EventType.Reaction, { MatrixClientPeg.safeGet().sendEvent(lastMessage.getRoomId()!, EventType.Reaction, {
"m.relates_to": { "m.relates_to": {
rel_type: RelationType.Annotation, rel_type: RelationType.Annotation,
event_id: lastMessage.getId(), event_id: lastMessage.getId(),
@ -476,7 +476,7 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
let commandSuccessful: boolean; let commandSuccessful: boolean;
[content, commandSuccessful] = await runSlashCommand( [content, commandSuccessful] = await runSlashCommand(
MatrixClientPeg.get(), MatrixClientPeg.safeGet(),
cmd, cmd,
args, args,
this.props.room.roomId, this.props.room.roomId,

View file

@ -139,7 +139,7 @@ export default class Stickerpicker extends React.PureComponent<IProps, IState> {
this.dispatcherRef = dis.register(this.onAction); this.dispatcherRef = dis.register(this.onAction);
// Track updates to widget state in account data // Track updates to widget state in account data
MatrixClientPeg.get().on(ClientEvent.AccountData, this.updateWidget); MatrixClientPeg.safeGet().on(ClientEvent.AccountData, this.updateWidget);
RightPanelStore.instance.on(UPDATE_EVENT, this.onRightPanelStoreUpdate); RightPanelStore.instance.on(UPDATE_EVENT, this.onRightPanelStoreUpdate);
// Initialise widget state from current account data // Initialise widget state from current account data
@ -291,8 +291,10 @@ export default class Stickerpicker extends React.PureComponent<IProps, IState> {
room={this.props.room} room={this.props.room}
threadId={this.props.threadId} threadId={this.props.threadId}
fullWidth={true} fullWidth={true}
userId={MatrixClientPeg.get().credentials.userId!} userId={MatrixClientPeg.safeGet().credentials.userId!}
creatorUserId={stickerpickerWidget.sender || MatrixClientPeg.get().credentials.userId!} creatorUserId={
stickerpickerWidget.sender || MatrixClientPeg.safeGet().credentials.userId!
}
waitForIframeLoad={true} waitForIframeLoad={true}
showMenubar={true} showMenubar={true}
onEditClick={this.launchManageIntegrations} onEditClick={this.launchManageIntegrations}

View file

@ -50,8 +50,8 @@ export default class ThirdPartyMemberInfo extends React.Component<IProps, IState
public constructor(props: IProps) { public constructor(props: IProps) {
super(props); super(props);
this.room = MatrixClientPeg.get().getRoom(this.props.event.getRoomId()); this.room = MatrixClientPeg.safeGet().getRoom(this.props.event.getRoomId());
const me = this.room?.getMember(MatrixClientPeg.get().getUserId()!); const me = this.room?.getMember(MatrixClientPeg.safeGet().getSafeUserId());
const powerLevels = this.room?.currentState.getStateEvents("m.room.power_levels", ""); const powerLevels = this.room?.currentState.getStateEvents("m.room.power_levels", "");
const senderId = this.props.event.getSender()!; const senderId = this.props.event.getSender()!;
@ -71,7 +71,7 @@ export default class ThirdPartyMemberInfo extends React.Component<IProps, IState
} }
public componentDidMount(): void { public componentDidMount(): void {
MatrixClientPeg.get().on(RoomStateEvent.Events, this.onRoomStateEvents); MatrixClientPeg.safeGet().on(RoomStateEvent.Events, this.onRoomStateEvents);
} }
public componentWillUnmount(): void { public componentWillUnmount(): void {
@ -100,7 +100,7 @@ export default class ThirdPartyMemberInfo extends React.Component<IProps, IState
}; };
public onKickClick = (): void => { public onKickClick = (): void => {
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.sendStateEvent(this.state.roomId, "m.room.third_party_invite", {}, this.state.stateKey) .sendStateEvent(this.state.roomId, "m.room.third_party_invite", {}, this.state.stateKey)
.catch((err) => { .catch((err) => {
logger.error(err); logger.error(err);

View file

@ -130,7 +130,7 @@ export default class VoiceRecordComposerTile extends React.PureComponent<IProps,
); );
// Attach mentions, which really only applies if there's a replyToEvent. // Attach mentions, which really only applies if there's a replyToEvent.
attachMentions(MatrixClientPeg.get().getSafeUserId(), content, null, replyToEvent); attachMentions(MatrixClientPeg.safeGet().getSafeUserId(), content, null, replyToEvent);
attachRelation(content, relation); attachRelation(content, relation);
if (replyToEvent) { if (replyToEvent) {
addReplyToMessageContent(content, replyToEvent, { addReplyToMessageContent(content, replyToEvent, {
@ -148,7 +148,7 @@ export default class VoiceRecordComposerTile extends React.PureComponent<IProps,
doMaybeLocalRoomAction( doMaybeLocalRoomAction(
this.props.room.roomId, this.props.room.roomId,
(actualRoomId: string) => MatrixClientPeg.get().sendMessage(actualRoomId, content), (actualRoomId: string) => MatrixClientPeg.safeGet().sendMessage(actualRoomId, content),
this.props.room.client, this.props.room.client,
); );
} catch (e) { } catch (e) {

View file

@ -57,8 +57,8 @@ export default class WhoIsTypingTile extends React.Component<IProps, IState> {
}; };
public componentDidMount(): void { public componentDidMount(): void {
MatrixClientPeg.get().on(RoomMemberEvent.Typing, this.onRoomMemberTyping); MatrixClientPeg.safeGet().on(RoomMemberEvent.Typing, this.onRoomMemberTyping);
MatrixClientPeg.get().on(RoomEvent.Timeline, this.onRoomTimeline); MatrixClientPeg.safeGet().on(RoomEvent.Timeline, this.onRoomTimeline);
} }
public componentDidUpdate(prevProps: IProps, prevState: IState): void { public componentDidUpdate(prevProps: IProps, prevState: IState): void {

View file

@ -22,7 +22,7 @@ import EditableTextContainer from "../elements/EditableTextContainer";
export default class ChangeDisplayName extends React.Component { export default class ChangeDisplayName extends React.Component {
private getDisplayName = async (): Promise<string> => { private getDisplayName = async (): Promise<string> => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
try { try {
const res = await cli.getProfileInfo(cli.getUserId()!); const res = await cli.getProfileInfo(cli.getUserId()!);
return res.displayname ?? ""; return res.displayname ?? "";
@ -32,7 +32,7 @@ export default class ChangeDisplayName extends React.Component {
}; };
private changeDisplayName = (newDisplayname: string): Promise<{}> => { private changeDisplayName = (newDisplayname: string): Promise<{}> => {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
return cli.setDisplayName(newDisplayname).catch(function () { return cli.setDisplayName(newDisplayname).catch(function () {
throw new Error("Failed to set display name"); throw new Error("Failed to set display name");
}); });

View file

@ -93,7 +93,7 @@ export default class ChangePassword extends React.Component<IProps, IState> {
} }
private async onChangePassword(oldPassword: string, newPassword: string): Promise<void> { private async onChangePassword(oldPassword: string, newPassword: string): Promise<void> {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
// if the server supports it then don't sign user out of all devices // if the server supports it then don't sign user out of all devices
const serverSupportsControlOfDevicesLogout = await cli.doesServerSupportLogoutDevices(); const serverSupportsControlOfDevicesLogout = await cli.doesServerSupportLogoutDevices();
@ -235,7 +235,7 @@ export default class ChangePassword extends React.Component<IProps, IState> {
typeof ExportE2eKeysDialog typeof ExportE2eKeysDialog
>, >,
{ {
matrixClient: MatrixClientPeg.get(), matrixClient: MatrixClientPeg.safeGet(),
}, },
); );
}; };

View file

@ -38,7 +38,7 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
} }
public render(): React.ReactNode { public render(): React.ReactNode {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const deviceId = client.deviceId; const deviceId = client.deviceId;
let identityKey = client.getDeviceEd25519Key(); let identityKey = client.getDeviceEd25519Key();
if (!identityKey) { if (!identityKey) {
@ -103,7 +103,7 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
import("../../../async-components/views/dialogs/security/ExportE2eKeysDialog") as unknown as Promise< import("../../../async-components/views/dialogs/security/ExportE2eKeysDialog") as unknown as Promise<
typeof ExportE2eKeysDialog typeof ExportE2eKeysDialog
>, >,
{ matrixClient: MatrixClientPeg.get() }, { matrixClient: MatrixClientPeg.safeGet() },
); );
}; };
@ -112,11 +112,11 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
import("../../../async-components/views/dialogs/security/ImportE2eKeysDialog") as unknown as Promise< import("../../../async-components/views/dialogs/security/ImportE2eKeysDialog") as unknown as Promise<
typeof ImportE2eKeysDialog typeof ImportE2eKeysDialog
>, >,
{ matrixClient: MatrixClientPeg.get() }, { matrixClient: MatrixClientPeg.safeGet() },
); );
}; };
private updateBlacklistDevicesFlag = (checked: boolean): void => { private updateBlacklistDevicesFlag = (checked: boolean): void => {
MatrixClientPeg.get().setGlobalBlacklistUnverifiedDevices(checked); MatrixClientPeg.safeGet().setGlobalBlacklistUnverifiedDevices(checked);
}; };
} }

View file

@ -62,8 +62,8 @@ export default class FontScalingPanel extends React.Component<IProps, IState> {
public async componentDidMount(): Promise<void> { public async componentDidMount(): Promise<void> {
// Fetch the current user profile for the message preview // Fetch the current user profile for the message preview
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const userId = client.getUserId()!; const userId = client.getSafeUserId();
const profileInfo = await client.getProfileInfo(userId); const profileInfo = await client.getProfileInfo(userId);
if (this.unmounted) return; if (this.unmounted) return;

View file

@ -270,7 +270,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
} }
private async refreshFromAccountData(): Promise<void> { private async refreshFromAccountData(): Promise<void> {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const settingsEvent = cli.getAccountData(getLocalNotificationAccountDataEventType(cli.deviceId)); const settingsEvent = cli.getAccountData(getLocalNotificationAccountDataEventType(cli.deviceId));
if (settingsEvent) { if (settingsEvent) {
const notificationsEnabled = !(settingsEvent.getContent() as LocalNotificationSettings).is_silenced; const notificationsEnabled = !(settingsEvent.getContent() as LocalNotificationSettings).is_silenced;
@ -279,14 +279,14 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
} }
private persistLocalNotificationSettings(enabled: boolean): Promise<{}> { private persistLocalNotificationSettings(enabled: boolean): Promise<{}> {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
return cli.setAccountData(getLocalNotificationAccountDataEventType(cli.deviceId), { return cli.setAccountData(getLocalNotificationAccountDataEventType(cli.deviceId), {
is_silenced: !enabled, is_silenced: !enabled,
}); });
} }
private async refreshRules(): Promise<Partial<IState>> { private async refreshRules(): Promise<Partial<IState>> {
const ruleSets = await MatrixClientPeg.get().getPushRules()!; const ruleSets = await MatrixClientPeg.safeGet().getPushRules()!;
const categories: Record<string, RuleClass> = { const categories: Record<string, RuleClass> = {
[RuleId.Master]: RuleClass.Master, [RuleId.Master]: RuleClass.Master,
@ -384,11 +384,11 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
} }
private refreshPushers(): Promise<Partial<IState>> { private refreshPushers(): Promise<Partial<IState>> {
return MatrixClientPeg.get().getPushers(); return MatrixClientPeg.safeGet().getPushers();
} }
private refreshThreepids(): Promise<Partial<IState>> { private refreshThreepids(): Promise<Partial<IState>> {
return MatrixClientPeg.get().getThreePids(); return MatrixClientPeg.safeGet().getThreePids();
} }
private showSaveError(): void { private showSaveError(): void {
@ -403,7 +403,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
const masterRule = this.state.masterPushRule!; const masterRule = this.state.masterPushRule!;
try { try {
await MatrixClientPeg.get().setPushRuleEnabled("global", masterRule.kind, masterRule.rule_id, !checked); await MatrixClientPeg.safeGet().setPushRuleEnabled("global", masterRule.kind, masterRule.rule_id, !checked);
await this.refreshFromServer(); await this.refreshFromServer();
} catch (e) { } catch (e) {
this.setState({ phase: Phase.Error }); this.setState({ phase: Phase.Error });
@ -428,7 +428,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
try { try {
if (checked) { if (checked) {
await MatrixClientPeg.get().setPusher({ await MatrixClientPeg.safeGet().setPusher({
kind: "email", kind: "email",
app_id: "m.email", app_id: "m.email",
pushkey: email, pushkey: email,
@ -446,7 +446,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
} else { } else {
const pusher = this.state.pushers?.find((p) => p.kind === "email" && p.pushkey === email); const pusher = this.state.pushers?.find((p) => p.kind === "email" && p.pushkey === email);
if (pusher) { if (pusher) {
await MatrixClientPeg.get().removePusher(pusher.pushkey, pusher.app_id); await MatrixClientPeg.safeGet().removePusher(pusher.pushkey, pusher.app_id);
} }
} }
@ -477,7 +477,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
})); }));
try { try {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
if (rule.ruleId === KEYWORD_RULE_ID) { if (rule.ruleId === KEYWORD_RULE_ID) {
// should not encounter this // should not encounter this
if (!this.state.vectorKeywordRuleInfo) { if (!this.state.vectorKeywordRuleInfo) {
@ -536,7 +536,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
private onClearNotificationsClicked = async (): Promise<void> => { private onClearNotificationsClicked = async (): Promise<void> => {
try { try {
this.setState({ clearingNotifications: true }); this.setState({ clearingNotifications: true });
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
await clearAllNotifications(client); await clearAllNotifications(client);
} finally { } finally {
this.setState({ clearingNotifications: false }); this.setState({ clearingNotifications: false });
@ -560,7 +560,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
for (const word of diff.removed) { for (const word of diff.removed) {
for (const rule of originalRules.filter((r) => r.pattern === word)) { for (const rule of originalRules.filter((r) => r.pattern === word)) {
await MatrixClientPeg.get().deletePushRule("global", rule.kind, rule.rule_id); await MatrixClientPeg.safeGet().deletePushRule("global", rule.kind, rule.rule_id);
} }
} }
@ -577,12 +577,12 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
} }
const kind = PushRuleKind.ContentSpecific; const kind = PushRuleKind.ContentSpecific;
for (const word of diff.added) { for (const word of diff.added) {
await MatrixClientPeg.get().addPushRule("global", kind, word, { await MatrixClientPeg.safeGet().addPushRule("global", kind, word, {
actions: PushRuleVectorState.actionsFor(ruleVectorState), actions: PushRuleVectorState.actionsFor(ruleVectorState),
pattern: word, pattern: word,
}); });
if (ruleVectorState === VectorState.Off) { if (ruleVectorState === VectorState.Off) {
await MatrixClientPeg.get().setPushRuleEnabled("global", kind, word, false); await MatrixClientPeg.safeGet().setPushRuleEnabled("global", kind, word, false);
} }
} }
@ -730,7 +730,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
let clearNotifsButton: JSX.Element | undefined; let clearNotifsButton: JSX.Element | undefined;
if ( if (
category === RuleClass.VectorOther && category === RuleClass.VectorOther &&
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.getRooms() .getRooms()
.some((r) => r.getUnreadNotificationCount() > 0) .some((r) => r.getUnreadNotificationCount() > 0)
) { ) {

View file

@ -47,7 +47,7 @@ export default class ProfileSettings extends React.Component<{}, IState> {
public constructor(props: {}) { public constructor(props: {}) {
super(props); super(props);
this.userId = MatrixClientPeg.get().getSafeUserId(); this.userId = MatrixClientPeg.safeGet().getSafeUserId();
let avatarUrl = OwnProfileStore.instance.avatarMxc; let avatarUrl = OwnProfileStore.instance.avatarMxc;
if (avatarUrl) avatarUrl = mediaFromMxc(avatarUrl).getSquareThumbnailHttp(96); if (avatarUrl) avatarUrl = mediaFromMxc(avatarUrl).getSquareThumbnailHttp(96);
this.state = { this.state = {
@ -96,11 +96,11 @@ export default class ProfileSettings extends React.Component<{}, IState> {
if (!this.state.enableProfileSave) return; if (!this.state.enableProfileSave) return;
this.setState({ enableProfileSave: false }); this.setState({ enableProfileSave: false });
const client = MatrixClientPeg.get();
const newState: Partial<IState> = {}; const newState: Partial<IState> = {};
const displayName = this.state.displayName.trim(); const displayName = this.state.displayName.trim();
try { try {
const client = MatrixClientPeg.safeGet();
if (this.state.originalDisplayName !== this.state.displayName) { if (this.state.originalDisplayName !== this.state.displayName) {
await client.setDisplayName(displayName); await client.setDisplayName(displayName);
newState.originalDisplayName = displayName; newState.originalDisplayName = displayName;

View file

@ -69,16 +69,16 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
public componentDidMount(): void { public componentDidMount(): void {
this.checkKeyBackupStatus(); this.checkKeyBackupStatus();
MatrixClientPeg.get().on(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatus); MatrixClientPeg.safeGet().on(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatus);
MatrixClientPeg.get().on(CryptoEvent.KeyBackupSessionsRemaining, this.onKeyBackupSessionsRemaining); MatrixClientPeg.safeGet().on(CryptoEvent.KeyBackupSessionsRemaining, this.onKeyBackupSessionsRemaining);
} }
public componentWillUnmount(): void { public componentWillUnmount(): void {
this.unmounted = true; this.unmounted = true;
if (MatrixClientPeg.get()) { if (MatrixClientPeg.get()) {
MatrixClientPeg.get().removeListener(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatus); MatrixClientPeg.get()!.removeListener(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatus);
MatrixClientPeg.get().removeListener( MatrixClientPeg.get()!.removeListener(
CryptoEvent.KeyBackupSessionsRemaining, CryptoEvent.KeyBackupSessionsRemaining,
this.onKeyBackupSessionsRemaining, this.onKeyBackupSessionsRemaining,
); );
@ -100,7 +100,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
private async checkKeyBackupStatus(): Promise<void> { private async checkKeyBackupStatus(): Promise<void> {
this.getUpdatedDiagnostics(); this.getUpdatedDiagnostics();
try { try {
const keyBackupResult = await MatrixClientPeg.get().checkKeyBackup(); const keyBackupResult = await MatrixClientPeg.safeGet().checkKeyBackup();
this.setState({ this.setState({
loading: false, loading: false,
error: null, error: null,
@ -123,8 +123,8 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
this.setState({ loading: true }); this.setState({ loading: true });
this.getUpdatedDiagnostics(); this.getUpdatedDiagnostics();
try { try {
const backupInfo = await MatrixClientPeg.get().getKeyBackupVersion(); const backupInfo = await MatrixClientPeg.safeGet().getKeyBackupVersion();
const backupSigStatus = backupInfo ? await MatrixClientPeg.get().isKeyBackupTrusted(backupInfo) : null; const backupSigStatus = backupInfo ? await MatrixClientPeg.safeGet().isKeyBackupTrusted(backupInfo) : null;
if (this.unmounted) return; if (this.unmounted) return;
this.setState({ this.setState({
loading: false, loading: false,
@ -145,7 +145,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
} }
private async getUpdatedDiagnostics(): Promise<void> { private async getUpdatedDiagnostics(): Promise<void> {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const crypto = cli.crypto; const crypto = cli.crypto;
if (!crypto) return; if (!crypto) return;
@ -195,7 +195,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
onFinished: (proceed) => { onFinished: (proceed) => {
if (!proceed) return; if (!proceed) return;
this.setState({ loading: true }); this.setState({ loading: true });
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.deleteKeyBackupVersion(this.state.backupInfo!.version!) .deleteKeyBackupVersion(this.state.backupInfo!.version!)
.then(() => { .then(() => {
this.loadBackupStatus(); this.loadBackupStatus();
@ -246,7 +246,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
} else if (backupInfo) { } else if (backupInfo) {
let restoreButtonCaption = _t("Restore from Backup"); let restoreButtonCaption = _t("Restore from Backup");
if (MatrixClientPeg.get().getKeyBackupEnabled()) { if (MatrixClientPeg.safeGet().getKeyBackupEnabled()) {
statusDescription = <p> {_t("This session is backing up your keys.")}</p>; statusDescription = <p> {_t("This session is backing up your keys.")}</p>;
} else { } else {
statusDescription = ( statusDescription = (
@ -272,7 +272,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
} }
let uploadStatus: ReactNode; let uploadStatus: ReactNode;
if (!MatrixClientPeg.get().getKeyBackupEnabled()) { if (!MatrixClientPeg.safeGet().getKeyBackupEnabled()) {
// No upload status to show when backup disabled. // No upload status to show when backup disabled.
uploadStatus = ""; uploadStatus = "";
} else if (sessionsRemaining > 0) { } else if (sessionsRemaining > 0) {
@ -311,8 +311,9 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
<span className="mx_SecureBackupPanel_deviceName">{deviceName}</span> <span className="mx_SecureBackupPanel_deviceName">{deviceName}</span>
); );
const fromThisDevice = const fromThisDevice =
sig.device && sig.device.getFingerprint() === MatrixClientPeg.get().getDeviceEd25519Key(); sig.device && sig.device.getFingerprint() === MatrixClientPeg.safeGet().getDeviceEd25519Key();
const fromThisUser = sig.crossSigningId && sig.deviceId === MatrixClientPeg.get().getCrossSigningId(); const fromThisUser =
sig.crossSigningId && sig.deviceId === MatrixClientPeg.safeGet().getCrossSigningId();
let sigStatus; let sigStatus;
if (sig.valid && fromThisUser) { if (sig.valid && fromThisUser) {
sigStatus = _t( sigStatus = _t(
@ -419,7 +420,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
</AccessibleButton>, </AccessibleButton>,
); );
if (!isSecureBackupRequired(MatrixClientPeg.get())) { if (!isSecureBackupRequired(MatrixClientPeg.safeGet())) {
actions.push( actions.push(
<AccessibleButton key="delete" kind="danger" onClick={this.deleteBackup}> <AccessibleButton key="delete" kind="danger" onClick={this.deleteBackup}>
{_t("Delete Backup")} {_t("Delete Backup")}

View file

@ -88,7 +88,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
super(props); super(props);
let defaultIdServer = ""; let defaultIdServer = "";
if (!MatrixClientPeg.get().getIdentityServerUrl() && getDefaultIdentityServerUrl()) { if (!MatrixClientPeg.safeGet().getIdentityServerUrl() && getDefaultIdentityServerUrl()) {
// If no identity server is configured but there's one in the config, prepopulate // If no identity server is configured but there's one in the config, prepopulate
// the field to help the user. // the field to help the user.
defaultIdServer = abbreviateUrl(getDefaultIdentityServerUrl()); defaultIdServer = abbreviateUrl(getDefaultIdentityServerUrl());
@ -96,7 +96,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
this.state = { this.state = {
defaultIdServer, defaultIdServer,
currentClientIdServer: MatrixClientPeg.get().getIdentityServerUrl(), currentClientIdServer: MatrixClientPeg.safeGet().getIdentityServerUrl(),
idServer: "", idServer: "",
busy: false, busy: false,
disconnectBusy: false, disconnectBusy: false,
@ -118,7 +118,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
if (payload.action !== "id_server_changed") return; if (payload.action !== "id_server_changed") return;
this.setState({ this.setState({
currentClientIdServer: MatrixClientPeg.get().getIdentityServerUrl(), currentClientIdServer: MatrixClientPeg.safeGet().getIdentityServerUrl(),
}); });
}; };
@ -149,7 +149,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
private saveIdServer = (fullUrl: string): void => { private saveIdServer = (fullUrl: string): void => {
// Account data change will update localstorage, client, etc through dispatcher // Account data change will update localstorage, client, etc through dispatcher
MatrixClientPeg.get().setAccountData("m.identity_server", { MatrixClientPeg.safeGet().setAccountData("m.identity_server", {
base_url: fullUrl, base_url: fullUrl,
}); });
this.setState({ this.setState({
@ -181,7 +181,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
let save = true; let save = true;
// Double check that the identity server even has terms of service. // Double check that the identity server even has terms of service.
const hasTerms = await doesIdentityServerHaveTerms(MatrixClientPeg.get(), fullUrl); const hasTerms = await doesIdentityServerHaveTerms(MatrixClientPeg.safeGet(), fullUrl);
if (!hasTerms) { if (!hasTerms) {
const [confirmed] = await this.showNoTermsWarning(fullUrl); const [confirmed] = await this.showNoTermsWarning(fullUrl);
save = !!confirmed; save = !!confirmed;
@ -217,7 +217,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
busy: false, busy: false,
checking: false, checking: false,
error: errStr ?? undefined, error: errStr ?? undefined,
currentClientIdServer: MatrixClientPeg.get().getIdentityServerUrl(), currentClientIdServer: MatrixClientPeg.safeGet().getIdentityServerUrl(),
}); });
}; };
@ -272,7 +272,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
let currentServerReachable = true; let currentServerReachable = true;
try { try {
threepids = await timeout( threepids = await timeout(
getThreepidsWithBindStatus(MatrixClientPeg.get()), getThreepidsWithBindStatus(MatrixClientPeg.safeGet()),
Promise.reject(new Error("Timeout attempting to reach identity server")), Promise.reject(new Error("Timeout attempting to reach identity server")),
REACHABILITY_TIMEOUT, REACHABILITY_TIMEOUT,
); );
@ -362,7 +362,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
private disconnectIdServer = (): void => { private disconnectIdServer = (): void => {
// Account data change will update localstorage, client, etc through dispatcher // Account data change will update localstorage, client, etc through dispatcher
MatrixClientPeg.get().setAccountData("m.identity_server", { MatrixClientPeg.safeGet().setAccountData("m.identity_server", {
base_url: null, // clear base_url: null, // clear
}); });
@ -376,7 +376,7 @@ export default class SetIdServer extends React.Component<IProps, IState> {
this.setState({ this.setState({
busy: false, busy: false,
error: undefined, error: undefined,
currentClientIdServer: MatrixClientPeg.get().getIdentityServerUrl(), currentClientIdServer: MatrixClientPeg.safeGet().getIdentityServerUrl(),
idServer: newFieldVal, idServer: newFieldVal,
}); });
}; };

View file

@ -77,7 +77,7 @@ export class ExistingEmailAddress extends React.Component<IExistingEmailAddressP
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.deleteThreePid(this.props.email.medium, this.props.email.address) .deleteThreePid(this.props.email.medium, this.props.email.address)
.then(() => { .then(() => {
return this.props.onRemoved(this.props.email); return this.props.onRemoved(this.props.email);
@ -181,7 +181,7 @@ export default class EmailAddresses extends React.Component<IProps, IState> {
return; return;
} }
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ verifying: true, continueDisabled: true, addTask: task }); this.setState({ verifying: true, continueDisabled: true, addTask: task });
task.addEmailAddress(email) task.addEmailAddress(email)

View file

@ -72,7 +72,7 @@ export class ExistingPhoneNumber extends React.Component<IExistingPhoneNumberPro
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
MatrixClientPeg.get() MatrixClientPeg.safeGet()
.deleteThreePid(this.props.msisdn.medium, this.props.msisdn.address) .deleteThreePid(this.props.msisdn.medium, this.props.msisdn.address)
.then(() => { .then(() => {
return this.props.onRemoved(this.props.msisdn); return this.props.onRemoved(this.props.msisdn);
@ -182,7 +182,7 @@ export default class PhoneNumbers extends React.Component<IProps, IState> {
const phoneNumber = this.state.newPhoneNumber; const phoneNumber = this.state.newPhoneNumber;
const phoneCountry = this.state.phoneCountry; const phoneCountry = this.state.phoneCountry;
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ verifying: true, continueDisabled: true, addTask: task }); this.setState({ verifying: true, continueDisabled: true, addTask: task });
task.addMsisdn(phoneCountry, phoneNumber) task.addMsisdn(phoneCountry, phoneNumber)

View file

@ -78,7 +78,7 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
} }
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> { private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
if (!(await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind())) { if (!(await MatrixClientPeg.safeGet().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle }); return this.changeBindingTangledAddBind({ bind, label, errorTitle });
} }
@ -86,7 +86,7 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
try { try {
if (bind) { if (bind) {
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ this.setState({
verifying: true, verifying: true,
continueDisabled: true, continueDisabled: true,
@ -97,7 +97,7 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
continueDisabled: false, continueDisabled: false,
}); });
} else { } else {
await MatrixClientPeg.get().unbindThreePid(medium, address); await MatrixClientPeg.safeGet().unbindThreePid(medium, address);
} }
this.setState({ bound: bind }); this.setState({ bound: bind });
} catch (err) { } catch (err) {
@ -117,7 +117,7 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> { private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> {
const { medium, address } = this.props.email; const { medium, address } = this.props.email;
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ this.setState({
verifying: true, verifying: true,
continueDisabled: true, continueDisabled: true,
@ -125,7 +125,7 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
}); });
try { try {
await MatrixClientPeg.get().deleteThreePid(medium, address); await MatrixClientPeg.safeGet().deleteThreePid(medium, address);
if (bind) { if (bind) {
await task.bindEmailAddress(address); await task.bindEmailAddress(address);
} else { } else {

View file

@ -74,7 +74,7 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
} }
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> { private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
if (!(await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind())) { if (!(await MatrixClientPeg.safeGet().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle }); return this.changeBindingTangledAddBind({ bind, label, errorTitle });
} }
@ -82,7 +82,7 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
try { try {
if (bind) { if (bind) {
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ this.setState({
verifying: true, verifying: true,
continueDisabled: true, continueDisabled: true,
@ -98,7 +98,7 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
continueDisabled: false, continueDisabled: false,
}); });
} else { } else {
await MatrixClientPeg.get().unbindThreePid(medium, address); await MatrixClientPeg.safeGet().unbindThreePid(medium, address);
} }
this.setState({ bound: bind }); this.setState({ bound: bind });
} catch (err) { } catch (err) {
@ -118,7 +118,7 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> { private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> {
const { medium, address } = this.props.msisdn; const { medium, address } = this.props.msisdn;
const task = new AddThreepid(MatrixClientPeg.get()); const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({ this.setState({
verifying: true, verifying: true,
continueDisabled: true, continueDisabled: true,
@ -126,7 +126,7 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
}); });
try { try {
await MatrixClientPeg.get().deleteThreePid(medium, address); await MatrixClientPeg.safeGet().deleteThreePid(medium, address);
// XXX: Sydent will accept a number without country code if you add // XXX: Sydent will accept a number without country code if you add
// a leading plus sign to a number in E.164 format (which the 3PID // a leading plus sign to a number in E.164 format (which the 3PID
// address is), but this goes against the spec. // address is), but this goes against the spec.

View file

@ -55,7 +55,8 @@ const SpacePublicShare: React.FC<IProps> = ({ space, onFinished }) => {
{_t("Share invite link")} {_t("Share invite link")}
<div>{copiedText}</div> <div>{copiedText}</div>
</AccessibleButton> </AccessibleButton>
{space.canInvite(MatrixClientPeg.get()?.getSafeUserId()) && shouldShowComponent(UIComponent.InviteUsers) ? ( {space.canInvite(MatrixClientPeg.safeGet().getSafeUserId()) &&
shouldShowComponent(UIComponent.InviteUsers) ? (
<AccessibleButton <AccessibleButton
className="mx_SpacePublicShare_inviteButton" className="mx_SpacePublicShare_inviteButton"
onClick={() => { onClick={() => {

View file

@ -432,7 +432,7 @@ export default class LegacyCallView extends React.Component<IProps, IState> {
const { isLocalOnHold, isRemoteOnHold, sidebarShown, primaryFeed, secondaryFeed, sidebarFeeds } = this.state; const { isLocalOnHold, isRemoteOnHold, sidebarShown, primaryFeed, secondaryFeed, sidebarFeeds } = this.state;
const callRoomId = LegacyCallHandler.instance.roomIdForCall(call); const callRoomId = LegacyCallHandler.instance.roomIdForCall(call);
const callRoom = (callRoomId ? MatrixClientPeg.get().getRoom(callRoomId) : undefined) ?? undefined; const callRoom = (callRoomId ? MatrixClientPeg.safeGet().getRoom(callRoomId) : undefined) ?? undefined;
const avatarSize = pipMode ? 76 : 160; const avatarSize = pipMode ? 76 : 160;
const transfereeCall = LegacyCallHandler.instance.getTransfereeForCallId(call.callId); const transfereeCall = LegacyCallHandler.instance.getTransfereeForCallId(call.callId);
const isOnHold = isLocalOnHold || isRemoteOnHold; const isOnHold = isLocalOnHold || isRemoteOnHold;
@ -452,7 +452,7 @@ export default class LegacyCallView extends React.Component<IProps, IState> {
let holdTransferContent: React.ReactNode; let holdTransferContent: React.ReactNode;
if (transfereeCall) { if (transfereeCall) {
const cli = MatrixClientPeg.get(); const cli = MatrixClientPeg.safeGet();
const callRoomId = LegacyCallHandler.instance.roomIdForCall(call); const callRoomId = LegacyCallHandler.instance.roomIdForCall(call);
const transferTargetRoom = callRoomId ? cli.getRoom(callRoomId) : null; const transferTargetRoom = callRoomId ? cli.getRoom(callRoomId) : null;
const transferTargetName = transferTargetRoom ? transferTargetRoom.name : _t("unknown person"); const transferTargetName = transferTargetRoom ? transferTargetRoom.name : _t("unknown person");
@ -575,7 +575,7 @@ export default class LegacyCallView extends React.Component<IProps, IState> {
const { call, secondaryCall, pipMode, showApps, onMouseDownOnHeader } = this.props; const { call, secondaryCall, pipMode, showApps, onMouseDownOnHeader } = this.props;
const { sidebarShown, sidebarFeeds } = this.state; const { sidebarShown, sidebarFeeds } = this.state;
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.safeGet();
const callRoomId = LegacyCallHandler.instance.roomIdForCall(call); const callRoomId = LegacyCallHandler.instance.roomIdForCall(call);
const secondaryCallRoomId = LegacyCallHandler.instance.roomIdForCall(secondaryCall); const secondaryCallRoomId = LegacyCallHandler.instance.roomIdForCall(secondaryCall);
const callRoom = callRoomId ? client.getRoom(callRoomId) : null; const callRoom = callRoomId ? client.getRoom(callRoomId) : null;

View file

@ -200,7 +200,7 @@ export default class VideoFeed extends React.PureComponent<IProps, IState> {
let content; let content;
if (this.state.videoMuted) { if (this.state.videoMuted) {
const callRoomId = LegacyCallHandler.instance.roomIdForCall(this.props.call); const callRoomId = LegacyCallHandler.instance.roomIdForCall(this.props.call);
const callRoom = (callRoomId ? MatrixClientPeg.get().getRoom(callRoomId) : undefined) ?? undefined; const callRoom = (callRoomId ? MatrixClientPeg.safeGet().getRoom(callRoomId) : undefined) ?? undefined;
let avatarSize; let avatarSize;
if (pipMode && primary) avatarSize = 76; if (pipMode && primary) avatarSize = 76;

View file

@ -49,6 +49,7 @@ describe("EncryptionEvent", () => {
jest.clearAllMocks(); jest.clearAllMocks();
client = createTestClient(); client = createTestClient();
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client); jest.spyOn(MatrixClientPeg, "get").mockReturnValue(client);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(client);
event = mkMessage({ event = mkMessage({
event: true, event: true,
room: roomId, room: roomId,

View file

@ -166,6 +166,7 @@ beforeEach(() => {
} as unknown as MatrixClient); } as unknown as MatrixClient);
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient); jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mockClient);
}); });
describe("<UserInfo />", () => { describe("<UserInfo />", () => {

View file

@ -18,7 +18,7 @@ import React, { ComponentProps } from "react";
import { render, fireEvent, RenderResult, waitFor } from "@testing-library/react"; import { render, fireEvent, RenderResult, waitFor } from "@testing-library/react";
import { Room, RoomMember, MatrixError, IContent } from "matrix-js-sdk/src/matrix"; import { Room, RoomMember, MatrixError, IContent } from "matrix-js-sdk/src/matrix";
import { stubClient } from "../../../test-utils"; import { withClientContextRenderOptions, stubClient } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg"; import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import DMRoomMap from "../../../../src/utils/DMRoomMap"; import DMRoomMap from "../../../../src/utils/DMRoomMap";
import RoomPreviewBar from "../../../../src/components/views/rooms/RoomPreviewBar"; import RoomPreviewBar from "../../../../src/components/views/rooms/RoomPreviewBar";
@ -77,7 +77,10 @@ describe("<RoomPreviewBar />", () => {
roomId, roomId,
room: createRoom(roomId, userId), room: createRoom(roomId, userId),
}; };
return render(<RoomPreviewBar {...defaultProps} {...props} />); return render(
<RoomPreviewBar {...defaultProps} {...props} />,
withClientContextRenderOptions(MatrixClientPeg.safeGet()),
);
}; };
const isSpinnerRendered = (wrapper: RenderResult) => !!wrapper.container.querySelector(".mx_Spinner"); const isSpinnerRendered = (wrapper: RenderResult) => !!wrapper.container.querySelector(".mx_Spinner");
@ -92,7 +95,10 @@ describe("<RoomPreviewBar />", () => {
beforeEach(() => { beforeEach(() => {
stubClient(); stubClient();
MatrixClientPeg.get().getUserId = jest.fn().mockReturnValue(userId);
MatrixClientPeg.get().getSafeUserId = jest.fn().mockReturnValue(userId);
MatrixClientPeg.safeGet().getUserId = jest.fn().mockReturnValue(userId); MatrixClientPeg.safeGet().getUserId = jest.fn().mockReturnValue(userId);
MatrixClientPeg.safeGet().getSafeUserId = jest.fn().mockReturnValue(userId);
}); });
afterEach(() => { afterEach(() => {

View file

@ -127,6 +127,7 @@ describe("<SpacePanel />", () => {
beforeAll(() => { beforeAll(() => {
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient); jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mockClient);
}); });
beforeEach(() => { beforeEach(() => {