All files / src/hooks useSplashScreen.ts

97.91% Statements 94/96
95.65% Branches 44/46
100% Functions 25/25
100% Lines 81/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262                                                                                                                2x 118x 118x   118x     118x       118x 37x 31x                 118x 118x 118x   118x 6x 6x       118x 44x   31x   31x 200x 774x       31x 31x 31x     31x   31x         31x           31x 12x         31x 59x 59x 48x         48x   12x 11x 11x 10x 3x 7x 1x           6x   10x       31x     6x                   30x     29x       6x 5x                     29x   29x 2x 2x 2x             27x   27x 27x     27x       3x 2x 2x 2x 3x     24x   23x 2x   21x     23x 23x     31x   1x 1x 1x 1x 4x     1x 1x   31x 31x                 118x   417x     118x                    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useState, useEffect, useCallback } from "react";
import type { Update } from "@tauri-apps/plugin-updater";
import { refreshProvider, refreshEpg } from "@/lib/tauri";
import {
	loadProviderSettings,
	getEpgLastRefresh,
	setEpgLastRefresh,
	useChannels,
} from "@/hooks/useChannels";
import { findDueRefreshes, refreshKeys } from "@/lib/refresh-schedule";
import type { UpdateState } from "@/hooks/useUpdateChecker";
import { readStorage, SPLASH_SHOWN_KEY, writeStorage } from "@/lib/storage";
import { useLatestRef } from "@/hooks/useLatestRef";
 
export type StepStatus = "pending" | "active" | "done" | "error";
 
export interface SplashStep {
	id: string;
	label: string;
	status: StepStatus;
}
 
export interface SplashScreenState {
	steps: SplashStep[];
	allDone: boolean;
	progress: number;
	update: Update | null;
	dismissed: boolean;
	hasProviders: boolean;
	dismiss: () => void;
}
 
/** One of the splash steps that refreshes a list of providers. */
interface RefreshStep {
	id: string;
	ids: string[];
	refresh: (id: string) => Promise<unknown>;
	labels: {
		active: string;
		failed: string;
		/** Plural noun for the partial failure message. */
		sources: string;
		done: string;
		upToDate: string;
		none: string;
	};
}
 
interface UseSplashScreenOptions {
	updateState: UpdateState;
	onComplete?: (didRefreshProviders: boolean) => void;
}
 
