import { randomUUID } from 'node:crypto'; import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises'; import { dirname, isAbsolute, join, relative } from 'node:path'; import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { Copies } from '@shared/schemas/install.ts'; import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts'; const CACHE_FOLDER = 'decal-cache'; let changing = false; export function decalImportInProgress(): boolean { return changing; } export function decalCachePath(dataPath: string, cacheId: string): string { return join(dataPath, CACHE_FOLDER, cacheId); } async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise { if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed'); const data = await canonicalCopyPath(dataPath); const root = join(data, CACHE_FOLDER); if ((isInSteamLibrary(data) && (!steamDataConfirmed || relative(dataPath, data) !== '')) || relative(root, await canonicalCopyPath(root)) !== '') { throw new AppError('decal_import_failed'); } return root; } /** Import the selected cache as its own snapshot so a later build can use the copy's data alone. */ export async function importDecalCache( dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false, ): Promise { if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid'); const source = await realpath(sourcePath).catch(() => null); if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid'); const root = await cacheRoot(dataPath, steamDataConfirmed); if (copyPathContains(source, root) || copyPathContains(root, source)) { throw new AppError('decal_source_invalid'); } const id = randomUUID(); const target = join(root, id); try { await mkdir(root, { recursive: true }); await cp(source, target, { recursive: true, force: false, errorOnExist: true, filter: async (path) => { signal?.throwIfAborted(); const entry = await lstat(path); if (!entry.isDirectory() && !entry.isFile()) throw new AppError('decal_source_invalid'); return true; }, }); signal?.throwIfAborted(); if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid'); return id; } catch (error) { await discardDecalCache(dataPath, id, steamDataConfirmed); if (signal?.aborted || error instanceof AppError) throw error; console.error('[decals] could not import the cache:', error); throw new AppError('decal_import_failed'); } } export async function discardDecalCache(dataPath: string, id: string, steamDataConfirmed = false): Promise { try { const root = await cacheRoot(dataPath, steamDataConfirmed); const target = decalCachePath(dataPath, id); const actual = await realpath(target).catch(() => null); if (actual && relative(root, dirname(actual)) === '' && relative(join(root, id), actual) === '') { await rm(actual, { recursive: true, force: true }); } } catch (error) { console.warn('[decals] could not remove the replaced cache:', error); } } export async function changeDecalSource(id: string, source: string | null): Promise { if (changing) throw new AppError('maintenance_busy'); changing = true; try { const record = (await listCopies()).copies.find((copy) => copy.id === id); if (!record) throw new AppError('copy_not_found'); const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]); if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required'); const dataInSteam = isInSteamLibrary(dataPath); const cacheId = source === null ? undefined : await importDecalCache(dataPath, source, undefined, dataInSteam); let copies: Copies; try { copies = await updateCopyRecord(id, (current) => { const { decalCacheId, ...other } = current; return cacheId === undefined ? other : { ...other, decalCacheId: cacheId }; }); } catch (error) { if (cacheId) await discardDecalCache(dataPath, cacheId, dataInSteam); throw error; } if (record.decalCacheId) await discardDecalCache(dataPath, record.decalCacheId, dataInSteam); return copies; } finally { changing = false; } }