Electron patches node:fs to treat any .asar file on disk as a virtual archive directory. When a player's War Thunder source directory contains an .asar file (for example from a leftover portable launcher folder previously unpacked inside the game folder), createReadStream fails with ENOENT and aborts full-copy installation. Changes: - Add rawFs() helper using Electron's original-fs (with node:fs fallback) and use it across copy-game.ts and change-copy-files.ts for directory scans, streaming copies, timestamp preservation, rollback and cleanup. - Preserve the first non-cancellation worker error in copyPlannedFiles so sibling AbortError rejections do not mask the real filesystem or hardlink error. - Skip nested subfolders containing WTOffline Launcher.exe during planCopy, and reject copy installation upfront with launcher_inside_source when the packaged launcher itself runs from inside the selected source game directory (with en and zh-CN messages). Verification: - Root and launcher typecheck passed. - Launcher electron-vite build passed. - en.json and zh-CN.json key parity check passed (720 keys). - Verified in Electron that patched node:fs reproduces ENOENT on default_app.asar while original-fs copies and cleans it up cleanly. - Packaged installer end-to-end verification pending.
307 lines
14 KiB
TypeScript
307 lines
14 KiB
TypeScript
import type { BigIntStats } from 'node:fs';
|
|
import { access, mkdir } from 'node:fs/promises';
|
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
|
import { app } from 'electron';
|
|
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
|
import { AppError } from '@shared/errors.ts';
|
|
import type { DataFolderProblem, 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 { statHardlinkResource } from './hardlink-files.ts';
|
|
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
|
import { checkPatches } from './patch-check.ts';
|
|
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
|
|
|
/**
|
|
* Install the offline version: check the patches against the player's game,
|
|
* copy it (method "copy"), keep its stock files in the copy's backup folder and record the
|
|
* installation. The patched files are written by the build at every launch, with that launch's
|
|
* port; installing writes no patched file.
|
|
*
|
|
* The patches are checked first, on the stock files the copy would get, so a game whose
|
|
* essential patches do not fit is refused before 90 GB are copied.
|
|
*/
|
|
|
|
/** Room kept free on the target drive beyond the copy itself, for the game's caches and logs. */
|
|
const SPARE_BYTES = 1024 ** 3;
|
|
/** At most this often a progress event goes to the window. */
|
|
const PROGRESS_INTERVAL_MS = 250;
|
|
|
|
let running: AbortController | null = null;
|
|
|
|
export function installationInProgress(): boolean {
|
|
return running !== null;
|
|
}
|
|
|
|
export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise<InstallRecord> {
|
|
if (running) throw new AppError('install_busy');
|
|
const controller = new AbortController();
|
|
running = controller;
|
|
try {
|
|
return await install(request, controller.signal, throttled(onProgress));
|
|
} catch (error) {
|
|
if (controller.signal.aborted) throw new AppError('install_cancelled');
|
|
throw error;
|
|
} finally {
|
|
running = null;
|
|
}
|
|
}
|
|
|
|
/** Stops a running copy at the next file; returns whether an installation was running. */
|
|
export function cancelInstall(): boolean {
|
|
if (!running) return false;
|
|
running.abort();
|
|
return true;
|
|
}
|
|
|
|
/** Which patches fit the game in `gameFolder`, for the window to show before installing. */
|
|
export async function checkGameFolder(gameFolder: string, dataPath: string, stockSourcePath?: string): Promise<PatchCheck> {
|
|
const game = await requireGameFolder(gameFolder);
|
|
const stock = stockSourcePath
|
|
? await resolveExternalStockSource(stockSourcePath, game.version)
|
|
: game.needsStockSource
|
|
? (() => { throw new AppError('stock_source_invalid'); })()
|
|
: await installStockSource(game.resolvedPath, game.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<InstallRecord> {
|
|
const { version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam } =
|
|
await inspectInstallation(request);
|
|
report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
|
const stock = externalStockPath
|
|
? { path: externalStockPath, refresh: false }
|
|
: 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');
|
|
signal.throwIfAborted();
|
|
|
|
let decalCacheId: string | undefined;
|
|
if (request.decalSourcePath) {
|
|
report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
|
decalCacheId = await importDecalCache(dataPath, request.decalSourcePath, signal, dataInSteam);
|
|
}
|
|
try {
|
|
const copied = request.method === 'copy'
|
|
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
|
|
: undefined;
|
|
|
|
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
|
const stockBackup = externalStockPath
|
|
? await refreshStockBackupFrom(copyPath, externalStockPath)
|
|
: (request.method === 'in-place' || request.method === 'existing') && 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' ? sourcePath : null,
|
|
method: request.method,
|
|
copyPath: requestedCopyPath,
|
|
dataPath: request.dataPath,
|
|
...(copyInSteam || dataInSteam ? { steamLibraryConfirmation: { copyPath, dataPath } } : {}),
|
|
stockBackupPath: stockBackup,
|
|
gameVersion: version,
|
|
unavailablePatches: check.unavailable,
|
|
installedAt: new Date().toISOString(),
|
|
lastCheckedAt: new Date().toISOString(),
|
|
...(decalCacheId ? { decalCacheId } : {}),
|
|
...copied,
|
|
};
|
|
await writeInstallRecord(record);
|
|
return record;
|
|
} catch (error) {
|
|
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);
|
|
let externalStockPath: string | null = null;
|
|
if (request.method === 'copy') {
|
|
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
|
} else if (request.stockSourcePath) {
|
|
externalStockPath = (await resolveExternalStockSource(request.stockSourcePath, game.version)).path;
|
|
} else if (game.needsStockSource) {
|
|
throw new AppError('stock_source_invalid');
|
|
}
|
|
const requestedCopyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
|
|
const [copyPath, dataPath, sourcePath] = await Promise.all([
|
|
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
|
|
]);
|
|
if (request.method === 'copy' && app.isPackaged) {
|
|
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
|
|
if (copyPathContains(sourcePath, launcherDir)) {
|
|
throw new AppError('launcher_inside_source');
|
|
}
|
|
}
|
|
await requireAvailableCopy(request.id, copyPath, dataPath);
|
|
const dataProblem = dataFolderProblem(
|
|
dataPath,
|
|
copyPath,
|
|
request.method === 'copy' ? sourcePath : null,
|
|
externalStockPath,
|
|
);
|
|
if (!isAbsolute(request.dataPath) || dataProblem !== null) {
|
|
throw new AppError('target_not_usable', { problem: dataProblem ?? '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) {
|
|
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, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
|
|
}
|
|
|
|
/**
|
|
* Validate where the offline data folder sits relative to the client and stock folders.
|
|
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
|
|
* client folder itself or an ancestor of it would mix game files into the data root.
|
|
*/
|
|
export function dataFolderProblem(
|
|
dataPath: string,
|
|
copyPath: string | null,
|
|
sourcePath: string | null,
|
|
externalStockPath: string | null,
|
|
): DataFolderProblem | null {
|
|
if (copyPath && (copyPathContains(dataPath, copyPath) ||
|
|
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
|
|
return 'overlaps_client';
|
|
}
|
|
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
|
|
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
|
|
return 'overlaps_stock';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
|
|
const stockGame = await requireGameFolder(stockSourcePath);
|
|
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
|
|
if (expectedVersion !== null && stockGame.version !== null && expectedVersion !== stockGame.version) {
|
|
throw new AppError('stock_source_version_mismatch', { expected: expectedVersion, actual: stockGame.version });
|
|
}
|
|
return installStockSource(stockGame.resolvedPath, stockGame.version);
|
|
}
|
|
|
|
async function copyGame(
|
|
source: string,
|
|
target: string,
|
|
initialFreeBytes: number | null,
|
|
useHardLinks: boolean,
|
|
sourceVersion: string | null,
|
|
signal: AbortSignal,
|
|
report: (progress: InstallProgress) => void,
|
|
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
|
|
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
|
const plan = await planCopy(source);
|
|
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
|
|
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
|
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
|
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
|
throw new AppError('hardlink_file_changed');
|
|
}
|
|
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
|
if (available !== null && available < neededBytes) {
|
|
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
|
}
|
|
const targetExisted = await exists(target);
|
|
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
|
|
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
|
|
try {
|
|
await copyPlannedFiles(source, target, plan, signal,
|
|
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
|
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
|
|
return {
|
|
sourceFiles: plan.files.map((file) => file.relativePath),
|
|
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
|
|
};
|
|
} catch (error) {
|
|
await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup));
|
|
if (signal.aborted) throw new AppError('install_cancelled');
|
|
if (error instanceof AppError) throw error;
|
|
console.error('[install] copying failed:', error);
|
|
throw new AppError('copy_failed');
|
|
}
|
|
}
|
|
|
|
async function prepareHardlinks(
|
|
source: string,
|
|
plan: CopyPlan,
|
|
signal: AbortSignal,
|
|
report: (progress: InstallProgress) => void,
|
|
): Promise<ReadonlyMap<string, BigIntStats>> {
|
|
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
|
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
|
const links = new Map<string, BigIntStats>();
|
|
let doneBytes = 0;
|
|
let doneFiles = 0;
|
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
|
for (const file of candidates) {
|
|
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
|
if (verified) links.set(file.relativePath, verified);
|
|
doneBytes += file.bytes;
|
|
doneFiles += 1;
|
|
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
|
}
|
|
if (!links.size) throw new AppError('hardlink_no_match');
|
|
return links;
|
|
}
|
|
|
|
async function requireGameFolder(path: string) {
|
|
const game = await inspectGameFolder(path);
|
|
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
|
return game;
|
|
}
|
|
|
|
/** Passes on the first and last report of each phase and at most one per interval in between. */
|
|
function throttled(onProgress: (progress: InstallProgress) => void): (progress: InstallProgress) => void {
|
|
let lastSent = 0;
|
|
let lastPhase = '';
|
|
return (progress) => {
|
|
const now = Date.now();
|
|
const finished = progress.totalFiles > 0 && progress.doneFiles === progress.totalFiles;
|
|
if (progress.phase !== lastPhase || finished || now - lastSent >= PROGRESS_INTERVAL_MS) {
|
|
lastSent = now;
|
|
lastPhase = progress.phase;
|
|
onProgress(progress);
|
|
}
|
|
};
|
|
}
|
|
|
|
function gigabytes(bytes: number): string {
|
|
return (bytes / 1024 ** 3).toFixed(1);
|
|
}
|
|
|
|
async function exists(path: string): Promise<boolean> {
|
|
try {
|
|
await access(path);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|