diff --git a/index.html b/index.html index 90010a8..728a413 100644 --- a/index.html +++ b/index.html @@ -7,54 +7,62 @@ Blink -
- -
+
+
+
Blink
+ +
+
+ + + + +
+
+ +
+ {[0, 1, 2, 3].map((index) => ( + + ))} +
+
+
+
+ + ); + } + return (
diff --git a/src/routes/_api/player/index.tsx b/src/routes/_api/player/index.tsx index 1edab4e..2584ef2 100644 --- a/src/routes/_api/player/index.tsx +++ b/src/routes/_api/player/index.tsx @@ -10,7 +10,7 @@ import "./videoPlayer.scss"; import { RepeatMode } from "@jellyfin/sdk/lib/generated-client"; import { useMutation } from "@tanstack/react-query"; -import { createFileRoute, useRouter } from "@tanstack/react-router"; +import { createFileRoute, useNavigate, useRouter } from "@tanstack/react-router"; import JASSUB from "jassub"; import wasmUrl from "jassub/dist/wasm/jassub-worker.wasm?url"; // non-SIMD fallback import modernWasmUrl from "jassub/dist/wasm/jassub-worker-modern.wasm?url"; // SIMD @@ -82,6 +82,7 @@ function addSubtitleTrackToReactPlayer( export function VideoPlayer() { const api = useApiInContext((s) => s.api); + const navigate = useNavigate(); const { history } = useRouter(); const player = useRef(null); /** Re-apply the transfer/resume position until the HLS player stabilises. */ @@ -599,6 +600,17 @@ export function VideoPlayer() { setError(e); }, []); + // A direct/reloaded /player route with no active stream must not trap the + // user on an endless spinner. + useEffect(() => { + if (playbackStream) return; + const timer = window.setTimeout( + () => navigate({ to: "/home", replace: true }), + 250, + ); + return () => window.clearTimeout(timer); + }, [playbackStream, navigate]); + if (!playbackStream) { return (
diff --git a/src/utils/queryCachePersistence.ts b/src/utils/queryCachePersistence.ts new file mode 100644 index 0000000..d7d91e9 --- /dev/null +++ b/src/utils/queryCachePersistence.ts @@ -0,0 +1,106 @@ +import type { QueryClient } from "@tanstack/react-query"; + +const STORAGE_KEY = "blink:query-cache:v1"; +const MAX_AGE_MS = 1000 * 60 * 60 * 24 * 7; +const MAX_ENTRIES = 60; + +type PersistedEntry = { + key: readonly unknown[]; + data: unknown; + updatedAt: number; +}; + +type PersistedCache = { + owner: string; + entries: PersistedEntry[]; +}; + +const isPersistableKey = (key: readonly unknown[]) => + typeof key[0] === "string" && (key[0] === "home" || key[0] === "libraries"); + +/** + * Synchronously hydrate the most useful home/library queries from + * localStorage. React Query then renders cached content immediately and + * refetches in the background. + */ +export const restoreQueryCache = (client: QueryClient, owner: string) => { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return; + const cached = JSON.parse(raw) as PersistedCache; + if (cached.owner !== owner || !Array.isArray(cached.entries)) return; + const now = Date.now(); + for (const entry of cached.entries) { + if (!Array.isArray(entry.key) || !isPersistableKey(entry.key)) continue; + if (!entry.updatedAt || now - entry.updatedAt > MAX_AGE_MS) continue; + client.setQueryData(entry.key, entry.data, { + updatedAt: entry.updatedAt, + }); + } + } catch (error) { + console.warn("Could not restore the query cache", error); + } +}; + +/** Persist only home/library query data; throttled and silently forgiving. */ +export const persistQueryCache = ( + client: QueryClient, + getOwner: () => string | undefined, +) => { + let timer: ReturnType | undefined; + + const save = () => { + const owner = getOwner(); + if (!owner) return; + try { + const entries = client + .getQueryCache() + .getAll() + .filter( + (query) => + query.state.status === "success" && + query.state.data !== undefined && + isPersistableKey(query.queryKey), + ) + .sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt) + .slice(0, MAX_ENTRIES) + .map((query) => ({ + key: query.queryKey, + data: query.state.data, + updatedAt: query.state.dataUpdatedAt, + })); + const payload: PersistedCache = { owner, entries }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(payload)); + } catch (error) { + // A full storage quota must never break navigation. + console.warn("Could not persist the query cache", error); + try { + localStorage.removeItem(STORAGE_KEY); + } catch { + // Ignore. + } + } + }; + + const schedule = () => { + window.clearTimeout(timer); + timer = window.setTimeout(save, 400); + }; + + const unsubscribe = client.getQueryCache().subscribe(schedule); + window.addEventListener("beforeunload", save); + + return () => { + window.clearTimeout(timer); + unsubscribe(); + window.removeEventListener("beforeunload", save); + }; +}; + +export const clearPersistedQueryCache = () => { + try { + localStorage.removeItem(STORAGE_KEY); + } catch { + // Ignore. + } +}; diff --git a/src/utils/storage/user.ts b/src/utils/storage/user.ts index 7b4a800..dff9116 100644 --- a/src/utils/storage/user.ts +++ b/src/utils/storage/user.ts @@ -40,6 +40,7 @@ const getUser = async () => { */ const delUser = async () => { sessionStorage.removeItem("accessToken"); + localStorage.removeItem("blink:query-cache:v1"); await user.clear(); await user.save(); }; diff --git a/src/utils/store/api.tsx b/src/utils/store/api.tsx index ce5307d..47cada9 100644 --- a/src/utils/store/api.tsx +++ b/src/utils/store/api.tsx @@ -46,22 +46,30 @@ export const jellyfin = new Jellyfin({ }, }); -export const initializeApi = async () => { - const currentServerId = await getDefaultServer(); - if (currentServerId) { - const currentServer = await getServer(currentServerId); - if (currentServer?.address) { - const userOnDisk = await getUser(); - if (userOnDisk) { - return jellyfin.createApi( - currentServer.address, - userOnDisk.AccessToken, - ); - } - return jellyfin.createApi(currentServer.address); - } - } - return undefined; +export type InitialSession = { + api?: Api; + user?: { Name: string; AccessToken: string; Id: string } | null; +}; + +/** + * Restore the API and a minimal user snapshot from local storage in one pass. + * The full UserDto is fetched in the background, so the UI can render without + * waiting for the server. + */ +export const initializeApi = async (): Promise => { + const [currentServerId, userOnDisk] = await Promise.all([ + getDefaultServer(), + getUser(), + ]); + if (!currentServerId) return { user: userOnDisk }; + + const currentServer = await getServer(currentServerId); + if (!currentServer?.address) return { user: userOnDisk }; + + return { + api: jellyfin.createApi(currentServer.address, userOnDisk?.AccessToken), + user: userOnDisk, + }; }; export const ApiContext = createContext>(undefined!); diff --git a/src/utils/store/central.tsx b/src/utils/store/central.tsx index f080f14..3acbe37 100644 --- a/src/utils/store/central.tsx +++ b/src/utils/store/central.tsx @@ -51,7 +51,13 @@ export const setAppReady = () => { const CentralContext = createContext>(null!); -export const CentralProvider = ({ children }: { children: ReactNode }) => { +export const CentralProvider = ({ + children, + initialUser, +}: { + children: ReactNode; + initialUser?: UserDto | null; +}) => { const [store] = useState(() => createStore()((set) => ({ defaultServerOnDisk: async () => (await getDefaultServer()) ?? null, @@ -63,7 +69,7 @@ export const CentralProvider = ({ children }: { children: ReactNode }) => { allServersOnDisk: async () => await getAllServers(), userOnDisk: async () => (await getUser()) ?? null, clientVersion: version, - currentUser: null, + currentUser: initialUser ?? null, fetchCurrentUser: async (api) => { if (api?.accessToken) { const user = (await getUserApi(api).getCurrentUser()).data;