Files
Sable/src/app/hooks/useSessionProfiles.ts
T
Erwan Leboucher ec91c3579a Merge remote-tracking branch 'origin/dev' into feat/tauri-desktop
# Conflicts:
#	.gitignore
#	.prettierignore
#	.vscode/settings.json
#	eslint.config.js
#	flake.lock
#	flake.nix
#	knip.json
#	package.json
#	pnpm-lock.yaml
#	src/app/components/AuthFlowsLoader.tsx
#	src/app/components/ClientConfigLoader.tsx
#	src/app/components/SpecVersionsLoader.tsx
#	src/app/components/SwipeableChatWrapper.tsx
#	src/app/components/SwipeableOverlayWrapper.tsx
#	src/app/components/emoji-board/components/Item.tsx
#	src/app/components/message/content/ImageContent.tsx
#	src/app/components/message/content/ThumbnailContent.tsx
#	src/app/components/power/PowerIcon.tsx
#	src/app/components/url-preview/ClientPreview.tsx
#	src/app/features/room/RoomInput.tsx
#	src/app/features/room/message/Message.tsx
#	src/app/features/settings/Settings.tsx
#	src/app/features/settings/emojis-stickers/GlobalPacks.tsx
#	src/app/features/settings/notifications/PushNotifications.tsx
#	src/app/features/settings/notifications/SystemNotification.tsx
#	src/app/hooks/useClientConfig.ts
#	src/app/hooks/useIntegrationManager.ts
#	src/app/hooks/useSessionProfiles.ts
#	src/app/pages/App.tsx
#	src/app/pages/Router.tsx
#	src/app/pages/auth/SSOLogin.tsx
#	src/app/pages/auth/login/Login.tsx
#	src/app/pages/auth/register/PasswordRegisterForm.tsx
#	src/app/pages/auth/register/Register.tsx
#	src/app/pages/auth/reset-password/PasswordResetForm.tsx
#	src/app/pages/client/AutoDiscovery.tsx
#	src/app/pages/client/BackgroundNotifications.tsx
#	src/app/pages/client/ClientNonUIFeatures.tsx
#	src/app/pages/client/ClientRoot.tsx
#	src/app/pages/client/SyncStatus.tsx
#	src/app/plugins/react-custom-html-parser.tsx
#	src/app/state/serviceWorkerRegistration.ts
#	src/app/state/settings.ts
#	src/app/utils/matrix.ts
#	src/app/utils/notifications.ts
#	src/app/utils/settingsSync.test.ts
#	src/client/initMatrix.ts
#	src/index.tsx
#	src/sw.ts
#	src/sw/pushNotification.ts
#	tsconfig.json
#	vite.config.ts
2026-07-17 12:12:26 +02:00

110 lines
3.2 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import type { Session } from '$state/sessions';
import { fetch } from '$utils/fetch';
import { fetchMediaBlob } from '$utils/mediaTransport';
export type SessionProfile = {
displayName?: string;
avatarHttpUrl?: string;
};
type SessionProfiles = Record<string, SessionProfile>;
const parseMxc = (mxcUrl: string): { serverName: string; mediaId: string } | undefined => {
const match = mxcUrl.match(/^mxc:\/\/([^/]+)\/(.+)$/);
if (!match) return undefined;
const serverName = match[1];
const mediaId = match[2];
if (!serverName || !mediaId) return undefined;
return { serverName, mediaId };
};
const fetchAvatarBlobUrl = async (
session: Session,
mxcUrl: string
): Promise<string | undefined> => {
const parsed = parseMxc(mxcUrl);
if (!parsed) return undefined;
const { serverName, mediaId } = parsed;
const tryFetch = async (url: string) => {
const blob = await fetchMediaBlob(url, {
accessToken: session.accessToken,
sessionScope: session.userId,
});
return URL.createObjectURL(blob);
};
try {
return await tryFetch(
`${session.baseUrl}/_matrix/client/v1/media/thumbnail/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`
);
} catch {
try {
return await tryFetch(
`${session.baseUrl}/_matrix/media/v3/thumbnail/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`
);
} catch {
return undefined;
}
}
};
export const useSessionProfiles = (sessions: Session[]): SessionProfiles => {
const [profiles, setProfiles] = useState<SessionProfiles>({});
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
const sessionIdentityKey = sessions
.map((session) =>
[session.userId, session.baseUrl, session.accessToken, session.deviceId].join('\x01')
)
.join('\x00');
useEffect(() => {
let cancelled = false;
const newBlobUrls: string[] = [];
sessionsRef.current.forEach(async (session) => {
try {
const profileUrl = `${session.baseUrl}/_matrix/client/v3/profile/${encodeURIComponent(session.userId)}`;
const res = await fetch(profileUrl, {
headers: { Authorization: `Bearer ${session.accessToken}` },
});
if (!res.ok || cancelled) return;
const data = (await res.json()) as { displayname?: string; avatar_url?: string };
if (cancelled) return;
let avatarHttpUrl: string | undefined;
if (data.avatar_url) {
avatarHttpUrl = await fetchAvatarBlobUrl(session, data.avatar_url);
if (avatarHttpUrl) newBlobUrls.push(avatarHttpUrl);
}
if (cancelled) {
if (avatarHttpUrl) URL.revokeObjectURL(avatarHttpUrl);
return;
}
setProfiles((prev) => ({
...prev,
[session.userId]: {
displayName: data.displayname ?? undefined,
avatarHttpUrl,
},
}));
} catch {
// ignore
}
});
return () => {
cancelled = true;
newBlobUrls.forEach((url) => URL.revokeObjectURL(url));
};
}, [sessionIdentityKey]);
return profiles;
};