import { access, mkdir } from 'node:fs/promises'; import { AppError } from '@shared/errors.ts'; import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts'; import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts'; import { writeInstallRecord } from './install-record.ts'; import { checkPatches } from './patch-check.ts'; import { backUpStockFiles, stockBackupPath } from './stock-backup.ts'; /** * Install the offline version: check the patches against the player's game, * copy it (method "copy"), keep its stock files in the copy's backup folder and record the * installation. The patched files are written by the build at every launch, with that launch's * port; installing writes no patched file. * * The patches are checked first, on the stock files the copy would get, so a game whose * essential patches do not fit is refused before 90 GB are copied. */ /** Room kept free on the target drive beyond the copy itself, for the game's caches and logs. */ const SPARE_BYTES = 1024 ** 3; /** At most this often a progress event goes to the window. */ const PROGRESS_INTERVAL_MS = 250; let running: AbortController | null = null; export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise { if (running) throw new AppError('install_busy'); const controller = new AbortController(); running = controller; try { return await install(request, controller.signal, throttled(onProgress)); } finally { running = null; } } /** Stops a running copy at the next file; returns whether an installation was running. */ export function cancelInstall(): boolean { if (!running) return false; running.abort(); return true; } /** * The stock files a check of `gameFolder` starts from: its backup folder when it already has one * (a folder installed before, whose own files may be patched), otherwise its own files. */ export async function stockFolderOf(gameFolder: string): Promise { const backup = stockBackupPath(gameFolder); try { await access(backup); return backup; } catch { return gameFolder; } } /** Which patches fit the game in `gameFolder`, for the window to show before installing. */ export async function checkGameFolder(gameFolder: string, dataPath: string): Promise { await requireGameFolder(gameFolder); return checkPatches(await stockFolderOf(gameFolder), dataPath); } async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise { const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath; const game = await requireGameFolder(gameFolder); const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath; const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null; if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem }); const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary; if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed'); report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); await mkdir(request.dataPath, { recursive: true }); const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath); const essential = check.unavailable.filter((patch) => patch.essential); if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') }); if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted'); signal.throwIfAborted(); if (request.method === 'copy') await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report); report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const stockBackup = await backUpStockFiles(copyPath); report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const record: InstallRecord = { method: request.method, copyPath, dataPath: request.dataPath, stockBackupPath: stockBackup, gameVersion: game.version, unavailablePatches: check.unavailable, installedAt: new Date().toISOString(), }; await writeInstallRecord(record); return record; } async function copyGame( source: string, target: string, freeBytes: number | null, signal: AbortSignal, report: (progress: InstallProgress) => void, ): Promise { report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const plan = await planCopy(source); if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) { throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) }); } const targetExisted = await exists(target); const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length }; report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); try { await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals })); } catch (error) { await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup)); if (signal.aborted) throw new AppError('install_cancelled'); console.error('[install] copying failed:', error); throw new AppError('copy_failed'); } } async function requireGameFolder(path: string) { const game = await inspectGameFolder(path); if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path }); return game; } /** Passes on the first and last report of each phase and at most one per interval in between. */ function throttled(onProgress: (progress: InstallProgress) => void): (progress: InstallProgress) => void { let lastSent = 0; let lastPhase = ''; return (progress) => { const now = Date.now(); const finished = progress.totalFiles > 0 && progress.doneFiles === progress.totalFiles; if (progress.phase !== lastPhase || finished || now - lastSent >= PROGRESS_INTERVAL_MS) { lastSent = now; lastPhase = progress.phase; onProgress(progress); } }; } function gigabytes(bytes: number): string { return (bytes / 1024 ** 3).toFixed(1); } async function exists(path: string): Promise { try { await access(path); return true; } catch { return false; } }