import { MatrixClient } from 'matrix-js-sdk'; import { mxcUrlToHttp } from './matrix'; import { getCurrentAccessToken } from './auth'; /** * Blob URLs for profile assets (banner, nameplate, avatar decoration). * * Kept in one cache so reopening the same profile does not re-download the * same media on every mount. Entries are revoked only when evicted. */ const MAX_ASSET_CACHE_ENTRIES = 200; const assetCache = new Map(); const inflightAssets = new Map>(); function evictOldest(): void { const firstKey = assetCache.keys().next().value; if (firstKey === undefined) return; const url = assetCache.get(firstKey); assetCache.delete(firstKey); if (url) URL.revokeObjectURL(url); } export async function getProfileAssetUrl( mx: MatrixClient, mxcUrl: string, useAuthentication: boolean ): Promise { if (!mxcUrl) return undefined; const cached = assetCache.get(mxcUrl); if (cached) return cached; const pending = inflightAssets.get(mxcUrl); if (pending) return pending; const request = (async () => { const httpUrl = mxcUrlToHttp(mx, mxcUrl, useAuthentication); if (!httpUrl) return undefined; const headers: HeadersInit = {}; if (useAuthentication) { const accessToken = getCurrentAccessToken(); if (accessToken) headers.Authorization = `Bearer ${accessToken}`; } try { const response = await fetch(httpUrl, { headers }); if (!response.ok) return undefined; const blob = await response.blob(); const blobUrl = URL.createObjectURL(blob); if (assetCache.size >= MAX_ASSET_CACHE_ENTRIES) evictOldest(); assetCache.set(mxcUrl, blobUrl); return blobUrl; } catch { return undefined; } })(); inflightAssets.set(mxcUrl, request); try { return await request; } finally { if (inflightAssets.get(mxcUrl) === request) inflightAssets.delete(mxcUrl); } } export function clearProfileAssetCache(): void { assetCache.forEach((url) => URL.revokeObjectURL(url)); assetCache.clear(); inflightAssets.clear(); }