Files
ThreadNet-Web/apps/web/src/stores/OwnProfileStore.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

219 lines
8.0 KiB
TypeScript
Raw Normal View History

2020-06-23 20:59:26 -06:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
2020-06-23 20:59:26 -06:00
Copyright 2020 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2020-06-23 20:59:26 -06:00
*/
2025-02-05 13:25:06 +00:00
import {
type MatrixEvent,
RoomStateEvent,
MatrixError,
type User,
UserEvent,
EventType,
ClientEvent,
2025-02-05 13:25:06 +00:00
} from "matrix-js-sdk/src/matrix";
2021-08-23 19:26:57 +02:00
import { throttle } from "lodash";
2026-06-16 10:01:34 +01:00
import { type UserStatus } from "@element-hq/web-shared-components";
2021-10-22 17:23:32 -05:00
2025-02-05 13:25:06 +00:00
import { type ActionPayload } from "../dispatcher/payloads";
2021-10-22 17:23:32 -05:00
import { AsyncStoreWithClient } from "./AsyncStoreWithClient";
import defaultDispatcher from "../dispatcher/dispatcher";
2020-06-23 20:59:26 -06:00
import { MatrixClientPeg } from "../MatrixClientPeg";
import { _t } from "../languageHandler";
2021-06-29 13:11:58 +01:00
import { mediaFromMxc } from "../customisations/Media";
import SettingsStore from "../settings/SettingsStore";
2026-06-16 10:01:34 +01:00
import { validateUserStatus } from "../utils/userStatus";
2020-06-23 20:59:26 -06:00
interface IState {
displayName?: string;
avatarUrl?: string;
fetchedAt?: number;
userStatus?: UserStatus;
2020-06-23 20:59:26 -06:00
}
const KEY_DISPLAY_NAME = "mx_profile_displayname";
const KEY_AVATAR_URL = "mx_profile_avatar_url";
2020-06-23 20:59:26 -06:00
export class OwnProfileStore extends AsyncStoreWithClient<IState> {
private static readonly internalInstance = (() => {
const instance = new OwnProfileStore();
2024-10-10 15:08:43 +01:00
instance.start();
return instance;
})();
2020-06-23 20:59:26 -06:00
private monitoredUser: User | null = null;
2020-06-23 20:59:26 -06:00
2023-07-26 11:54:45 +02:00
public constructor() {
// seed from localstorage because otherwise we won't get these values until a whole network
// round-trip after the client is ready, and we often load widgets in that time, and we'd
// and up passing them an incorrect display name
super(defaultDispatcher, {
displayName: window.localStorage.getItem(KEY_DISPLAY_NAME) || undefined,
avatarUrl: window.localStorage.getItem(KEY_AVATAR_URL) || undefined,
});
2020-06-23 20:59:26 -06:00
}
public static get instance(): OwnProfileStore {
return OwnProfileStore.internalInstance;
}
/**
* Gets the display name for the user, or null if not present.
*/
public get displayName(): string | null {
2020-06-23 20:59:26 -06:00
if (!this.matrixClient) return this.state.displayName || null;
if (this.matrixClient.isGuest()) {
return _t("common|guest");
2020-06-23 20:59:26 -06:00
} else if (this.state.displayName) {
return this.state.displayName;
} else {
return this.matrixClient.getUserId();
}
}
public get isProfileInfoFetched(): boolean {
return !!this.state.fetchedAt;
}
2020-06-23 20:59:26 -06:00
/**
* Gets the MXC URI of the user's avatar, or null if not present.
*/
public get avatarMxc(): string | null {
2020-06-23 20:59:26 -06:00
return this.state.avatarUrl || null;
}
public get userStatus(): UserStatus | undefined {
return this.state.userStatus;
}
2020-06-23 20:59:26 -06:00
/**
* Gets the user's avatar as an HTTP URL of the given size. If the user's
* avatar is not present, this returns null.
* @param size The size of the avatar. If zero, a full res copy of the avatar
* will be returned as an HTTP URL.
2020-06-23 20:59:26 -06:00
* @returns The HTTP URL of the user's avatar
*/
public getHttpAvatarUrl(size = 0): string | null {
2020-06-23 20:59:26 -06:00
if (!this.avatarMxc) return null;
const media = mediaFromMxc(this.avatarMxc);
if (!size || size <= 0) {
return media.srcHttp;
} else {
return media.getSquareThumbnailHttp(size);
}
2020-06-23 20:59:26 -06:00
}
protected async onNotReady(): Promise<void> {
this.onProfileUpdate.cancel();
2020-06-23 20:59:26 -06:00
if (this.monitoredUser) {
this.monitoredUser.removeListener(UserEvent.DisplayName, this.onProfileUpdate);
this.monitoredUser.removeListener(UserEvent.AvatarUrl, this.onProfileUpdate);
2020-06-23 20:59:26 -06:00
}
this.matrixClient?.removeListener(RoomStateEvent.Events, this.onStateEvents);
if (SettingsStore.getValue("feature_user_status")) {
this.matrixClient?.removeListener(ClientEvent.UserProfileUpdate, this.onExtendedProfileUpdate);
}
2020-06-23 20:59:26 -06:00
await this.reset({});
}
protected async onReady(): Promise<void> {
if (!this.matrixClient) return;
const myUserId = this.matrixClient.getSafeUserId();
2020-06-23 20:59:26 -06:00
this.monitoredUser = this.matrixClient.getUser(myUserId);
if (this.monitoredUser) {
this.monitoredUser.on(UserEvent.DisplayName, this.onProfileUpdate);
this.monitoredUser.on(UserEvent.AvatarUrl, this.onProfileUpdate);
2020-06-23 20:59:26 -06:00
}
if (SettingsStore.getValue("feature_user_status")) {
this.matrixClient.on(ClientEvent.UserProfileUpdate, this.onExtendedProfileUpdate);
}
2020-06-23 20:59:26 -06:00
// We also have to listen for membership events for ourselves as the above User events
// are fired only with presence, which matrix.org (and many others) has disabled.
this.matrixClient.on(RoomStateEvent.Events, this.onStateEvents);
2020-06-23 20:59:26 -06:00
await this.onProfileUpdate(); // trigger an initial update
await this.refreshUserStatus(); // trigger an update for the user status
2020-06-23 20:59:26 -06:00
}
protected async onAction(payload: ActionPayload): Promise<void> {
2020-06-23 20:59:26 -06:00
// we don't actually do anything here
}
private onProfileUpdate = throttle(
async (): Promise<void> => {
if (!this.matrixClient) return;
2020-06-23 20:59:26 -06:00
// We specifically do not use the User object we stored for profile info as it
// could easily be wrong (such as per-room instead of global profile).
2023-07-26 11:54:45 +02:00
let profileInfo: { displayname?: string; avatar_url?: string } = {
displayname: undefined,
avatar_url: undefined,
};
try {
profileInfo = await this.matrixClient.getProfileInfo(this.matrixClient.getSafeUserId());
} catch (error: unknown) {
if (!(error instanceof MatrixError) || error.errcode !== "M_NOT_FOUND") {
/**
* Raise any other error than M_NOT_FOUND.
* M_NOT_FOUND could occur if there is no user profile.
* {@link https://spec.matrix.org/v1.7/client-server-api/#get_matrixclientv3profileuserid}
* We should then assume an empty profile, emit UPDATE_EVENT etc..
*/
throw error;
}
}
2021-03-19 11:29:14 +00:00
if (profileInfo.displayname) {
window.localStorage.setItem(KEY_DISPLAY_NAME, profileInfo.displayname);
} else {
window.localStorage.removeItem(KEY_DISPLAY_NAME);
}
2023-07-26 11:54:45 +02:00
2021-03-19 11:29:14 +00:00
if (profileInfo.avatar_url) {
window.localStorage.setItem(KEY_AVATAR_URL, profileInfo.avatar_url);
} else {
window.localStorage.removeItem(KEY_AVATAR_URL);
}
await this.updateState({
displayName: profileInfo.displayname,
avatarUrl: profileInfo.avatar_url,
fetchedAt: Date.now(),
});
},
200,
{ trailing: true, leading: true },
);
2020-06-23 20:59:26 -06:00
private onExtendedProfileUpdate = async (syncedUserId: string): Promise<void> => {
if (syncedUserId === this.matrixClient?.getSafeUserId()) {
await this.refreshUserStatus();
}
};
private refreshUserStatus = async (): Promise<void> => {
if (!this.matrixClient) return;
if (!SettingsStore.getValue("feature_user_status")) return;
const rawUserStatus = await this.matrixClient.getExtendedProfileProperty(
this.matrixClient.getSafeUserId(),
"org.matrix.msc4426.status",
);
await this.updateState({ userStatus: validateUserStatus(rawUserStatus) });
};
private onStateEvents = async (ev: MatrixEvent): Promise<void> => {
const myUserId = MatrixClientPeg.safeGet().getUserId();
if (ev.getType() === EventType.RoomMember && ev.getSender() === myUserId && ev.getStateKey() === myUserId) {
2020-06-23 20:59:26 -06:00
await this.onProfileUpdate();
}
};
2020-06-23 20:59:26 -06:00
}