import { readdir, rm } from 'node:fs/promises'; import { isAbsolute, join, parse, relative } from 'node:path'; import { app } from 'electron'; import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { Copies, InstallRecord } from '@shared/schemas/install.ts'; import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; import { installationInProgress } from '../install/install-game.ts'; import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts'; import { checkPatches } from '../install/patch-check.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; import { readInstalledLab } from '../launch/lab-handoff.ts'; import { localServerReady } from '../launch/local-server.ts'; import { fileInfo } from './change-copy-files.ts'; import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts'; let current: { stop: AbortController; interruptible: boolean } | null = null; export function maintenanceInProgress(): boolean { return current !== null; } export function cancelMaintenance(): void { if (current?.interruptible) current.stop.abort(); } export async function maintenanceInfo(id: string): Promise { const record = await requireCopy(id); const source = await readSource(record); const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]); const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath); const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath); return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion), spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath), steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath), steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null, }; } export async function maintainCopy( request: MaintenanceRequest, publish: (progress: MaintenanceProgress) => void, ): Promise { if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy'); const job = { stop: new AbortController(), interruptible: request.operation === 'update' || request.operation === 'compact', }; current = job; const signal = job.stop.signal; const report: Report = (phase, doneBytes = 0, totalBytes = 0) => { if (phase === 'applying') job.interruptible = false; publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes }); }; try { report('checking'); return await performMaintenance(request, signal, report); } catch (error) { if (signal.aborted) throw new AppError('maintenance_cancelled'); if (error instanceof AppError) throw error; console.error('[copies] maintenance failed:', request.operation, error); throw new AppError('maintenance_failed'); } finally { current = null; } } async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise { const { id, operation, steamLocations } = request; const record = await requireCopy(id); const root = await checkedRoot(record); const dataPath = await canonicalCopyPath(record.dataPath); const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath); if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); signal.throwIfAborted(); if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) { throw new AppError('launch_steam_confirmation_required'); } switch (operation) { case 'confirm-steam': if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) || relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') { throw new AppError('maintenance_location'); } if (!needsConfirmation) return listCopies(); return updateCopyRecord(id, (copy) => ({ ...copy, steamLibraryConfirmation: { copyPath: root, dataPath }, })); case 'check': return recordCheck(record, record.stockBackupPath); case 'repair': return repair(record, root, () => report('applying')); case 'update': return updateFromSource(record, root, signal, report); case 'compact': return compactCopy(record, root, signal, report); case 'delete': report('applying'); return remove(record, root, request.deleteData); } } async function requireCopy(id: string): Promise { const record = (await listCopies()).copies.find((copy) => copy.id === id); if (!record) throw new AppError('copy_not_found'); return record; } async function checkedRoot(record: InstallRecord): Promise { const root = await safeFolder(record.copyPath, true); const backup = await canonicalCopyPath(record.stockBackupPath); if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location'); if (record.sourcePath) { const source = await canonicalCopyPath(record.sourcePath); if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location'); } return root; } async function safeFolder(path: string, steamAllowed = false): Promise { const root = await canonicalCopyPath(path); const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root); if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) || copyPathContains(root, await canonicalCopyPath(app.getAppPath())) || copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) { throw new AppError('maintenance_location'); } if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location'); return root; } async function labServerUses(root: string): Promise { const lab = await readInstalledLab().catch(() => null); if (!lab || relative(lab.copyPath, root) !== '') return false; return localServerReady(lab.port); } async function recordCheck(record: InstallRecord, folder: string): Promise { const check = await checkPatches(folder, record.dataPath); return updateCopyRecord(record.id, (copy) => ({ ...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(), })); } async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise { if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) { if (deleteData) throw new AppError('maintenance_location'); return removeCopyRecord(record.id); } const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath); const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null; if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) || (relative(data, root) !== '' && copyPathContains(data, root)))) { throw new AppError('maintenance_location'); } if (!deleteData && copyPathContains(root, data)) { await removeExcept(root, data); } else { await rm(root, { recursive: true, force: true }); } if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true }); return removeCopyRecord(record.id); } /** Keep the data folder in place when it was chosen inside this copy. */ async function removeExcept(folder: string, kept: string): Promise { if (relative(folder, kept) === '' || !(await fileInfo(folder))) return; for (const entry of await readdir(folder, { withFileTypes: true })) { const path = join(folder, entry.name); if (copyPathContains(path, kept)) { if (!entry.isDirectory()) throw new AppError('maintenance_location'); await removeExcept(path, kept); } else { await rm(path, { recursive: true, force: true }); } } }