All files / src/hooks useUpdateChecker.ts

100% Statements 77/77
82.14% Branches 23/28
100% Functions 12/12
100% Lines 71/71

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                                                      2x 106x 106x 106x 106x 106x 106x 106x 106x     106x       106x   106x 41x 40x   39x 39x 39x 39x 39x   39x 29x     39x 39x   39x 39x   39x   2x 2x 2x 2x   39x 39x       39x 39x       106x 30x       106x 30x 29x   1x       29x     106x 2x 2x     106x 9x   8x 8x 8x   8x 8x   2x   1x   2x 2x   2x       6x   6x 3x 1x 2x 2x 2x 2x         5x   3x 3x 3x 3x 3x       106x                            
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, useState, useCallback, useRef } from "react";
import { check, type Update } from "@tauri-apps/plugin-updater";
import { relaunch } from "@tauri-apps/plugin-process";
import { listen } from "@tauri-apps/api/event";
import { getInstallInfo, packageUpdate } from "@/lib/tauri";
import { isMobilePlatform } from "@/lib/platform";
 
export interface UpdateState {
	update: Update | null;
	checking: boolean;
	installing: boolean;
	progress: number | null;
	error: string | null;
	/** Why the last update check failed, or null when it succeeded */
	checkError: string | null;
	/** true when using package manager update (deb/rpm) instead of Tauri updater */
	packageInstall: boolean;
	/** false on iOS and Android, where the app store updates the app */
	supported: boolean;
	dismiss: () => void;
	install: () => Promise<void>;
	checkForUpdates: () => Promise<Update | null>;
}
 
export const useUpdateChecker = (): UpdateState => {
	const [update, setUpdate] = useState<Update | null>(null);
	const [checking, setChecking] = useState(false);
	const [installing, setInstalling] = useState(false);
	const [progress, setProgress] = useState<number | null>(null);
	const [error, setError] = useState<string | null>(null);
	const [checkError, setCheckError] = useState<string | null>(null);
	const [packageInstall, setPackageInstall] = useState(false);
	const [supported] = useState(() => !isMobilePlatform());
 
	// Cache install info so we only call it once
	const installInfoRef = useRef<{ installType: string; releaseUrl: string } | null>(null);
 
	// Share a single in-flight promise so concurrent callers (mount + splash)
	// all wait for the same check() call instead of one getting null.
	const inflightRef = useRef<Promise<Update | null> | null>(null);
 
	const checkForUpdates = useCallback((): Promise<Update | null> => {
		if (!supported) return Promise.resolve(null);
		if (inflightRef.current) return inflightRef.current;
 
		const promise = (async () => {
			setChecking(true);
			setError(null);
			setCheckError(null);
			try {
				// Fetch install info once
				if (!installInfoRef.current) {
					installInfoRef.current = await getInstallInfo();
				}
 
				const result = (await check({ timeout: 5_000 })) ?? null;
				setUpdate(result);
 
				const type = installInfoRef.current.installType;
				setPackageInstall(type === "deb" || type === "rpm");
 
				return result;
			} catch (err) {
				const msg = err instanceof Error ? err.message : String(err);
				console.warn("[updater] check error:", msg);
				setCheckError(msg);
				return null;
			} finally {
				setChecking(false);
				inflightRef.current = null;
			}
		})();
 
		inflightRef.current = promise;
		return promise;
	}, [supported]);
 
	// Check on mount
	useEffect(() => {
		checkForUpdates();
	}, [checkForUpdates]);
 
	// Re-check every 2 hours
	useEffect(() => {
		if (!supported) return;
		const id = setInterval(
			() => {
				checkForUpdates();
			},
			2 * 60 * 60 * 1000
		);
		return () => clearInterval(id);
	}, [checkForUpdates, supported]);
 
	const dismiss = useCallback(() => {
		setUpdate(null);
		setPackageInstall(false);
	}, []);
 
	const install = useCallback(async () => {
		if (!update) return;
 
		setInstalling(true);
		setProgress(0);
		setError(null);
 
		try {
			if (packageInstall) {
				// deb/rpm: use our custom package update command
				const unlisten = await listen<{ percent: number }>(
					"package-update://progress",
					(event) => setProgress(event.payload.percent)
				);
				try {
					await packageUpdate();
				} finally {
					unlisten();
				}
			} else {
				// AppImage/macOS/Windows: use Tauri's built-in updater
				let downloaded = 0;
				let total: number | undefined;
				await update.downloadAndInstall((event) => {
					if (event.event === "Started") {
						total = event.data.contentLength ?? undefined;
					} else Eif (event.event === "Progress") {
						downloaded += event.data.chunkLength;
						Eif (total) {
							setProgress(Math.min(100, Math.round((downloaded / total) * 100)));
						}
					}
				});
			}
			await relaunch();
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			console.error("[updater] install failed:", msg);
			setError(`Update failed: ${msg}`);
			setInstalling(false);
			setProgress(null);
		}
	}, [update, packageInstall]);
 
	return {
		update,
		checking,
		installing,
		progress,
		error,
		checkError,
		packageInstall,
		supported,
		dismiss,
		install,
		checkForUpdates,
	};
};