From 5a78b1fdf85d099d750b0190d73e41d716b6f34a Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:23:17 +0800 Subject: [PATCH] fix(copies): honor confirmed Steam locations Bind confirmation to the selected copy and data paths throughout installation, launch, and maintenance. Validate redirected runtime data paths and recheck original files before refreshing an in-place backup. Verified by type checking and build. The acceptance checklist covers directory links and Steam confirmation. --- apps/launcher/src/main/ipc/handlers.ts | 8 +- .../services/copies/copy-file-maintenance.ts | 208 +++++++++++++ .../main/services/copies/copy-maintenance.ts | 274 ++++-------------- .../game-folder/inspect-game-folder.ts | 10 +- .../game-folder/inspect-target-folder.ts | 21 +- .../src/main/services/install/copy-game.ts | 2 +- .../main/services/install/data-location.ts | 18 ++ .../src/main/services/install/decals.ts | 26 +- .../src/main/services/install/install-game.ts | 106 +++---- .../main/services/install/install-record.ts | 7 + .../src/main/services/install/stock-backup.ts | 41 ++- .../main/services/launch/launch-controller.ts | 144 +++++---- .../main/services/launch/ordinary-launch.ts | 27 +- .../src/main/workers/build-protocol.ts | 1 + .../launcher/src/main/workers/build-worker.ts | 19 +- .../src/renderer/src/i18n/locales/en.json | 15 +- .../src/renderer/src/i18n/locales/zh-CN.json | 15 +- .../src/pages/copies/CopyMaintenance.tsx | 118 ++++---- .../pages/copies/CopyMaintenanceControls.tsx | 110 +++++++ .../renderer/src/pages/install/DataStep.tsx | 16 +- .../renderer/src/pages/install/MethodStep.tsx | 9 +- .../renderer/src/pages/install/WizardMain.tsx | 3 + .../src/pages/install/useInstallWizard.ts | 36 ++- apps/launcher/src/shared/errors.ts | 3 +- apps/launcher/src/shared/ipc/contract.ts | 4 + apps/launcher/src/shared/schemas/install.ts | 12 +- .../src/shared/schemas/maintenance.ts | 13 +- packages/patcher/src/game-copy.ts | 6 +- 28 files changed, 813 insertions(+), 459 deletions(-) create mode 100644 apps/launcher/src/main/services/copies/copy-file-maintenance.ts create mode 100644 apps/launcher/src/main/services/install/data-location.ts create mode 100644 apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 0bd9029..31b2332 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -1,5 +1,5 @@ import { app, BrowserWindow, dialog, shell } from 'electron'; -import { patchFeatures, recordedGameVersions } from '@wto/patcher'; +import { isInSteamLibrary, patchFeatures, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdate } from '../services/app-update/app-update.ts'; import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; @@ -12,7 +12,7 @@ import { inspectGameFolder, requireFolder } from '../services/game-folder/inspec import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts'; import { cancelInstall, checkGameFolder, installGame, installationInProgress } from '../services/install/install-game.ts'; -import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts'; +import { canonicalCopyPath, createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts'; import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; @@ -64,6 +64,10 @@ export function registerIpcHandlers(): void { handle('install:prepareCopy', () => createCopyDraft()); handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path)); handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath)); + handle('install:inspectDataFolder', async ({ path }) => { + const resolved = await canonicalCopyPath(path); + return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) }; + }); handle('install:measureFolder', async ({ path, version }) => { await requireFolder(path); try { diff --git a/apps/launcher/src/main/services/copies/copy-file-maintenance.ts b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts new file mode 100644 index 0000000..10ad44c --- /dev/null +++ b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts @@ -0,0 +1,208 @@ +import type { BigIntStats } from 'node:fs'; +import { copyFile, lstat, mkdir } from 'node:fs/promises'; +import { dirname, join, normalize } from 'node:path'; +import { compareVersions, GAME_FILES } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts'; +import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts'; +import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; +import { sameVolume } from '../game-folder/inspect-target-folder.ts'; +import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts'; +import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts'; +import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; +import { checkPatches } from '../install/patch-check.ts'; +import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; +import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; + +export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void; + +export async function readSource(record: InstallRecord): Promise { + if (!record.sourcePath) return null; + try { + const game = await inspectGameFolder(record.sourcePath); + return game.missingFiles.length > 0 ? null : game; + } catch (error) { + if (error instanceof AppError) return null; + throw error; + } +} + +export function isNewer(source: GameFolderInspection | null, version: string | null): boolean { + return !!source?.version && !!version && compareVersions(source.version, version) > 0; +} + +export async function repair(record: InstallRecord, root: string, applying: () => void): Promise { + return changeCopyFiles(root, async (incoming) => { + const files = Object.values(GAME_FILES); + for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file)); + applying(); + return { replace: files, remove: [] }; + }, listCopies); +} + +export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise { + const game = await readSource(record); + if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update'); + + const dataPath = await canonicalCopyPath(record.dataPath); + const plan = await planCopy(game.path); + const inventory = plan.files.map((entry) => entry.relativePath); + const found = new Set(inventory.map(key)); + const linked = record.hardlinkedFiles ?? []; + const linkedPaths = new Set(linked.map(key)); + const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name))); + const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal); + for (const file of remove) await scopedInstallFile(dataPath, root, file); + + signal.throwIfAborted(); + const check = await checkPatches(game.path, record.dataPath); + signal.throwIfAborted(); + return changeCopyFiles(root, async (incoming) => { + report('copying', 0, copy.totalBytes); + let lastReport = 0; + await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { + if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) { + lastReport = Date.now(); + report('copying', doneBytes, copy.totalBytes); + } + }); + const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file)); + for (const file of Object.values(GAME_FILES)) { + signal.throwIfAborted(); + await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file)); + } + await verifySourceFiles(game.path, plan, signal); + signal.throwIfAborted(); + report('applying', copy.totalBytes, copy.totalBytes); + return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove }; + }, () => updateCopyRecord(record.id, (latest) => ({ + ...latest, gameVersion: game.version, unavailablePatches: check.unavailable, + lastCheckedAt: new Date().toISOString(), sourceFiles: inventory, + ...(linked.length ? { hardlinkedFiles: [] } : {}), + }))); +} + +async function planChangedFiles( + source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet, signal: AbortSignal, +): Promise { + const changed: CopyPlan['files'][number][] = []; + for (const file of plan.files) { + signal.throwIfAborted(); + const target = await scopedInstallFile(dataPath, root, file.relativePath); + const old = await fileInfo(target); + if (linked.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) { + changed.push(file); + } else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) { + const [targetHash, sourceHash] = await Promise.all([ + fileHash(target, signal), fileHash(join(source, file.relativePath), signal), + ]); + if (targetHash !== sourceHash) changed.push(file); + } + } + return { + files: changed, + folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))], + totalBytes: changed.reduce((total, file) => total + file.bytes, 0), + }; +} + +async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSignal): Promise { + for (const file of plan.files) { + signal.throwIfAborted(); + const info = await fileInfo(join(source, file.relativePath)); + if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) { + throw new AppError('maintenance_source_changed'); + } + } +} + +export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise { + return record.method === 'copy' && source.version === record.gameVersion && + hasHardlinkEvidence(source.version) && await sameVolume(source.path, root); +} + +export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise { + const source = await readSource(record); + if (!source || !await convertibleCopy(record, source, root) || + (await inspectGameFolder(root)).version !== source.version) { + throw new AppError('hardlink_unavailable'); + } + + const plan = await planCopy(source.path); + const candidates = plan.files.flatMap(({ relativePath, bytes }) => { + const evidence = hardlinkResource(source.version, relativePath, bytes); + return evidence ? [{ relativePath, evidence }] : []; + }); + const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0); + const dataPath = await canonicalCopyPath(record.dataPath); + const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path])); + return changeCopyFiles(root, async (incoming) => { + const replacements: string[] = []; + const unchanged = new Map(); + let checked = 0; + let matches = 0; + let lastReport = 0; + report('checking', 0, total); + for (const { relativePath, evidence } of candidates) { + const target = await scopedInstallFile(dataPath, root, relativePath); + const original = join(source.path, relativePath); + const copyStamp = await verifyHardlinkResource(target, evidence, signal); + const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null; + if (copyStamp && sourceStamp) { + if (!sameResource(copyStamp, sourceStamp)) { + const staged = join(incoming, relativePath); + await mkdir(dirname(staged), { recursive: true }); + const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp); + unchanged.set(target, copyStamp); + unchanged.set(staged, stagedStamp); + replacements.push(relativePath); + } + linked.set(key(relativePath), relativePath); + matches += 1; + } + checked += evidence.bytes; + if (checked === total || Date.now() - lastReport >= 250) { + lastReport = Date.now(); + report('checking', checked, total); + } + } + if (!matches) throw new AppError('hardlink_no_match'); + + await verifyStagedLinks(record, source.version, unchanged, signal); + signal.throwIfAborted(); + report('applying', total, total); + return { replace: replacements, remove: [] }; + }, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] }))); +} + +async function verifyStagedLinks( + record: InstallRecord, version: string | null, unchanged: ReadonlyMap, signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + if ((await readSource(record))?.version !== version) throw new AppError('hardlink_file_changed'); + for (const [path, stamp] of unchanged) { + signal.throwIfAborted(); + if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); + } +} + +function key(path: string): string { + const name = normalize(path); + return process.platform === 'win32' ? name.toLowerCase() : name; +} + +async function scopedInstallFile(dataPath: string, root: string, name: string): Promise { + const target = await stagedPath(root, name); + if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) || + copyPathContains(dataPath, target)) { + throw new AppError('maintenance_location'); + } + return target; +} + +async function stageBackup(folder: string, file: string, target: string): Promise { + await mkdir(dirname(target), { recursive: true }); + const source = join(folder, file); + if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location'); + await copyFile(source, target); +} diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts index 1395821..bbacc5b 100644 --- a/apps/launcher/src/main/services/copies/copy-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -1,23 +1,19 @@ -import type { BigIntStats } from 'node:fs'; -import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises'; -import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path'; +import { readdir, rm } from 'node:fs/promises'; +import { isAbsolute, join, parse, relative } from 'node:path'; import { app } from 'electron'; -import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; +import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; -import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts'; +import type { Copies, InstallRecord } from '@shared/schemas/install.ts'; import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; -import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; -import { sameVolume } from '../game-folder/inspect-target-folder.ts'; -import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts'; -import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts'; import { installationInProgress } from '../install/install-game.ts'; -import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.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 { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.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; @@ -32,10 +28,15 @@ export function cancelMaintenance(): void { 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, }; } @@ -50,31 +51,14 @@ export async function maintainCopy( }; current = job; const signal = job.stop.signal; - const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => { + const report: Report = (phase, doneBytes = 0, totalBytes = 0) => { if (phase === 'applying') job.interruptible = false; publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes }); }; - report('checking'); try { - const record = await requireCopy(request.id); - const root = await checkedRoot(record); - if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); - signal.throwIfAborted(); - - switch (request.operation) { - case 'check': - return await recordCheck(record, record.stockBackupPath); - case 'repair': - return await repair(record, root, () => report('applying')); - case 'update': - return await updateFromSource(record, root, signal, report); - case 'compact': - return await compactCopy(record, root, signal, report); - case 'delete': - report('applying'); - return await remove(record, root, request.deleteData); - } + report('checking'); + return await performMaintenance(request, signal, report); } catch (error) { if (signal.aborted) throw new AppError('maintenance_cancelled'); if (error instanceof AppError) throw error; @@ -85,29 +69,51 @@ export async function maintainCopy( } } +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 readSource(record: InstallRecord): Promise { - if (!record.sourcePath) return null; - try { - const game = await inspectGameFolder(record.sourcePath); - return game.missingFiles.length > 0 ? null : game; - } catch (error) { - if (error instanceof AppError) return null; - throw error; - } -} - -function isNewer(source: GameFolderInspection | null, version: string | null): boolean { - return !!source?.version && !!version && compareVersions(source.version, version) > 0; -} - async function checkedRoot(record: InstallRecord): Promise { - const root = await safeFolder(record.copyPath); + 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) { @@ -117,14 +123,15 @@ async function checkedRoot(record: InstallRecord): Promise { return root; } -async function safeFolder(path: string): Promise { +async function safeFolder(path: string, steamAllowed = false): Promise { const root = await canonicalCopyPath(path); - if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) || + 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 ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location'); + if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location'); return root; } @@ -141,169 +148,12 @@ async function recordCheck(record: InstallRecord, folder: string): Promise void): Promise { - return changeCopyFiles(root, async (incoming) => { - const files = Object.values(GAME_FILES); - for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file)); - applying(); - return { replace: files, remove: [] }; - }, listCopies); -} - -type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void; - -async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise { - const game = await readSource(record); - if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update'); - - const dataPath = await canonicalCopyPath(record.dataPath); - const plan = await planCopy(game.path); - const inventory = plan.files.map((entry) => entry.relativePath); - const found = new Set(inventory.map(key)); - const linked = record.hardlinkedFiles ?? []; - const linkedPaths = new Set(linked.map(key)); - const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name))); - const changed: CopyPlan['files'][number][] = []; - for (const file of plan.files) { - signal.throwIfAborted(); - const target = await scopedInstallFile(dataPath, root, file.relativePath); - const old = await fileInfo(target); - if (linkedPaths.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) { - changed.push(file); - } else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) { - const [targetHash, sourceHash] = await Promise.all([ - fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal), - ]); - if (targetHash !== sourceHash) changed.push(file); - } - } - for (const file of remove) await scopedInstallFile(dataPath, root, file); - - signal.throwIfAborted(); - const check = await checkPatches(game.path, record.dataPath); - signal.throwIfAborted(); - const copy: CopyPlan = { - files: changed, - folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))], - totalBytes: changed.reduce((total, file) => total + file.bytes, 0), - }; - return changeCopyFiles(root, async (incoming) => { - report('copying', 0, copy.totalBytes); - let lastReport = 0; - await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { - if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) { - lastReport = Date.now(); - report('copying', doneBytes, copy.totalBytes); - } - }); - const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file)); - for (const file of Object.values(GAME_FILES)) { - signal.throwIfAborted(); - await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file)); - } - for (const file of plan.files) { - signal.throwIfAborted(); - const info = await fileInfo(join(game.path, file.relativePath)); - if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) { - throw new AppError('maintenance_source_changed'); - } - } - signal.throwIfAborted(); - report('applying', copy.totalBytes, copy.totalBytes); - return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove }; - }, () => updateCopyRecord(record.id, (latest) => ({ - ...latest, gameVersion: game.version, unavailablePatches: check.unavailable, - lastCheckedAt: new Date().toISOString(), sourceFiles: inventory, - ...(linked.length ? { hardlinkedFiles: [] } : {}), - }))); -} - -function key(path: string): string { - const name = normalize(path); - return process.platform === 'win32' ? name.toLowerCase() : name; -} - -async function scopedInstallFile(dataPath: string, root: string, name: string): Promise { - const target = await stagedPath(root, name); - if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) || - copyPathContains(dataPath, target)) { - throw new AppError('maintenance_location'); - } - return target; -} - -async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise { - return record.method === 'copy' && source.version === record.gameVersion && - hasHardlinkEvidence(source.version) && await sameVolume(source.path, root); -} - -async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise { - const source = await readSource(record); - if (!source || !await convertibleCopy(record, source, root) || - (await inspectGameFolder(root)).version !== source.version) { - throw new AppError('hardlink_unavailable'); - } - - const plan = await planCopy(source.path); - const candidates = plan.files.flatMap(({ relativePath, bytes }) => { - const evidence = hardlinkResource(source.version, relativePath, bytes); - return evidence ? [{ relativePath, evidence }] : []; - }); - const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0); - const dataPath = await canonicalCopyPath(record.dataPath); - const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path])); - return changeCopyFiles(root, async (incoming) => { - const replacements: string[] = []; - const unchanged = new Map(); - let checked = 0; - let matches = 0; - let lastReport = 0; - report('checking', 0, total); - for (const { relativePath, evidence } of candidates) { - const target = await scopedInstallFile(dataPath, root, relativePath); - const original = join(source.path, relativePath); - const copyStamp = await verifyHardlinkResource(target, evidence, signal); - const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null; - if (copyStamp && sourceStamp) { - if (!sameResource(copyStamp, sourceStamp)) { - const staged = join(incoming, relativePath); - await mkdir(dirname(staged), { recursive: true }); - const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp); - unchanged.set(target, copyStamp); - unchanged.set(staged, stagedStamp); - replacements.push(relativePath); - } - linked.set(key(relativePath), relativePath); - matches += 1; - } - checked += evidence.bytes; - if (checked === total || Date.now() - lastReport >= 250) { - lastReport = Date.now(); - report('checking', checked, total); - } - } - if (!matches) throw new AppError('hardlink_no_match'); - - signal.throwIfAborted(); - if ((await readSource(record))?.version !== source.version) throw new AppError('hardlink_file_changed'); - for (const [path, stamp] of unchanged) { - signal.throwIfAborted(); - if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); - } - signal.throwIfAborted(); - report('applying', total, total); - return { replace: replacements, remove: [] }; - }, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] }))); -} - -async function stageBackup(folder: string, file: string, target: string): Promise { - await mkdir(dirname(target), { recursive: true }); - const source = join(folder, file); - if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location'); - await copyFile(source, target); -} - 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))) || diff --git a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts index 10e26f7..bd5efbe 100644 --- a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts +++ b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts @@ -1,4 +1,4 @@ -import { access, readFile, stat } from 'node:fs/promises'; +import { access, readFile, realpath, stat } from 'node:fs/promises'; import { join } from 'node:path'; import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; @@ -11,18 +11,20 @@ import { resourcePaths } from '../resources/resource-paths.ts'; */ export async function inspectGameFolder(path: string): Promise { await requireFolder(path); + const resolved = await realpath(path); const required = Object.values(GAME_FILES); const missingFiles: string[] = []; for (const file of required) { - if (!(await exists(join(path, file)))) missingFiles.push(file); + if (!(await exists(join(resolved, file)))) missingFiles.push(file); } const resources = resourcePaths(); return { path, + resolvedPath: resolved, missingFiles, - version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(path, GAME_FILES.executable)), + version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(resolved, GAME_FILES.executable)), verifiedVersions: recordedGameVersions(resources.patches), - inSteamLibrary: isInSteamLibrary(path), + inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved), }; } diff --git a/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts index 42a4a30..e0ea008 100644 --- a/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts +++ b/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts @@ -1,19 +1,20 @@ -import { readdir, realpath, stat, statfs } from 'node:fs/promises'; +import { readdir, stat, statfs } from 'node:fs/promises'; import { dirname, relative, resolve, isAbsolute } from 'node:path'; import { isInSteamLibrary } from '@wto/patcher'; import type { TargetFolderInspection } from '@shared/schemas/install.ts'; +import { canonicalCopyPath } from '../install/install-record.ts'; /** * Look at the folder the player chose for the game copy (install by copying): it must be new or * empty, must not overlap the stock installation, and the drive must have room. Only reads. */ export async function inspectTargetFolder(path: string, stockPath: string): Promise { - const target = await canonical(path); - const stock = await canonical(stockPath); + const [target, stock] = await Promise.all([canonicalCopyPath(path), canonicalCopyPath(stockPath)]); return { path, + resolvedPath: target, problem: await targetProblem(target, stock), - inSteamLibrary: isInSteamLibrary(target), + inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(target), freeBytes: await freeBytes(target), sameDriveAsStock: await sameVolume(target, stock), }; @@ -65,15 +66,3 @@ export async function freeBytes(path: string): Promise { } } } - -/** The real path of the nearest existing part, with the rest appended as given. */ -async function canonical(path: string): Promise { - const absolute = resolve(path); - try { - return await realpath(absolute); - } catch { - const parent = dirname(absolute); - if (parent === absolute) return absolute; - return resolve(await canonical(parent), relative(parent, absolute)); - } -} diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts index 12c0c4a..588f45a 100644 --- a/apps/launcher/src/main/services/install/copy-game.ts +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -17,7 +17,7 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts'; * own missions. The offline copy does not take the online game's data (working rules 18); the * game creates these folders again when it needs them. */ -const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']); +export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']); interface CopyEntry { readonly relativePath: string; diff --git a/apps/launcher/src/main/services/install/data-location.ts b/apps/launcher/src/main/services/install/data-location.ts new file mode 100644 index 0000000..b4a00d1 --- /dev/null +++ b/apps/launcher/src/main/services/install/data-location.ts @@ -0,0 +1,18 @@ +import { readdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { AppError } from '@shared/errors.ts'; + +/** A data tree must keep the server's saves, logs and caches inside the selected folder. */ +export async function requireUnredirectedData(root: string): Promise { + const folders = [root]; + for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) { + const entries = await readdir(folder, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => { + if (folder === root && error.code === 'ENOENT') return []; + throw error; + }); + for (const entry of entries) { + if (entry.isSymbolicLink()) throw new AppError('launch_location'); + if (entry.isDirectory()) folders.push(join(folder, entry.name)); + } + } +} diff --git a/apps/launcher/src/main/services/install/decals.ts b/apps/launcher/src/main/services/install/decals.ts index c383d80..e312c29 100644 --- a/apps/launcher/src/main/services/install/decals.ts +++ b/apps/launcher/src/main/services/install/decals.ts @@ -4,7 +4,7 @@ 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, updateCopyRecord } from './install-record.ts'; +import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts'; const CACHE_FOLDER = 'decal-cache'; let changing = false; @@ -17,11 +17,12 @@ export function decalCachePath(dataPath: string, cacheId: string): string { return join(dataPath, CACHE_FOLDER, cacheId); } -async function cacheRoot(dataPath: string): Promise { +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) || relative(root, await canonicalCopyPath(root)) !== '') { + if ((isInSteamLibrary(data) && (!steamDataConfirmed || relative(dataPath, data) !== '')) || + relative(root, await canonicalCopyPath(root)) !== '') { throw new AppError('decal_import_failed'); } return root; @@ -29,13 +30,13 @@ async function cacheRoot(dataPath: string): Promise { /** 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, + 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); + const root = await cacheRoot(dataPath, steamDataConfirmed); if (copyPathContains(source, root) || copyPathContains(root, source)) { throw new AppError('decal_source_invalid'); } @@ -58,16 +59,16 @@ export async function importDecalCache( if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid'); return id; } catch (error) { - await discardDecalCache(dataPath, id); + 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): Promise { +export async function discardDecalCache(dataPath: string, id: string, steamDataConfirmed = false): Promise { try { - const root = await cacheRoot(dataPath); + 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) === '') { @@ -84,7 +85,10 @@ export async function changeDecalSource(id: string, source: string | null): Prom try { const record = (await listCopies()).copies.find((copy) => copy.id === id); if (!record) throw new AppError('copy_not_found'); - const cacheId = source === null ? undefined : await importDecalCache(record.dataPath, source); + 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) => { @@ -92,10 +96,10 @@ export async function changeDecalSource(id: string, source: string | null): Prom return cacheId === undefined ? other : { ...other, decalCacheId: cacheId }; }); } catch (error) { - if (cacheId) await discardDecalCache(record.dataPath, cacheId); + if (cacheId) await discardDecalCache(dataPath, cacheId, dataInSteam); throw error; } - if (record.decalCacheId) await discardDecalCache(record.dataPath, record.decalCacheId); + if (record.decalCacheId) await discardDecalCache(dataPath, record.decalCacheId, dataInSteam); return copies; } finally { changing = false; diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index 3f1bcff..daf52c3 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -1,17 +1,18 @@ import type { BigIntStats } from 'node:fs'; import { access, mkdir } from 'node:fs/promises'; -import { join } from 'node:path'; +import { isAbsolute, join, relative } from 'node:path'; import { isInSteamLibrary } from '@wto/patcher'; 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 { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts'; import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts'; +import { requireUnredirectedData } from './data-location.ts'; import { discardDecalCache, importDecalCache } from './decals.ts'; import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts'; import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts'; import { checkPatches } from './patch-check.ts'; -import { backUpStockFiles, stockBackupPath } from './stock-backup.ts'; +import { backUpStockFiles, installStockSource, refreshStockBackup, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts'; /** * Install the offline version: check the patches against the player's game, @@ -55,55 +56,22 @@ export function cancelInstall(): boolean { 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); + const { resolvedPath, version } = await requireGameFolder(gameFolder); + const stock = await installStockSource(resolvedPath, version); + const data = await canonicalCopyPath(dataPath); + await requireUnredirectedData(data); + return checkPatches(stock.path, data); } 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; - await requireAvailableCopy(request.id, copyPath, request.dataPath); - - const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null; - if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem }); - const useHardLinks = request.method === 'copy' && request.useHardLinks === true; - if (useHardLinks) { - if (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version)) throw new AppError('hardlink_unavailable'); - if (copyPathContains(await canonicalCopyPath(gameFolder), await canonicalCopyPath(request.dataPath))) { - throw new AppError('target_not_usable', { problem: 'overlaps_stock' }); - } - } - const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary; - if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed'); - - if (request.decalSourcePath) { - const dataPath = await canonicalCopyPath(request.dataPath); - if (isInSteamLibrary(dataPath) || - (request.method === 'copy' && copyPathContains(await canonicalCopyPath(gameFolder), dataPath))) { - throw new AppError('decal_import_failed'); - } - } - + const { version, requestedCopyPath, copyPath, dataPath, sourcePath, target, useHardLinks, copyInSteam, dataInSteam } = + await inspectInstallation(request); 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 stock = await installStockSource(sourcePath, version); + await mkdir(dataPath, { recursive: true }); + const check = await checkPatches(stock.path, 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'); @@ -112,26 +80,29 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr let decalCacheId: string | undefined; if (request.decalSourcePath) { report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); - decalCacheId = await importDecalCache(request.dataPath, request.decalSourcePath, signal); + decalCacheId = await importDecalCache(dataPath, request.decalSourcePath, signal, dataInSteam); } try { const copied = request.method === 'copy' - ? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report) + ? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report) : undefined; report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); - const stockBackup = await backUpStockFiles(copyPath); + const stockBackup = request.method === 'in-place' && stock.refresh + ? await refreshStockBackup(copyPath) + : await backUpStockFiles(copyPath); report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const record: InstallRecord = { id: request.id, name: request.name, - sourcePath: request.method === 'copy' ? request.sourcePath : null, + sourcePath: request.method === 'copy' ? sourcePath : null, method: request.method, - copyPath, + copyPath: requestedCopyPath, dataPath: request.dataPath, + ...(copyInSteam || dataInSteam ? { steamLibraryConfirmation: { copyPath, dataPath } } : {}), stockBackupPath: stockBackup, - gameVersion: game.version, + gameVersion: version, unavailablePatches: check.unavailable, installedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(), @@ -141,11 +112,42 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr await writeInstallRecord(record); return record; } catch (error) { - if (decalCacheId) await discardDecalCache(request.dataPath, decalCacheId); + if (decalCacheId) await discardDecalCache(dataPath, decalCacheId, dataInSteam); throw error; } } +async function inspectInstallation(request: InstallRequest) { + const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath; + const game = await requireGameFolder(gameFolder); + const requestedCopyPath = request.method === 'copy' ? request.copyPath : request.gamePath; + const [copyPath, dataPath, sourcePath] = await Promise.all([ + canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder), + ]); + await requireAvailableCopy(request.id, copyPath, dataPath); + if (!isAbsolute(request.dataPath) || copyPathContains(stockBackupPath(copyPath), dataPath) || + (request.method === 'copy' && copyPathContains(sourcePath, dataPath))) { + throw new AppError('target_not_usable', { problem: 'overlaps_stock' }); + } + + const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null; + if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem }); + const useHardLinks = request.method === 'copy' && request.useHardLinks === true; + if (useHardLinks && (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version))) { + throw new AppError('hardlink_unavailable'); + } + const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath); + const dataInSteam = isInSteamLibrary(request.dataPath) || isInSteamLibrary(dataPath); + const { confirmedSteamCopyPath, confirmedSteamDataPath } = request; + const copyConfirmed = confirmedSteamCopyPath !== undefined && relative(copyPath, confirmedSteamCopyPath) === ''; + const dataConfirmed = confirmedSteamDataPath !== undefined && relative(dataPath, confirmedSteamDataPath) === ''; + if ((copyInSteam && !copyConfirmed) || (dataInSteam && !dataConfirmed)) { + throw new AppError('steam_library_not_confirmed'); + } + await Promise.all([requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]); + return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, target, useHardLinks, copyInSteam, dataInSteam }; +} + async function copyGame( source: string, target: string, diff --git a/apps/launcher/src/main/services/install/install-record.ts b/apps/launcher/src/main/services/install/install-record.ts index 9164dc2..2b93127 100644 --- a/apps/launcher/src/main/services/install/install-record.ts +++ b/apps/launcher/src/main/services/install/install-record.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import { realpath } from 'node:fs/promises'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { app } from 'electron'; +import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts'; import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; @@ -106,6 +107,12 @@ export function copyPathContains(parent: string, child: string): boolean { return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep); } +export function steamLibraryNeedsConfirmation(record: InstallRecord, copyPath: string, dataPath: string): boolean { + if (![record.copyPath, record.dataPath, copyPath, dataPath].some(isInSteamLibrary)) return false; + const confirmed = record.steamLibraryConfirmation; + return !confirmed || relative(confirmed.copyPath, copyPath) !== '' || relative(confirmed.dataPath, dataPath) !== ''; +} + function overlaps(left: string, right: string): boolean { return copyPathContains(left, right) || copyPathContains(right, left); } diff --git a/apps/launcher/src/main/services/install/stock-backup.ts b/apps/launcher/src/main/services/install/stock-backup.ts index d0aaf5d..234447a 100644 --- a/apps/launcher/src/main/services/install/stock-backup.ts +++ b/apps/launcher/src/main/services/install/stock-backup.ts @@ -1,7 +1,10 @@ import { constants } from 'node:fs'; -import { access, copyFile, mkdir } from 'node:fs/promises'; -import { dirname, join } from 'node:path'; -import { GAME_FILES } from '@wto/patcher'; +import { access, copyFile, mkdir, readFile } from 'node:fs/promises'; +import { dirname, join, relative } from 'node:path'; +import { executableVersion, GAME_FILES } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import { changeCopyFiles } from '../copies/change-copy-files.ts'; +import { canonicalCopyPath } from './install-record.ts'; /** * The stock files every build starts from, kept inside the game copy: the three data packs and @@ -15,12 +18,21 @@ export function stockBackupPath(copyFolder: string): string { return join(copyFolder, STOCK_BACKUP_FOLDER); } +export async function requireStockBackupLocation(copyFolder: string): Promise { + const backup = stockBackupPath(await canonicalCopyPath(copyFolder)); + for (const file of Object.values(GAME_FILES)) { + const path = join(backup, file); + if (relative(path, await canonicalCopyPath(path)) !== '') throw new AppError('launch_location'); + } + return backup; +} + /** * Copies each stock file from the copy into the backup folder, unless the backup already has it: * a backed-up file is never replaced, because the copy's own file may be a patched one by then. */ export async function backUpStockFiles(copyFolder: string): Promise { - const backup = stockBackupPath(copyFolder); + const backup = await requireStockBackupLocation(copyFolder); for (const file of Object.values(GAME_FILES)) { const kept = join(backup, file); if (await exists(kept)) continue; @@ -30,6 +42,27 @@ export async function backUpStockFiles(copyFolder: string): Promise { return backup; } +/** A new game version must pass the patch checks before replacing an existing stock backup. */ +export async function installStockSource(copyFolder: string, version: string | null) { + const backup = await requireStockBackupLocation(copyFolder); + if (!await exists(join(backup, GAME_FILES.executable))) return { path: copyFolder, refresh: await exists(backup) }; + const backedUpVersion = executableVersion(await readFile(join(backup, GAME_FILES.executable))); + return version !== null && backedUpVersion !== version ? { path: copyFolder, refresh: true } : { path: backup, refresh: false }; +} + +export async function refreshStockBackup(copyFolder: string): Promise { + const backup = await requireStockBackupLocation(copyFolder); + return await changeCopyFiles(copyFolder, async (incoming) => { + const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file)); + for (const file of Object.values(GAME_FILES)) { + const target = join(incoming, STOCK_BACKUP_FOLDER, file); + await mkdir(dirname(target), { recursive: true }); + await copyFile(join(copyFolder, file), target); + } + return { replace, remove: [] }; + }, async () => backup); +} + async function exists(path: string): Promise { try { await access(path); diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index 86f1ecc..ec5f7a0 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -5,15 +5,17 @@ import { app, BrowserWindow, shell } from 'electron'; import { AccountStore, LOOPBACK } from '@wto/server'; import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; +import type { InstallRecord } from '@shared/schemas/install.ts'; import type { GameExit, LaunchState } from '@shared/schemas/launch.ts'; +import type { Settings } from '@shared/schemas/settings.ts'; import { getSettings } from '../config/settings-store.ts'; import { decalCachePath } from '../install/decals.ts'; -import { copyPathContains, readInstallRecord } from '../install/install-record.ts'; +import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; import { saveBackup } from '../saves/save-archive.ts'; import { buildCopy } from './build-copy.ts'; import { gameProcessRunning } from './game-process.ts'; -import { readInstalledLab, runLab } from './lab-handoff.ts'; +import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts'; import { localServerStatusUrl } from './local-server.ts'; import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts'; @@ -104,61 +106,10 @@ async function launch(job: LaunchJob): Promise { const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); if (!record) throw new AppError('launch_no_copy'); job.copyId = record.id; - const useLab = !app.isPackaged && settings.developerMode; - if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam'); - const currentVersion = await readVersion(record.copyPath, signal); - if (!currentVersion || currentVersion !== record.gameVersion) { - update(job, { phase: 'version-changed', actualVersion: currentVersion }); - return; - } - - const lab = useLab ? await readInstalledLab() : null; - const { copyPath, stockPath, dataPath } = lab ? { - copyPath: lab.copyPath, - stockPath: settings.labStockPath ?? record.stockBackupPath, - dataPath: settings.labDataPath ?? record.dataPath, - } : await ordinaryLaunchPaths(record); - if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { - throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); - } - if (isInSteamLibrary(dataPath) || copyPathContains(stockPath, dataPath)) { - throw new AppError('launch_copy_in_steam'); - } - const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0); - if (requestedPort) update(job, { phase: 'checking', port: requestedPort }); - const [copyVersion, stockVersion, games] = await Promise.all([ - lab ? readVersion(copyPath, signal) : currentVersion, - readVersion(stockPath, signal), - gameProcessRunning(signal), - ]); - signal.throwIfAborted(); - if (!copyVersion || copyVersion !== stockVersion) { - throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); - } - if (games) throw new AppError('launch_game_running'); - const port = await selectPort(requestedPort); - if (settings.autoSaveBackups) { - for (const { userId } of new AccountStore(dataPath).all()) { - signal.throwIfAborted(); - await saveBackup({ ...record, dataPath }, userId, 'launch'); - } - } - signal.throwIfAborted(); - update(job, { phase: 'building', port }); - await buildCopy({ - kind: 'build', - stockPath, - copyPath, - dataPath, - port, - ...resourcePaths(), - ...(record.decalCacheId ? { decalCache: decalCachePath(record.dataPath, record.decalCacheId) } : {}), - acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), - }, signal, (filesWritten, filesTotal, file) => { - if (!signal.aborted) update(job, { - phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), - }); - }); + const plan = await planLaunch(job, record, settings); + if (plan === null) return; + const { lab, copyPath, stockPath, dataPath, port } = plan; + await buildForLaunch(job, record, plan, settings.autoSaveBackups); const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => { if (signal.aborted) return; @@ -176,6 +127,85 @@ async function launch(job: LaunchJob): Promise { update(job, { phase: 'game-exited', gameExit }); } +interface LaunchPlan { + readonly lab: Lab | null; + readonly copyPath: string; + readonly stockPath: string; + readonly dataPath: string; + readonly steamLibraryConfirmed: boolean; + readonly port: number; +} + +async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise { + const signal = job.stop.signal; + const useLab = !app.isPackaged && settings.developerMode; + if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) { + throw new AppError('launch_copy_in_steam'); + } + const currentVersion = await readVersion(record.copyPath, signal); + if (!currentVersion || currentVersion !== record.gameVersion) { + update(job, { phase: 'version-changed', actualVersion: currentVersion }); + return null; + } + + const lab = useLab ? await readInstalledLab() : null; + const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? { + copyPath: lab.copyPath, + stockPath: settings.labStockPath ?? record.stockBackupPath, + dataPath: settings.labDataPath ?? record.dataPath, + steamLibraryConfirmed: false, + } : await ordinaryLaunchPaths(record); + if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { + throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); + } + if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) { + throw new AppError('launch_copy_in_steam'); + } + if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location'); + const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0); + if (requestedPort) update(job, { phase: 'checking', port: requestedPort }); + const [copyVersion, stockVersion, games] = await Promise.all([ + lab ? readVersion(copyPath, signal) : currentVersion, + readVersion(stockPath, signal), + gameProcessRunning(signal), + ]); + signal.throwIfAborted(); + if (!copyVersion || copyVersion !== stockVersion) { + throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); + } + if (games) throw new AppError('launch_game_running'); + const port = await selectPort(requestedPort); + return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port }; +} + +async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise { + const signal = job.stop.signal; + const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan; + if (autoSaveBackups) { + for (const { userId } of new AccountStore(dataPath).all()) { + signal.throwIfAborted(); + await saveBackup({ ...record, dataPath }, userId, 'launch'); + } + } + signal.throwIfAborted(); + update(job, { phase: 'building', port }); + await buildCopy({ + kind: 'build', + stockPath, + copyPath, + dataPath, + port, + steamLibraryConfirmed, + ...resourcePaths(), + ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), + acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), + }, signal, (filesWritten, filesTotal, file) => { + if (!signal.aborted) update(job, { + phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), + }); + }); +} + async function readVersion(folder: string, signal: AbortSignal): Promise { try { return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal })); diff --git a/apps/launcher/src/main/services/launch/ordinary-launch.ts b/apps/launcher/src/main/services/launch/ordinary-launch.ts index 1d4ebe3..32b9f13 100644 --- a/apps/launcher/src/main/services/launch/ordinary-launch.ts +++ b/apps/launcher/src/main/services/launch/ordinary-launch.ts @@ -6,8 +6,10 @@ import { parseLaunchArguments } from '@shared/launch-arguments.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; import type { GameExit } from '@shared/schemas/launch.ts'; import type { Settings } from '@shared/schemas/settings.ts'; -import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; -import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; +import { requireUnredirectedData } from '../install/data-location.ts'; +import { PLAYER_DATA_FOLDERS } from '../install/copy-game.ts'; +import { canonicalCopyPath, copyPathContains, steamLibraryNeedsConfirmation } from '../install/install-record.ts'; +import { requireStockBackupLocation, stockBackupPath } from '../install/stock-backup.ts'; import { runGameProcess } from './game-process.ts'; import { startLocalServer } from './local-server.ts'; @@ -17,16 +19,25 @@ export async function ordinaryLaunchPaths(record: InstallRecord) { const [copyPath, stockPath, dataPath] = await Promise.all([ canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath), ]); - const executable = await canonicalCopyPath(join(copyPath, GAME_FILES.executable)); - const source = record.sourcePath; - if (relative(copyPath, stockPath).toLowerCase() !== STOCK_BACKUP_FOLDER.toLowerCase() || - relative(copyPath, executable).toLowerCase() !== GAME_FILES.executable.toLowerCase() || + const source = record.sourcePath === null ? null : await canonicalCopyPath(record.sourcePath); + if (relative(stockBackupPath(copyPath), stockPath) !== '' || copyPathContains(stockPath, dataPath) || (source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) { throw new AppError('launch_location'); } - if (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath)) throw new AppError('launch_copy_in_steam'); - return { copyPath: copyPath, stockPath: stockPath, dataPath: dataPath }; + await Promise.all([requireUnredirectedGamePaths(copyPath), requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]); + if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required'); + return { copyPath, stockPath, dataPath, steamLibraryConfirmed: isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath) }; +} + +/** The game and build write to these copy-relative locations. */ +async function requireUnredirectedGamePaths(copyPath: string): Promise { + const paths = ['config.blk', join('cache', 'content'), ...PLAYER_DATA_FOLDERS, ...Object.values(GAME_FILES)]; + const checks = await Promise.all(paths.map(async (name) => { + const intended = join(copyPath, name); + return relative(intended, await canonicalCopyPath(intended)) === ''; + })); + if (checks.includes(false)) throw new AppError('launch_location'); } type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running'; diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index 592e203..ecd1ed9 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -5,6 +5,7 @@ export interface BuildRequest { readonly stockPath: string; readonly copyPath: string; readonly dataPath: string; + readonly steamLibraryConfirmed: boolean; readonly port: number; readonly patches: string; readonly networkHookLibrary: string; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index 44896b5..26b63c7 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -5,7 +5,16 @@ import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCac import { multiVehiclePackIds } from '@wto/server'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; -let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[]; readonly decalCache: string | undefined } | null = null; +let prepared: { + readonly request: BuildRequest; + readonly files: readonly GameCopyFile[]; + readonly decalCache: string | undefined; +} | null = null; + +function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void { + if (relative(copyPath, realpathSync(copyPath)) !== '') throw new Error('The copy path changed during the build.'); + assertWritableCopy(stockPath, copyPath, { steamLibraryConfirmed }); +} function send(reply: BuildReply): void { process.parentPort.postMessage(reply); @@ -23,7 +32,7 @@ function importedDecals(path: string | undefined): string | undefined { } function build(request: BuildRequest): void { - assertWritableCopy(request.stockPath, request.copyPath); + checkBuildLocation(request); const decalCache = importedDecals(request.decalCache); const result = buildGameCopy({ stock: readStockGameFiles(request.stockPath), @@ -40,7 +49,7 @@ function build(request: BuildRequest): void { send({ kind: 'failed', error: 'launch_build_unavailable' }); return; } - prepared = { copyPath: request.copyPath, files: result.files, decalCache }; + prepared = { request, files: result.files, decalCache }; send({ kind: 'prepared', total: prepared.files.length }); } @@ -52,8 +61,10 @@ process.parentPort.on('message', (event: MessageEvent) => { return; } if (!prepared) throw new Error('No build is ready to write.'); - const { copyPath, files, decalCache } = prepared; + const { request, files, decalCache } = prepared; prepared = null; + checkBuildLocation(request); + const { copyPath } = request; if (decalCache) copyPlayerDecalCache(decalCache, copyPath); for (const [index, file] of files.entries()) { writeGameCopy(copyPath, [file]); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index c233515..0d7f1bf 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -159,7 +159,10 @@ "steam": { "inPlaceWarning": "Launching offline will modify the game files in this Steam installation. Steam updates or file verification may overwrite the changes. Launching the official game online with modified files may result in an account ban.", "copyWarning": "The destination is in a Steam library. Choose a folder outside the library to keep the offline copy separate.", - "confirm": "Confirm this folder" + "confirm": "Confirm this folder", + "dataWarning": "Steam may remove saves, caches, and logs stored under the game folder when uninstalling the game.", + "maintenanceWarning": "This copy or its data folder is in a Steam library. Offline play can change game files in the library. Steam can replace them during an update or file verification. Using modified files online may result in an account ban. Uninstalling the game through Steam may also remove any saves stored under its folder.", + "confirmLocations": "Confirm these locations" }, "data": { "body": "Select a folder for saves, caches, and logs.", @@ -220,6 +223,10 @@ "delete": "Delete copy", "deleteAction": "Delete…", "deleteHint": "The data folder is kept by default.", + "unlink": "Remove registration", + "unlinkAction": "Remove…", + "unlinkHint": "The launcher keeps the Steam game files and data folder in place.", + "unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", "deleteLocation": "Delete the game copy at {{path}}?", "deleteData": "Also delete the data folder at {{path}}", "confirm": "Confirm deletion", @@ -229,6 +236,7 @@ "applying": "Applying changes" }, "result": { + "confirm-steam": "Steam locations confirmed.", "check": "Patch check complete.", "repair": "Original files restored.", "update": "Copy updated.", @@ -654,7 +662,8 @@ "launch_lab_version": "The lab copy and the stock backup must use the same game version.", "launch_lab_failed": "The isolated launch failed. See the launcher log.", "launch_game_running": "Another game process is running.", - "launch_copy_in_steam": "The launch requires a separate copy and data folder outside Steam.", + "launch_copy_in_steam": "The development lab requires a copy and data folder outside Steam.", + "launch_steam_confirmation_required": "Confirm the Steam locations in Copy Maintenance before launching.", "launch_location": "The game copy, stock backup, or data folder location is invalid.", "launch_stock_version": "The stock backup and game copy versions do not match.", "launch_build_failed": "The game files could not be generated.", @@ -667,7 +676,7 @@ "folder_unreadable": "The folder cannot be read: {{path}}", "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", "target_not_usable": "The selected folder cannot be used for installation.", - "steam_library_not_confirmed": "The installation folder is in a Steam library. Confirm the risk notice first.", + "steam_library_not_confirmed": "The copy or data folder is in a Steam library. Confirm the risk notice first.", "not_enough_space": "Not enough disk space: {{neededGb}} GB required, {{freeGb}} GB available.", "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index cad1d21..7fc1bc8 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -159,7 +159,10 @@ "steam": { "inPlaceWarning": "离线启动会修改此 Steam 安装中的游戏文件。Steam 更新或文件校验可能覆盖改动。使用修改后的文件联网启动正版可能导致账号封禁。", "copyWarning": "目标文件夹位于 Steam 游戏库。建议将副本放在游戏库之外。", - "confirm": "确认使用此文件夹" + "confirm": "确认使用此文件夹", + "dataWarning": "数据目录放在 Steam 游戏文件夹内时,在 Steam 中卸载游戏可能一并删除存档、缓存和日志。", + "maintenanceWarning": "副本或数据目录位于 Steam 游戏库中。离线启动可能修改库内的游戏文件。Steam 更新或校验可能覆盖改动,使用修改后的文件联网启动可能导致账号封禁。在 Steam 中卸载游戏还可能删除保存在该游戏文件夹内的存档。", + "confirmLocations": "确认使用这些位置" }, "data": { "body": "选择用于保存存档、缓存和日志的文件夹。", @@ -220,6 +223,10 @@ "delete": "删除副本", "deleteAction": "删除…", "deleteHint": "默认保留数据目录。", + "unlink": "解除登记", + "unlinkAction": "解除登记…", + "unlinkHint": "Steam 游戏文件和数据目录将留在原处。", + "unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", "deleteLocation": "确认删除 {{path}} 中的游戏副本?", "deleteData": "同时删除 {{path}} 中的数据", "confirm": "确认删除", @@ -229,6 +236,7 @@ "applying": "正在应用更改" }, "result": { + "confirm-steam": "已确认 Steam 目录。", "check": "补丁检查已完成。", "repair": "原版文件已还原。", "update": "副本已更新。", @@ -654,7 +662,8 @@ "launch_lab_version": "实验副本和原版文件备份必须使用同一游戏版本。", "launch_lab_failed": "隔离启动失败。请查看启动器日志。", "launch_game_running": "已有游戏进程在运行。", - "launch_copy_in_steam": "启动需使用 Steam 目录外的副本和数据目录。", + "launch_copy_in_steam": "隔离实验需使用 Steam 目录外的副本和数据目录。", + "launch_steam_confirmation_required": "请在副本维护中确认 Steam 目录后再启动。", "launch_location": "副本、原版文件备份或数据目录的位置无效。", "launch_stock_version": "原版文件备份的版本与副本不一致。", "launch_build_failed": "无法生成游戏文件。", @@ -667,7 +676,7 @@ "folder_unreadable": "无法读取文件夹:{{path}}", "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", "target_not_usable": "所选文件夹不能用于安装。", - "steam_library_not_confirmed": "安装位置位于 Steam 游戏库中,请先确认风险提示。", + "steam_library_not_confirmed": "副本或数据目录位于 Steam 游戏库中,请先确认风险提示。", "not_enough_space": "磁盘空间不足:需要 {{neededGb}} GB,仅剩 {{freeGb}} GB。", "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx index 0a370ba..bda67dc 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx @@ -1,12 +1,13 @@ import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import type { IpcInput } from '@shared/ipc/contract.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; import { ProgressBar } from '../../components/ProgressBar.tsx'; -import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; import { formatBytes } from '../../format.ts'; import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; +import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx'; interface CopyMaintenanceProps { readonly record: InstallRecord; @@ -14,14 +15,14 @@ interface CopyMaintenanceProps { } type Operation = MaintenanceRequest['operation']; +type OperationOptions = Pick, 'deleteData' | 'steamLocations'>; export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) { - const { t, i18n } = useTranslation(); + const { t } = useTranslation(); const [info, setInfo] = useState(null); const [working, setWorking] = useState(null); const [progress, setProgress] = useState(null); - const [confirming, setConfirming] = useState(false); - const [deleteData, setDeleteData] = useState(false); + const [removal, setRemoval] = useState(null); const [result, setResult] = useState(null); useEffect(() => { @@ -30,20 +31,20 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) { if (mounted) setInfo(value); }).catch(onError); return () => { mounted = false; }; - }, [record.id, record.gameVersion, onError]); + }, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]); useEffect(() => ipcOn('event:copy-maintenance', (event) => { if (event.id === record.id) setProgress(event); }), [record.id]); - const run = (operation: Operation): void => { + const run = (operation: Operation, options: OperationOptions = {}): void => { setResult(null); setWorking(operation); setProgress(null); - ipcInvoke('copies:maintain', { id: record.id, operation, deleteData: operation === 'delete' && deleteData }) + ipcInvoke('copies:maintain', { id: record.id, operation, ...options }) .then(() => { setResult(operation); - setConfirming(false); + setRemoval(null); }) .catch((error: unknown) => { if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled'); @@ -52,69 +53,54 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) { .finally(() => setWorking(null)); }; + const busy = working !== null; return ( - - - - - - - - - - - - - - - - {confirming && ( -
-

{t('copies.maintenance.deleteLocation', { path: record.copyPath })}

- -
- - -
-
- )} + run('confirm-steam', { steamLocations })} + /> + run('delete', { deleteData })} + /> {working && ( -
-

{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}

- - {progress?.totalBytes ?

{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}

: null} - {(working === 'update' || working === 'compact') && progress?.phase !== 'applying' && ( - - )} -
+ ipcInvoke('copies:cancelMaintenance').catch(onError)} + /> )} {result &&

{t(`copies.maintenance.result.${result}`)}

}
); } + +interface MaintenanceStatusProps { + readonly operation: Operation; + readonly progress: MaintenanceProgress | null; + readonly onCancel: () => void; +} + +function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) { + const { t } = useTranslation(); + return ( +
+

{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}

+ + {progress?.totalBytes ?

{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}

: null} + {(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && ( + + )} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx new file mode 100644 index 0000000..e57d18e --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx @@ -0,0 +1,110 @@ +import { useTranslation } from 'react-i18next'; +import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { MaintenanceInfo, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; +import { Notice } from '../../components/Notice.tsx'; +import { Row } from '../../components/Row.tsx'; + +interface CopyMaintenanceControlsProps { + readonly record: InstallRecord; + readonly info: MaintenanceInfo | null; + readonly busy: boolean; +} + +interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps { + readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void; + readonly onConfirmSteam: (locations: NonNullable) => void; +} + +export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) { + const { t, i18n } = useTranslation(); + const steam = info?.steamLocations; + return ( + <> + {info?.steamConfirmationRequired && steam && ( + +

{t('steam.maintenanceWarning')}

+

{steam.copyPath}
{steam.dataPath}

+ +
+ )} + + + + + + + + + + + + + + ); +} + +export interface CopyRemovalOptions { + readonly deleteData: boolean; +} + +interface CopyRemovalProps extends CopyMaintenanceControlsProps { + readonly options: CopyRemovalOptions | null; + readonly onOptionsChange: (options: CopyRemovalOptions | null) => void; + readonly onRemove: (deleteData: boolean) => void; +} + +export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) { + const { t } = useTranslation(); + const steam = info?.steamLocations; + const unlinkOnly = steam?.copyInSteam === true; + const canDeleteData = !unlinkOnly && !steam?.dataInSteam; + const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm'); + + return ( + <> + + + + {options && ( +
+

{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}

+ {canDeleteData && ( + + )} +
+ + +
+
+ )} + + ); +} diff --git a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx index d456e51..d5ee623 100644 --- a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx @@ -1,22 +1,36 @@ import { useTranslation } from 'react-i18next'; import { FolderField } from '../../components/FolderField.tsx'; +import { Notice } from '../../components/Notice.tsx'; import { Row } from '../../components/Row.tsx'; interface DataStepProps { readonly dataPath: string; readonly decalSource: string | null; + readonly steamDataPath: string | null; + readonly steamDataConfirmed: boolean; + readonly onSteamDataConfirmed: (confirmed: boolean) => void; readonly onDecalSource: (path: string | null) => void; readonly onDataPath: (path: string) => void; readonly onError: (error: unknown) => void; } /** Step 3: where saves, caches and logs of the offline version are kept. */ -export function DataStep({ dataPath, decalSource, onDataPath, onDecalSource, onError }: DataStepProps) { +export function DataStep({ dataPath, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) { const { t } = useTranslation(); return ( <>

{t('data.body')}

+ {steamDataPath && ( + +

{t('steam.dataWarning')}

+

{steamDataPath}

+ +
+ )} {decalSource && } diff --git a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx index df59b0b..e6b263a 100644 --- a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx @@ -34,8 +34,10 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me .then((target) => onChoice((current) => ({ ...current, target, steamConfirmed: false }))) .catch(onError); }; - const steamWarning = steamLibraryInvolved(source, choice) - ? onChoice({ ...choice, steamConfirmed })} /> + const folder = choice.method === 'in-place' ? source : choice.target; + const steamWarning = folder?.inSteamLibrary + ? onChoice({ ...choice, steamConfirmed })} /> : null; const targetPicker = ( <> @@ -120,11 +122,12 @@ function TargetVerdict({ target, sourceSize, method }: { : {t('method.room', { free: formatBytes(target.freeBytes) })}; } -function SteamWarning({ method, confirmed, onConfirmed }: { readonly method: Method; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) { +function SteamWarning({ method, path, confirmed, onConfirmed }: { readonly method: Method; readonly path: string; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) { const { t } = useTranslation(); return (

{t(method === 'in-place' ? 'steam.inPlaceWarning' : 'steam.copyWarning')}

+

{path}