export const useSplashScreen = (options: UseSplashScreenOptions): SplashScreenState => {
	const { updateState, onComplete } = options;
	const onCompleteRef = useLatestRef(onComplete);
 
	const [alreadyShown] = useState(() => readStorage(SPLASH_SHOWN_KEY, "session") === "true");
 
	// Consume providers from ChannelsContext (already loaded on mount — no extra Tauri calls)
	const { providers, initialized, autoRefresh } = useChannels();
 
	// Initialize all steps immediately so they're visible from the first render.
	// The app store updates the mobile apps, so they skip the update check.
	const [steps, setSteps] = useState<SplashStep[]>(() => {
		if (alreadyShown) return [];
		return [
			{ id: "providers", label: "Loading providers & channels", status: "active" },
			{ id: "playlists", label: "Checking playlists…", status: "pending" },
			{ id: "epg", label: "Checking EPG…", status: "pending" },
			...(updateState.supported
				? [{ id: "updates", label: "Checking for updates", status: "pending" as const }]
				: []),
		];
	});
	const [allDone, setAllDone] = useState(alreadyShown);
	const [dismissed, setDismissed] = useState(alreadyShown);
	const [hasProviders, setHasProviders] = useState(false);
 
	const dismiss = useCallback(() => {
		writeStorage(SPLASH_SHOWN_KEY, "true", "session");
		setDismissed(true);
	}, []);
 
	// Run once ChannelsContext has finished its initial provider fetch
	useEffect(() => {
		if (alreadyShown || !initialized) return;
 
		let cancelled = false;
 
		const setStepStatus = (id: string, status: StepStatus, label?: string) => {
			setSteps((prev) =>
				prev.map((s) => (s.id === id ? { ...s, status, ...(label ? { label } : {}) } : s))
			);
		};
 
		const run = async () => {
			const hasAnyProviders = providers.length > 0;
			setHasProviders(hasAnyProviders);
 
			// Step 1 complete — providers came from ChannelsContext, no extra fetch needed
			setStepStatus("providers", "done", "Providers & channels loaded");
 
			const { playlistIds: providerRefreshIds, epgIds: epgRefreshIds } = findDueRefreshes(
				providers,
				{ settingsFor: loadProviderSettings, epgLastRefreshFor: getEpgLastRefresh }
			);
 
			const didRefreshProviders = providerRefreshIds.length > 0;
 
			// Runs the refresh through the poll's tracker. A refresh the poll already
			// started is joined, not run twice, and the poll won't start this one
			// again while it runs. One still waiting to retry after a failure
			// counts as failed.
			const tracked = (key: string, refresh: () => Promise<unknown>) =>
				autoRefresh.run(key, refresh) ??
				Promise.reject(new Error(`${key} failed recently, waiting to retry`));
 
			// Runs one refresh step and returns false if the effect was cleaned up
			// while it waited, so the caller stops too.
			const runRefreshStep = async (step: RefreshStep): Promise<boolean> => {
				setStepStatus(step.id, "active", step.labels.active);
				if (step.ids.length === 0) {
					setStepStatus(
						step.id,
						"done",
						hasAnyProviders ? step.labels.upToDate : step.labels.none
					);
					return true;
				}
				const results = await Promise.allSettled(step.ids.map((id) => step.refresh(id)));
				if (cancelled) return false;
				const failed = results.filter((r) => r.status === "rejected").length;
				if (failed === results.length) {
					setStepStatus(step.id, "error", step.labels.failed);
				} else if (failed > 0) {
					setStepStatus(
						step.id,
						"error",
						`Failed to refresh ${failed} of ${results.length} ${step.labels.sources}`
					);
				} else {
					setStepStatus(step.id, "done", step.labels.done);
				}
				return true;
			};
 
			// Step 2: Refresh playlists (always shown; mark done immediately if nothing to do)
			const playlistsFinished = await runRefreshStep({
				id: "playlists",
				ids: providerRefreshIds,
				refresh: (id) => tracked(refreshKeys.playlist(id), () => refreshProvider(id)),
				labels: {
					active: "Refreshing playlists…",
					failed: "Failed to refresh playlists",
					sources: "playlists",
					done: "Playlists refreshed",
					upToDate: "Playlists up to date",
					none: "No playlists configured",
				},
			});
			if (!playlistsFinished) return;
 
			// Step 3: Refresh EPG (always shown; mark done immediately if nothing to do)
			const epgFinished = await runRefreshStep({
				id: "epg",
				ids: epgRefreshIds,
				refresh: (id) =>
					tracked(refreshKeys.epg(id), () =>
						refreshEpg(id).then(() => setEpgLastRefresh(id))
					),
				labels: {
					active: "Checking EPG…",
					failed: "Failed to refresh EPG",
					sources: "EPG sources",
					done: "EPG refreshed",
					upToDate: "EPG up to date",
					none: "No EPG configured",
				},
			});
			Iif (!epgFinished) return;
 
			if (!updateState.supported) {
				setAllDone(true);
				onCompleteRef.current?.(didRefreshProviders);
				return;
			}
 
			// Step 4: Check for updates via the shared hook.
			// checkForUpdates() joins the in-flight promise if the mount check is
			// still running, so only one actual check() call happens.
			// Give up after 7s so the splash never gets stuck.
			setStepStatus("updates", "active");
			let foundUpdate: Update | null;
			try {
				foundUpdate = await Promise.race([
					updateState.checkForUpdates(),
					new Promise<null>((_, reject) =>
						setTimeout(() => reject(new Error("Update check timed out")), 7_000)
					),
				]);
			} catch {
				if (cancelled) return;
				setStepStatus("updates", "error", "Unable to check for updates");
				setAllDone(true);
				onCompleteRef.current?.(didRefreshProviders);
				return;
			}
 
			if (cancelled) return;
 
			if (foundUpdate) {
				setStepStatus("updates", "done", `Update available — v${foundUpdate.version}`);
			} else {
				setStepStatus("updates", "done", "Up to date");
			}
 
			setAllDone(true);
			onCompleteRef.current?.(didRefreshProviders);
		};
 
		run().catch((err) => {
			// A step that throws must still leave the splash with a way out.
			console.error("[splash] startup steps failed:", err);
			Iif (cancelled) return;
			setSteps((prev) =>
				prev.map((s) =>
					s.status === "pending" || s.status === "active" ? { ...s, status: "error" } : s
				)
			);
			setAllDone(true);
			onCompleteRef.current?.(true);
		});
		return () => {
			cancelled = true;
		};
		// The steps run once, with the providers loaded at startup. Listing
		// providers or updateState here would restart them whenever a refresh
		// above updates the provider list.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [initialized]);
 
	const progress =
		steps.length === 0
			? 0
			: steps.filter((s) => s.status === "done" || s.status === "error").length /
				steps.length;
 
	return {
		steps,
		allDone,
		progress,
		update: updateState.update,
		dismissed,
		hasProviders,
		dismiss,
	};
};