import { accounts } from "#lib/stores/accounts.svelte.js"; import { auth } from "#lib/stores/auth.svelte.js"; import { PUBLIC_API_BASE_URL } from "$app/env/public"; const BASE = PUBLIC_API_BASE_URL; const MAX_CACHED = 100; const ready = new Map(); const missing = new Set(); const inflight = new Map>(); function remember(key: string, url: string) { ready.set(key, url); while (ready.size > MAX_CACHED) { const oldest = ready.keys().next(); if (oldest.done) { return; } const stale = ready.get(oldest.value); ready.delete(oldest.value); if (stale) { URL.revokeObjectURL(stale); } } } function authHeaders(): Record { return auth.token ? { Authorization: `Bearer ${auth.token}` } : {}; } async function fetchStoryMedia( account: number, peerId: number, storyId: number, key: string ): Promise { const url = `${BASE}/stories/${peerId}/${storyId}/media?account_id=${account}`; const response = await fetch(url, { headers: authHeaders() }); if (response.ok) { const objectUrl = URL.createObjectURL(await response.blob()); remember(key, objectUrl); return objectUrl; } missing.add(key); return null; } export function loadStoryMedia( peerId: number, storyId: number ): Promise { const account = accounts.selectedId; if (account === null) { return Promise.resolve(null); } const key = `${account}:${peerId}:${storyId}`; const cached = ready.get(key); if (cached) { return Promise.resolve(cached); } if (missing.has(key)) { return Promise.resolve(null); } const existing = inflight.get(key); if (existing) { return existing; } const promise = fetchStoryMedia(account, peerId, storyId, key).finally(() => { inflight.delete(key); }); inflight.set(key, promise); return promise; }