All files / src/hooks useSplashScreen.ts

94.28% Statements 132/140
91.3% Branches 42/46
100% Functions 3/3
94.28% Lines 132/140

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 2071x   1x 1x           1x                                         1x             1x 29x 29x 29x 10x 29x   29x     29x     29x 10x 9x 9x 9x 9x 9x 9x 29x 29x 29x 29x   29x 1x 1x 29x     29x 10x   9x   9x 63x 63x 63x 63x   9x 9x 9x     9x     9x 9x 9x   9x 4x 4x 4x 4x 4x 4x   4x 1x 1x 1x 1x 1x   4x 2x 2x 1x 1x 2x 4x   9x     9x 9x 1x 1x 1x 9x 8x 8x 8x 8x 8x 8x     9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 8x 8x 8x 8x 8x 8x           9x 9x 9x 9x 9x 9x 9x 9x 9x 9x               9x   9x 1x 9x 8x 8x   9x 9x 9x   9x 9x     29x   29x 29x 1x 28x 28x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x  
import { useState, useEffect, useCallback, useRef } 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 { parseDateMs } from "@/lib/date";
import type { UpdateState } from "@/hooks/useUpdateChecker";
 
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;
}
 
const SESSION_KEY = "splash-shown";
 
interface UseSplashScreenOptions {
	updateState: UpdateState;
	onComplete?: (didRefreshProviders: boolean) => void;
}
 
export const useSplashScreen = (options: UseSplashScreenOptions): SplashScreenState => {
	const { updateState, onComplete } = options;
	const onCompleteRef = useRef(onComplete);
	useEffect(() => {
		onCompleteRef.current = onComplete;
	}, [onComplete]);
 
	const alreadyShownRef = useRef(sessionStorage.getItem(SESSION_KEY) === "true");
 
	// Consume providers from ChannelsContext (already loaded on mount — no extra Tauri calls)
	const { providers, initialized } = useChannels();
 
	// Initialize all 4 steps immediately so they're visible from the first render
	const [steps, setSteps] = useState<SplashStep[]>(() => {
		if (alreadyShownRef.current) return [];
		return [
			{ id: "providers", label: "Loading providers & channels", status: "active" },
			{ id: "playlists", label: "Checking playlists…", status: "pending" },
			{ id: "epg", label: "Checking EPG…", status: "pending" },
			{ id: "updates", label: "Checking for updates", status: "pending" },
		];
	});
	const [allDone, setAllDone] = useState(alreadyShownRef.current);
	const [dismissed, setDismissed] = useState(alreadyShownRef.current);
	const [hasProviders, setHasProviders] = useState(false);
 
	const dismiss = useCallback(() => {
		sessionStorage.setItem(SESSION_KEY, "true");
		setDismissed(true);
	}, []);
 
	// Run once ChannelsContext has finished its initial provider fetch
	useEffect(() => {
		if (alreadyShownRef.current || !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");
 
			// Determine which providers need refresh
			const now = Date.now();
			const providerRefreshIds: string[] = [];
			const epgRefreshIds: string[] = [];
 
			for (const p of providers) {
				const {
					autoRefresh,
					refreshIntervalHours,
					epgAutoRefresh,
					epgRefreshIntervalHours,
				} = loadProviderSettings(p.id);
 
				if (autoRefresh) {
					const lastMs = parseDateMs(p.lastUpdated);
					if (now - lastMs >= refreshIntervalHours * 60 * 60 * 1000) {
						providerRefreshIds.push(p.id);
					}
				}
 
				if (epgAutoRefresh && p.epgUrl) {
					const lastMs = getEpgLastRefresh(p.id);
					if (now - lastMs >= epgRefreshIntervalHours * 60 * 60 * 1000) {
						epgRefreshIds.push(p.id);
					}
				}
			}
 
			const didRefreshProviders = providerRefreshIds.length > 0;
 
			// Step 2: Refresh playlists (always shown; mark done immediately if nothing to do)
			setStepStatus("playlists", "active", "Refreshing playlists…");
			if (didRefreshProviders) {
				await Promise.allSettled(providerRefreshIds.map((id) => refreshProvider(id)));
				if (cancelled) return;
				setStepStatus("playlists", "done", "Playlists refreshed");
			} else {
				setStepStatus(
					"playlists",
					"done",
					hasAnyProviders ? "Playlists up to date" : "No playlists configured"
				);
			}
 
			// Step 3: Refresh EPG (always shown; mark done immediately if nothing to do)
			setStepStatus("epg", "active", "Checking EPG…");
			if (epgRefreshIds.length > 0) {
				await Promise.allSettled(
					epgRefreshIds.map((id) =>
						refreshEpg(id)
							.then(() => setEpgLastRefresh(id))
							.catch(() => {})
					)
				);
				if (cancelled) return;
				setStepStatus("epg", "done", "EPG refreshed");
			} else {
				setStepStatus(
					"epg",
					"done",
					hasAnyProviders ? "EPG up to date" : "No EPG configured"
				);
			}
 
			// 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.
			// Timeout after 10s so the splash never gets stuck.
			setStepStatus("updates", "active");
			let foundUpdate: Update | null = 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();
		return () => {
			cancelled = true;
		};
	}, [initialized]); // eslint-disable-line react-hooks/exhaustive-deps
 
	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,
	};
};