perf(startup): instant splash, cached home and non-blocking auth
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
Renders a static branded splash immediately, restores the last user/API session from disk, hydrates home/library queries from localStorage, shows a home skeleton while the first request runs, drops blocking auth network checks, and redirects a streamless /player to home.
This commit is contained in:
1 parent
b1d9b40def
commit
205b655d00
12 files changed
+424
-158
No files matched your search
+37
-29
@@ -7,54 +7,62 @@
|
||||
<!-- <script src="http://localhost:8097"></script> -->
|
||||
<title>Blink</title>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
background: #08001f;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.app-loading {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%,-50%);
|
||||
width: 10em;
|
||||
height: 10em;
|
||||
background: rgb(180 180 180);
|
||||
z-index: 100000;
|
||||
mask-image: url("./src/assets/icon-outline.png");
|
||||
mask-size: contain;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.1rem;
|
||||
transition: opacity 0.2s ease;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.app-loading.hidden {
|
||||
display: none;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
|
||||
.app-loading-anim{
|
||||
width: 150%;
|
||||
height: 100%;
|
||||
.app-loading-mark {
|
||||
position: relative;
|
||||
width: 4.6rem;
|
||||
height: 4.6rem;
|
||||
border-radius: 1.2rem;
|
||||
background: linear-gradient(135deg, #f43f7c, #7c3aed);
|
||||
box-shadow: 0 18px 50px rgb(124 58 237 / 35%);
|
||||
}
|
||||
|
||||
.app-loading-mark::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
background: linear-gradient(to right,transparent,rgb(255 255 255),transparent);
|
||||
transform: scaleX(0);
|
||||
animation: loading 0.75s linear infinite both;
|
||||
transform-origin: left;
|
||||
top: 50%;
|
||||
left: 54%;
|
||||
transform: translate(-50%, -50%);
|
||||
border-left: 1.25rem solid #fff;
|
||||
border-top: 0.78rem solid transparent;
|
||||
border-bottom: 0.78rem solid transparent;
|
||||
}
|
||||
|
||||
@keyframes loading {
|
||||
0%{
|
||||
transform: translate(-100%);
|
||||
}
|
||||
50%{
|
||||
transform: translate(0%);
|
||||
}
|
||||
100%{
|
||||
transform: translate(100%);
|
||||
}
|
||||
.app-loading-word {
|
||||
color: rgb(255 255 255 / 0.82);
|
||||
font: 600 1.35rem/1 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="app-loading">
|
||||
<!-- <img src="./src/assets/icon-outline.svg" class="app-loading-logo" /> -->
|
||||
<div class="app-loading-anim"></div>
|
||||
<div class="app-loading" role="status" aria-label="Loading Blink">
|
||||
<div class="app-loading-mark"></div>
|
||||
<div class="app-loading-word">Blink</div>
|
||||
</div>
|
||||
<div id="root"></div>
|
||||
<svg style="width: 0; height: 0; position: absolute" aria-hidden="true" focusable="false">
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Hides the static HTML splash once React has mounted the app shell.
|
||||
* Keeping it in the DOM until this point avoids a blank window while the
|
||||
* Tauri store/API session is being restored.
|
||||
*/
|
||||
const SplashHider = () => {
|
||||
useEffect(() => {
|
||||
const splash = document.querySelector(".app-loading");
|
||||
if (!splash) return;
|
||||
|
||||
// The effect runs after React committed the app shell; the static
|
||||
// splash has done its job and can fade out immediately.
|
||||
splash.classList.add("hidden");
|
||||
if (import.meta.env.DEV) performance.mark("blink:splash-hidden");
|
||||
const timer = window.setTimeout(() => splash.remove(), 260);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default SplashHider;
|
||||
+41
-20
@@ -10,6 +10,10 @@ import {
|
||||
useApiInContext,
|
||||
} from "./utils/store/api";
|
||||
import { CentralProvider, useCentralStore } from "./utils/store/central";
|
||||
import {
|
||||
persistQueryCache,
|
||||
restoreQueryCache,
|
||||
} from "./utils/queryCachePersistence";
|
||||
import { delUser } from "./utils/storage/user";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -47,7 +51,10 @@ const router = createRouter({
|
||||
// Only animate real page changes; search-param updates (typing in the
|
||||
// search field) must not trigger a transition on every keystroke.
|
||||
defaultViewTransition: {
|
||||
types: ({ pathChanged }) => (pathChanged ? ["page"] : false),
|
||||
types: ({ pathChanged }) =>
|
||||
pathChanged && document.visibilityState === "visible"
|
||||
? ["page"]
|
||||
: false,
|
||||
},
|
||||
scrollRestoration: true,
|
||||
scrollRestorationBehavior: "auto",
|
||||
@@ -70,23 +77,24 @@ function ProviderWrapper() {
|
||||
s.currentUser,
|
||||
s.fetchCurrentUser,
|
||||
]);
|
||||
// Validate/refresh the saved session in the background. The UI reads the
|
||||
// minimal user snapshot from disk immediately, so this never blocks paint.
|
||||
useEffect(() => {
|
||||
if (api?.accessToken && !user?.Id) {
|
||||
fetchCurrentUser(api).catch(async (error) => {
|
||||
console.error("Could not restore the saved session", error);
|
||||
const status = (error as { response?: { status?: number } })?.response
|
||||
?.status;
|
||||
// Only an actual authorization failure should log the user out.
|
||||
if (status !== 401 && status !== 403) return;
|
||||
await delUser();
|
||||
createApi(api.basePath, undefined);
|
||||
router.navigate({
|
||||
to: "/login/manual",
|
||||
search: { redirect: window.location.pathname },
|
||||
});
|
||||
if (!api?.accessToken) return;
|
||||
fetchCurrentUser(api).catch(async (error) => {
|
||||
console.error("Could not restore the saved session", error);
|
||||
const status = (error as { response?: { status?: number } })?.response
|
||||
?.status;
|
||||
// Only an actual authorization failure should log the user out.
|
||||
if (status !== 401 && status !== 403) return;
|
||||
await delUser();
|
||||
createApi(api.basePath, undefined);
|
||||
router.navigate({
|
||||
to: "/login/manual",
|
||||
search: { redirect: window.location.pathname },
|
||||
});
|
||||
}
|
||||
}, [api, user, fetchCurrentUser, createApi]);
|
||||
});
|
||||
}, [api?.accessToken, fetchCurrentUser, createApi]);
|
||||
useEffect(() => {
|
||||
if (api) {
|
||||
console.log(`API is set - Route ${window.location.pathname}`);
|
||||
@@ -134,12 +142,27 @@ const init = async () => {
|
||||
}, 200);
|
||||
});
|
||||
|
||||
const initialApi = await initializeApi();
|
||||
const { api: initialApi, user: initialUser } = await initializeApi();
|
||||
|
||||
const owner =
|
||||
initialApi?.basePath && initialUser?.Id
|
||||
? `${initialApi.basePath}|${initialUser.Id}`
|
||||
: undefined;
|
||||
if (owner) {
|
||||
restoreQueryCache(queryClient, owner);
|
||||
persistQueryCache(queryClient, () => owner);
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CentralProvider>
|
||||
<CentralProvider
|
||||
initialUser={
|
||||
initialUser
|
||||
? { Id: initialUser.Id, Name: initialUser.Name }
|
||||
: null
|
||||
}
|
||||
>
|
||||
<ApiProvider initialApi={initialApi}>
|
||||
<ProviderWrapper />
|
||||
</ApiProvider>
|
||||
@@ -150,5 +173,3 @@ const init = async () => {
|
||||
};
|
||||
|
||||
init();
|
||||
|
||||
document.querySelector(".app-loading")!.classList.toggle("hidden");
|
||||
@@ -26,6 +26,7 @@ import Backdrop from "@/components/backdrop";
|
||||
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
|
||||
import OverlayScrollbar from "@/components/overlayScrollbar";
|
||||
import PlaybackSync from "@/components/playback/PlaybackSync";
|
||||
import SplashHider from "@/components/splash";
|
||||
import RemoteControlDialog from "@/components/remoteControl";
|
||||
import RouterLoading from "@/components/routerLoading";
|
||||
import Search from "@/components/search";
|
||||
@@ -50,6 +51,7 @@ export const Route = createRootRouteWithContext<ApiContext>()({
|
||||
<ThemeProvider theme={theme}>
|
||||
<SnackbarProvider maxSnack={5}>
|
||||
<CssBaseline />
|
||||
<SplashHider />
|
||||
{/* <NProgress /> */}
|
||||
|
||||
<RouterLoading />
|
||||
|
||||
+26
-83
@@ -1,14 +1,13 @@
|
||||
import { getDefaultServer, getServer } from "@/utils/storage/servers";
|
||||
import { delUser, getUser } from "@/utils/storage/user";
|
||||
import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api";
|
||||
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
|
||||
import { getUser } from "@/utils/storage/user";
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
|
||||
const isAuthError = (error: unknown) => {
|
||||
const status = (error as { response?: { status?: number } })?.response?.status;
|
||||
return status === 401 || status === 403;
|
||||
};
|
||||
|
||||
/**
|
||||
* Session bootstrap is deliberately local-only: reading the Tauri store is
|
||||
* quick, while network verification would block the first render. The token
|
||||
* is validated in the background by ProviderWrapper, which redirects to the
|
||||
* login page on a real 401/403 without punishing transient network errors.
|
||||
*/
|
||||
export const Route = createFileRoute("/_api")({
|
||||
beforeLoad: async ({ context, location }) => {
|
||||
const isAuthPage =
|
||||
@@ -18,86 +17,30 @@ export const Route = createFileRoute("/_api")({
|
||||
|
||||
if (!context.api) {
|
||||
const currentServerId = await getDefaultServer();
|
||||
if (currentServerId) {
|
||||
const currentServer = await getServer(currentServerId);
|
||||
if (currentServer?.address) {
|
||||
const apiTemp = context.jellyfinSDK.createApi(
|
||||
currentServer?.address,
|
||||
undefined,
|
||||
);
|
||||
try {
|
||||
await getSystemApi(apiTemp).getPingSystem();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw redirect({
|
||||
to: "/error/$code",
|
||||
params: {
|
||||
code: "101",
|
||||
},
|
||||
});
|
||||
}
|
||||
const userOnDisk = await getUser();
|
||||
if (userOnDisk) {
|
||||
if (location.pathname !== "/login/manual") {
|
||||
const apiTemp = context.jellyfinSDK.createApi(
|
||||
currentServer?.address,
|
||||
userOnDisk.AccessToken,
|
||||
);
|
||||
try {
|
||||
await getUserApi(apiTemp).getCurrentUser();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (isAuthError(error)) {
|
||||
await delUser();
|
||||
throw redirect({
|
||||
to: "/login/manual",
|
||||
search: {
|
||||
redirect: location.href,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Transient network failure: keep the saved session
|
||||
// instead of logging the user out.
|
||||
}
|
||||
}
|
||||
context.createApi(currentServer?.address, userOnDisk.AccessToken);
|
||||
} else {
|
||||
context.createApi(currentServer?.address, undefined); // Creates Api
|
||||
if (!isAuthPage) {
|
||||
throw redirect({
|
||||
to: "/login/manual",
|
||||
search: { redirect: location.href },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!currentServerId) {
|
||||
if (!isAuthPage) throw redirect({ to: "/setup/server/add" });
|
||||
return;
|
||||
}
|
||||
} else if (context.api) {
|
||||
// The API was created from a token stored on disk. The token can be
|
||||
// revoked (logged out everywhere / server reset); verify it and send
|
||||
// the user back to the login page instead of leaving a broken page.
|
||||
if (!context.api.accessToken && !isAuthPage) {
|
||||
|
||||
const currentServer = await getServer(currentServerId);
|
||||
if (!currentServer?.address) {
|
||||
if (!isAuthPage) throw redirect({ to: "/setup/server/add" });
|
||||
return;
|
||||
}
|
||||
|
||||
const userOnDisk = await getUser();
|
||||
context.createApi(currentServer.address, userOnDisk?.AccessToken);
|
||||
if (!userOnDisk?.AccessToken && !isAuthPage) {
|
||||
throw redirect({
|
||||
to: "/login/manual",
|
||||
search: { redirect: location.href },
|
||||
});
|
||||
}
|
||||
if (context.api.accessToken && !isAuthPage) {
|
||||
try {
|
||||
await getUserApi(context.api).getCurrentUser();
|
||||
} catch (error) {
|
||||
console.error("Could not verify the stored access token", error);
|
||||
if (isAuthError(error)) {
|
||||
await delUser();
|
||||
context.createApi(context.api.basePath, undefined);
|
||||
throw redirect({
|
||||
to: "/login/manual",
|
||||
search: { redirect: location.href },
|
||||
});
|
||||
}
|
||||
// Network hiccup: do not throw the user out of the app.
|
||||
}
|
||||
}
|
||||
} else if (!context.api.accessToken && !isAuthPage) {
|
||||
throw redirect({
|
||||
to: "/login/manual",
|
||||
search: { redirect: location.href },
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -146,6 +146,101 @@ body.has-player-bar .home-sections {
|
||||
padding-bottom: 10rem;
|
||||
}
|
||||
|
||||
/* Instant frame while the first home request resolves or cache restores. */
|
||||
.home-skeleton {
|
||||
position: relative;
|
||||
height: calc(100vh - 16px);
|
||||
min-height: 560px;
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(
|
||||
circle at 75% 35%,
|
||||
rgb(80 80 105 / 0.28),
|
||||
transparent 55%
|
||||
),
|
||||
linear-gradient(135deg, #11131a 0%, #0a0b10 70%);
|
||||
}
|
||||
|
||||
.home-skeleton-copy {
|
||||
position: absolute;
|
||||
left: clamp(2rem, 5vw, 4.5rem);
|
||||
bottom: calc(var(--home-trending-space, 200px) + 3.5rem);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.9rem;
|
||||
width: min(42rem, 55%);
|
||||
}
|
||||
|
||||
.home-skeleton-pill,
|
||||
.home-skeleton-title,
|
||||
.home-skeleton-text,
|
||||
.home-skeleton-buttons,
|
||||
.home-skeleton-heading,
|
||||
.home-skeleton-cards span {
|
||||
display: block;
|
||||
border-radius: 12px;
|
||||
background: rgb(255 255 255 / 0.08);
|
||||
}
|
||||
|
||||
.home-skeleton-pill {
|
||||
width: 7em;
|
||||
height: 2.1em;
|
||||
}
|
||||
|
||||
.home-skeleton-title {
|
||||
width: 92%;
|
||||
height: clamp(2.4rem, 4vw, 4rem);
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.home-skeleton-text {
|
||||
width: 100%;
|
||||
height: 5.2rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.home-skeleton-buttons {
|
||||
width: 18rem;
|
||||
height: 3.1rem;
|
||||
border-radius: 999px;
|
||||
background: rgb(255 255 255 / 0.14);
|
||||
}
|
||||
|
||||
.home-skeleton-trending {
|
||||
position: absolute;
|
||||
left: clamp(2rem, 5vw, 4.5rem);
|
||||
right: clamp(2rem, 5vw, 4.5rem);
|
||||
bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.home-skeleton-heading {
|
||||
width: 8em;
|
||||
height: 1.4rem;
|
||||
margin-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.home-skeleton-cards {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.home-skeleton-cards span {
|
||||
flex: 0 0 auto;
|
||||
width: clamp(200px, 21vw, 300px);
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.home-skeleton-copy {
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.home-skeleton-cards span {
|
||||
width: 42vw;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.home-header {
|
||||
.home-nav-link {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useSuspenseQuery } from "@tanstack/react-query";
|
||||
import React, { useCallback, useMemo } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React, { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import "./home.scss";
|
||||
|
||||
@@ -51,7 +51,7 @@ function Home() {
|
||||
}
|
||||
|
||||
function HomeContent({ api, user }: { api: Api; user: UserDto }) {
|
||||
const libraries = useSuspenseQuery({
|
||||
const libraries = useQuery({
|
||||
queryKey: ["libraries"],
|
||||
queryFn: async () => {
|
||||
const libs = await getUserViewApi(api).getUserViews({
|
||||
@@ -62,11 +62,11 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) {
|
||||
networkMode: "always",
|
||||
});
|
||||
|
||||
const latestMedia = useSuspenseQuery(
|
||||
const latestMedia = useQuery(
|
||||
getLatestItemsQueryOptions(api, user.Id),
|
||||
);
|
||||
|
||||
const resumeItemsVideo = useSuspenseQuery({
|
||||
const resumeItemsVideo = useQuery({
|
||||
queryKey: ["home", "resume", "video"],
|
||||
queryFn: async () => {
|
||||
const resumeItems = await getLibraryApi(api).getResumeItems({
|
||||
@@ -80,7 +80,7 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) {
|
||||
},
|
||||
});
|
||||
|
||||
const resumeItemsAudio = useSuspenseQuery({
|
||||
const resumeItemsAudio = useQuery({
|
||||
queryKey: ["home", "resume", "audio"],
|
||||
queryFn: async () => {
|
||||
const resumeItems = await getLibraryApi(api).getResumeItems({
|
||||
@@ -94,7 +94,7 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) {
|
||||
},
|
||||
});
|
||||
|
||||
const upNextItems = useSuspenseQuery({
|
||||
const upNextItems = useQuery({
|
||||
queryKey: ["home", "upNext"],
|
||||
queryFn: async () => {
|
||||
const upNext = await getShowApi(api).getNextUp({
|
||||
@@ -178,6 +178,46 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) {
|
||||
?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!import.meta.env.DEV) return;
|
||||
if (!libraries.data || !latestMedia.data) return;
|
||||
performance.mark("blink:home-ready");
|
||||
}, [libraries.data, latestMedia.data]);
|
||||
|
||||
// Render the frame immediately; only the expensive content waits for data.
|
||||
if (!libraries.data || !latestMedia.data) {
|
||||
return (
|
||||
<main className="home-cinema">
|
||||
<div className="home-frame">
|
||||
<HomeHeader
|
||||
libraries={libraries.data?.Items ?? []}
|
||||
onNewAndPopular={scrollToNewAndPopular}
|
||||
/>
|
||||
<section
|
||||
className="home-skeleton"
|
||||
aria-busy="true"
|
||||
aria-label="Loading home"
|
||||
>
|
||||
<div className="home-skeleton-copy">
|
||||
<span className="home-skeleton-pill" />
|
||||
<span className="home-skeleton-title" />
|
||||
<span className="home-skeleton-text" />
|
||||
<span className="home-skeleton-buttons" />
|
||||
</div>
|
||||
<div className="home-skeleton-trending">
|
||||
<span className="home-skeleton-heading" />
|
||||
<div className="home-skeleton-cards">
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<span key={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="home-cinema">
|
||||
<div className="home-frame">
|
||||
|
||||
@@ -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<HTMLVideoElement | null>(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 (
|
||||
<div className="video-player">
|
||||
|
||||
@@ -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<typeof setTimeout> | 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.
|
||||
}
|
||||
};
|
||||
@@ -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();
|
||||
};
|
||||
|
||||
+24
-16
@@ -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<InitialSession> => {
|
||||
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<StoreApi<ApiStore>>(undefined!);
|
||||
|
||||
@@ -51,7 +51,13 @@ export const setAppReady = () => {
|
||||
|
||||
const CentralContext = createContext<StoreApi<CentralStore>>(null!);
|
||||
|
||||
export const CentralProvider = ({ children }: { children: ReactNode }) => {
|
||||
export const CentralProvider = ({
|
||||
children,
|
||||
initialUser,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
initialUser?: UserDto | null;
|
||||
}) => {
|
||||
const [store] = useState(() =>
|
||||
createStore<CentralStore>()((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;
|
||||
|
||||
Reference in new issue
Block a user