Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7bd17c4f74 | ||
|
|
be772c0cea | ||
|
|
fa7f68b942 | ||
|
|
899fb5d91b | ||
|
|
3f0e08c5b7 | ||
|
|
fb7d07f4f9 | ||
|
|
2d5e268083 | ||
|
|
66bbdf7192 | ||
|
|
bf2ce539e7 |
No files matched your search
@@ -0,0 +1,27 @@
|
||||
## 简体中文
|
||||
|
||||
`v0.1.2` 是 WTOffline 启动器的维护更新,重点放开「节省空间的复制」对游戏版本的硬锁定、修复维护页更新客户端时的路径校验误报,并内置 `2.61.0.58` 版本核对记录。
|
||||
|
||||
### 修复与改进
|
||||
|
||||
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
|
||||
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
|
||||
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
`v0.1.2` is a maintenance release of the WTOffline Launcher that makes space-saving copies resilient across minor game updates, fixes false path-scope errors during client updates, and bundles the `2.61.0.58` version check record.
|
||||
|
||||
### Fixes and improvements
|
||||
|
||||
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
|
||||
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
|
||||
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<a id="zh-cn"></a>
|
||||
|
||||
简体中文 · [English](#english)
|
||||
简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
|
||||
|
||||
------
|
||||
|
||||
@@ -21,6 +21,10 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
|
||||
|
||||
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
|
||||
|
||||
## 开发讨论、交流与求助
|
||||
|
||||
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
|
||||
|
||||
## 功能
|
||||
|
||||
| 领域 | 已实现 |
|
||||
@@ -151,7 +155,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
|
||||
## 开发
|
||||
|
||||
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn)。
|
||||
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
|
||||
|
||||
### 环境要求
|
||||
|
||||
@@ -265,7 +269,7 @@ tools/ wtotools,补丁检查工具(Python)
|
||||
|
||||
# WTOffline (English)
|
||||
|
||||
[简体中文](#zh-cn) · English
|
||||
[简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
|
||||
|
||||
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
|
||||
|
||||
@@ -282,6 +286,10 @@ The repository contains source code and patch definitions only. It does not cont
|
||||
|
||||
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
|
||||
|
||||
## Community
|
||||
|
||||
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
|
||||
|
||||
## Features
|
||||
|
||||
| Area | Implemented |
|
||||
@@ -412,7 +420,7 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
|
||||
|
||||
## Development
|
||||
|
||||
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist.
|
||||
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
|
||||
|
||||
### Requirements
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wto/launcher",
|
||||
"productName": "WTOffline Launcher",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"private": true,
|
||||
"description": "Installer and launcher of the War Thunder offline project.",
|
||||
"type": "module",
|
||||
|
||||
@@ -5,14 +5,14 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
|
||||
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
|
||||
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
|
||||
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
||||
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
|
||||
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
|
||||
import { relocateCopy } from '../services/copies/relocate-copy.ts';
|
||||
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
|
||||
import { measureFolder } from '../services/game-folder/folder-size.ts';
|
||||
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
|
||||
import { inspectPickedTargetFolder } 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 { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
|
||||
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, 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';
|
||||
@@ -66,14 +66,23 @@ export function registerIpcHandlers(): void {
|
||||
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
||||
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
|
||||
inspectPickedTargetFolder(path, stockPath, version ?? null));
|
||||
handle('install:inspectDataFolder', async ({ path }) => {
|
||||
const resolved = await canonicalCopyPath(path);
|
||||
return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) };
|
||||
handle('install:inspectDataFolder', async ({ path, copyPath, sourcePath, stockSourcePath }) => {
|
||||
const [resolved, resolvedCopy, resolvedSource, resolvedStock] = await Promise.all([
|
||||
canonicalCopyPath(path),
|
||||
copyPath ? canonicalCopyPath(copyPath) : Promise.resolve(null),
|
||||
sourcePath ? canonicalCopyPath(sourcePath) : Promise.resolve(null),
|
||||
stockSourcePath ? canonicalCopyPath(stockSourcePath) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
path: resolved,
|
||||
inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||
problem: dataFolderProblem(resolved, resolvedCopy, resolvedSource, resolvedStock),
|
||||
};
|
||||
});
|
||||
handle('install:measureFolder', async ({ path, version }) => {
|
||||
handle('install:measureFolder', async ({ path }) => {
|
||||
await requireFolder(path);
|
||||
try {
|
||||
return await measureFolder(path, version);
|
||||
return await measureFolder(path);
|
||||
} catch (error) {
|
||||
console.warn('[install] measuring the folder failed:', error);
|
||||
throw new AppError('folder_unreadable', { path });
|
||||
@@ -126,6 +135,7 @@ export function registerIpcHandlers(): void {
|
||||
return updated;
|
||||
});
|
||||
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
|
||||
handle('copies:maintenanceState', () => maintenanceState());
|
||||
handle('copies:maintain', async (request) => {
|
||||
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
|
||||
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
|
||||
|
||||
@@ -4,6 +4,7 @@ import { app } from 'electron';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
|
||||
|
||||
/**
|
||||
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
|
||||
@@ -47,6 +48,7 @@ export function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
||||
throw new AppError('settings_write_failed');
|
||||
}
|
||||
cached = merged;
|
||||
setLauncherLoggingEnabled(merged.loggingEnabled);
|
||||
return merged;
|
||||
});
|
||||
pending = operation.then(() => undefined, () => undefined);
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
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 { dirname, join, normalize, relative, sep } from 'node:path';
|
||||
import { compareVersions, GAME_FILES, isHardlinkableResource } 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 {
|
||||
fileHash,
|
||||
linkVerifiedResource,
|
||||
sameInode,
|
||||
sameResource,
|
||||
statFile,
|
||||
statHardlinkResource,
|
||||
verifyMatchingResource,
|
||||
} 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';
|
||||
@@ -40,6 +48,14 @@ export async function repair(record: InstallRecord, root: string, applying: () =
|
||||
}, listCopies);
|
||||
}
|
||||
|
||||
export async function updatePreservesSpaceSaving(
|
||||
record: InstallRecord,
|
||||
source: GameFolderInspection,
|
||||
root: string,
|
||||
): Promise<boolean> {
|
||||
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
|
||||
}
|
||||
|
||||
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const game = await readSource(record);
|
||||
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
|
||||
@@ -50,8 +66,11 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
||||
const found = new Set(inventory.map(key));
|
||||
const linked = record.hardlinkedFiles ?? [];
|
||||
const linkedPaths = new Set(linked.map(key));
|
||||
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
|
||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
||||
const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal);
|
||||
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
|
||||
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
|
||||
);
|
||||
for (const file of remove) await scopedInstallFile(dataPath, root, file);
|
||||
|
||||
signal.throwIfAborted();
|
||||
@@ -66,43 +85,86 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
||||
report('copying', doneBytes, copy.totalBytes);
|
||||
}
|
||||
});
|
||||
const stagedLinks = new Map<string, BigIntStats>();
|
||||
for (const [relativePath, sourceStamp] of linksToStage) {
|
||||
signal.throwIfAborted();
|
||||
const staged = join(incoming, relativePath);
|
||||
await mkdir(dirname(staged), { recursive: true });
|
||||
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
|
||||
stagedLinks.set(staged, linkedStamp);
|
||||
}
|
||||
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);
|
||||
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
|
||||
signal.throwIfAborted();
|
||||
report('applying', copy.totalBytes, copy.totalBytes);
|
||||
return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove };
|
||||
return {
|
||||
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
|
||||
remove,
|
||||
};
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({
|
||||
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||
...(linked.length ? { hardlinkedFiles: [] } : {}),
|
||||
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
||||
})));
|
||||
}
|
||||
|
||||
async function planChangedFiles(
|
||||
source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet<string>, signal: AbortSignal,
|
||||
): Promise<CopyPlan> {
|
||||
interface UpdateFilePlan {
|
||||
readonly copy: CopyPlan;
|
||||
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
|
||||
readonly hardlinkedFiles: string[];
|
||||
}
|
||||
|
||||
async function planUpdateFiles(
|
||||
source: string,
|
||||
root: string,
|
||||
dataPath: string,
|
||||
plan: CopyPlan,
|
||||
linked: ReadonlySet<string>,
|
||||
preserveHardlinks: boolean,
|
||||
signal: AbortSignal,
|
||||
): Promise<UpdateFilePlan> {
|
||||
const changed: CopyPlan['files'][number][] = [];
|
||||
const linksToStage = new Map<string, BigIntStats>();
|
||||
const hardlinkedFiles: string[] = [];
|
||||
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) {
|
||||
const sourceFile = join(source, file.relativePath);
|
||||
const old = await statFile(target);
|
||||
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
|
||||
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
|
||||
if (!sourceStamp) throw new AppError('maintenance_source_changed');
|
||||
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
|
||||
hardlinkedFiles.push(file.relativePath);
|
||||
continue;
|
||||
}
|
||||
const sourceStamp = await statFile(sourceFile);
|
||||
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
|
||||
throw new AppError('maintenance_source_changed');
|
||||
}
|
||||
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
|
||||
old.size !== BigInt(file.bytes)) {
|
||||
changed.push(file);
|
||||
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
|
||||
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
|
||||
const [targetHash, sourceHash] = await Promise.all([
|
||||
fileHash(target, signal), fileHash(join(source, file.relativePath), signal),
|
||||
fileHash(target, signal), fileHash(sourceFile, 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),
|
||||
copy: {
|
||||
files: changed,
|
||||
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
|
||||
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
|
||||
},
|
||||
linksToStage,
|
||||
hardlinkedFiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -117,8 +179,8 @@ async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSi
|
||||
}
|
||||
|
||||
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
|
||||
return record.method === 'copy' && source.version === record.gameVersion &&
|
||||
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
|
||||
return record.method === 'copy' && source.version !== null &&
|
||||
source.version === record.gameVersion && await canShareVolume(source.path, root);
|
||||
}
|
||||
|
||||
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
@@ -129,11 +191,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
||||
}
|
||||
|
||||
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 candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
|
||||
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
@@ -143,24 +202,24 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
||||
let matches = 0;
|
||||
let lastReport = 0;
|
||||
report('checking', 0, total);
|
||||
for (const { relativePath, evidence } of candidates) {
|
||||
for (const { relativePath, bytes } 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);
|
||||
}
|
||||
const match = await verifyMatchingResource(target, original, bytes, signal);
|
||||
if (match.status === 'already-linked') {
|
||||
linked.set(key(relativePath), relativePath);
|
||||
matches += 1;
|
||||
} else if (match.status === 'matched') {
|
||||
const staged = join(incoming, relativePath);
|
||||
await mkdir(dirname(staged), { recursive: true });
|
||||
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
|
||||
unchanged.set(target, match.copyStamp);
|
||||
unchanged.set(staged, stagedStamp);
|
||||
replacements.push(relativePath);
|
||||
linked.set(key(relativePath), relativePath);
|
||||
matches += 1;
|
||||
}
|
||||
checked += evidence.bytes;
|
||||
checked += bytes;
|
||||
if (checked === total || Date.now() - lastReport >= 250) {
|
||||
lastReport = Date.now();
|
||||
report('checking', checked, total);
|
||||
@@ -175,6 +234,10 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||
}
|
||||
|
||||
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
||||
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
|
||||
}
|
||||
|
||||
async function verifyStagedLinks(
|
||||
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
@@ -191,11 +254,32 @@ function key(path: string): string {
|
||||
return process.platform === 'win32' ? name.toLowerCase() : name;
|
||||
}
|
||||
|
||||
const OFFLINE_DATA_ENTRIES = new Set(['accounts.json', 'saves', 'tuning', 'logs', 'asset-pack', 'decals', 'cache']);
|
||||
|
||||
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||
console.warn('[copies] maintenance_location:', reason, details);
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
|
||||
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
|
||||
const target = await stagedPath(root, name);
|
||||
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
|
||||
copyPathContains(dataPath, target)) {
|
||||
throw new AppError('maintenance_location');
|
||||
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target)) {
|
||||
failLocation('target_inside_wtoffline', { root, target, name });
|
||||
}
|
||||
// Protect the data folder when it is nested inside the client folder. If an older installation
|
||||
// placed dataPath at an ancestor of the client folder, files inside the client folder do not
|
||||
// overlap data files stored at the ancestor root.
|
||||
if (copyPathContains(root, dataPath)) {
|
||||
if (relative(root, dataPath) !== '') {
|
||||
if (copyPathContains(dataPath, target)) {
|
||||
failLocation('target_inside_nested_data_folder', { root, dataPath, target, name });
|
||||
}
|
||||
} else {
|
||||
const topSegment = normalize(name).split(sep)[0]?.toLowerCase() ?? '';
|
||||
if (OFFLINE_DATA_ENTRIES.has(topSegment)) {
|
||||
failLocation('target_collides_with_data_entry', { root, dataPath, target, name });
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
@@ -203,6 +287,8 @@ async function scopedInstallFile(dataPath: string, root: string, name: string):
|
||||
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
const source = join(folder, file);
|
||||
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
|
||||
if (!(await fileInfo(source))?.isFile()) {
|
||||
failLocation('stock_backup_source_missing', { folder, file, source });
|
||||
}
|
||||
await copyFile(source, target);
|
||||
}
|
||||
@@ -13,14 +13,22 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
|
||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { fileInfo } from './change-copy-files.ts';
|
||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts';
|
||||
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||
|
||||
let current: { stop: AbortController; interruptible: boolean } | null = null;
|
||||
let current: {
|
||||
stop: AbortController;
|
||||
interruptible: boolean;
|
||||
progress: MaintenanceProgress;
|
||||
} | null = null;
|
||||
|
||||
export function maintenanceInProgress(): boolean {
|
||||
return current !== null;
|
||||
}
|
||||
|
||||
export function maintenanceState(): MaintenanceProgress | null {
|
||||
return current ? { ...current.progress } : null;
|
||||
}
|
||||
|
||||
export function cancelMaintenance(): void {
|
||||
if (current?.interruptible) current.stop.abort();
|
||||
}
|
||||
@@ -34,6 +42,7 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
return {
|
||||
sourceVersion: source?.version ?? null,
|
||||
updateAvailable: isNewer(source, record.gameVersion),
|
||||
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
|
||||
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
||||
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
|
||||
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
|
||||
@@ -42,18 +51,28 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
|
||||
export async function maintainCopy(
|
||||
request: MaintenanceRequest,
|
||||
publish: (progress: MaintenanceProgress) => void,
|
||||
publish: (progress: MaintenanceProgress | null) => void,
|
||||
): Promise<Copies> {
|
||||
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
||||
const initial: MaintenanceProgress = {
|
||||
id: request.id,
|
||||
operation: request.operation,
|
||||
phase: 'checking',
|
||||
doneBytes: 0,
|
||||
totalBytes: 0,
|
||||
};
|
||||
const job = {
|
||||
stop: new AbortController(),
|
||||
interruptible: request.operation === 'update' || request.operation === 'compact',
|
||||
progress: initial,
|
||||
};
|
||||
current = job;
|
||||
const signal = job.stop.signal;
|
||||
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
|
||||
if (phase === 'applying') job.interruptible = false;
|
||||
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
|
||||
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
|
||||
job.progress = next;
|
||||
publish(next);
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -66,6 +85,7 @@ export async function maintainCopy(
|
||||
throw new AppError('maintenance_failed');
|
||||
} finally {
|
||||
current = null;
|
||||
publish(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +106,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
||||
case 'confirm-steam':
|
||||
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
|
||||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
|
||||
throw new AppError('maintenance_location');
|
||||
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
|
||||
}
|
||||
if (!needsConfirmation) return listCopies();
|
||||
return updateCopyRecord(id, (copy) => ({
|
||||
@@ -112,13 +132,23 @@ async function requireCopy(id: string): Promise<InstallRecord> {
|
||||
return record;
|
||||
}
|
||||
|
||||
function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||
console.warn('[copies] maintenance_location:', reason, details);
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
|
||||
async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||
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');
|
||||
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
|
||||
if (relative(expectedBackup, backup) !== '') {
|
||||
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
|
||||
}
|
||||
if (record.sourcePath) {
|
||||
const source = await canonicalCopyPath(record.sourcePath);
|
||||
if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location');
|
||||
if (copyPathContains(source, root) || copyPathContains(root, source)) {
|
||||
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
@@ -126,12 +156,15 @@ async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
||||
const root = await canonicalCopyPath(path);
|
||||
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
|
||||
const appPath = await canonicalCopyPath(app.getAppPath());
|
||||
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
|
||||
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');
|
||||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
||||
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
||||
}
|
||||
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
||||
failLocation('folder_is_symlink', { path, root });
|
||||
}
|
||||
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
|
||||
return root;
|
||||
}
|
||||
|
||||
@@ -150,7 +183,7 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
|
||||
|
||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
||||
if (deleteData) throw new AppError('maintenance_location');
|
||||
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
|
||||
@@ -158,7 +191,7 @@ async function remove(record: InstallRecord, root: string, deleteData: boolean):
|
||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
||||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
||||
throw new AppError('maintenance_location');
|
||||
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
|
||||
}
|
||||
if (!deleteData && copyPathContains(root, data)) {
|
||||
await removeExcept(root, data);
|
||||
@@ -175,7 +208,7 @@ async function removeExcept(folder: string, kept: string): Promise<void> {
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (copyPathContains(path, kept)) {
|
||||
if (!entry.isDirectory()) throw new AppError('maintenance_location');
|
||||
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||
await removeExcept(path, kept);
|
||||
} else {
|
||||
await rm(path, { recursive: true, force: true });
|
||||
|
||||
@@ -61,7 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||
if (dataPath) await addServerLogs(files, dataPath);
|
||||
if (record) await addClientLogs(files, record);
|
||||
if (record) await addClientLogs(files, record, settings.loggingEnabled);
|
||||
|
||||
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
@@ -91,10 +91,11 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
|
||||
}
|
||||
|
||||
/**
|
||||
* Include the hook library log, the latest game .clog and a small metadata summary for the active
|
||||
* client so startup crashes can be diagnosed without touching player saves.
|
||||
* Include the hook library log, the latest game .clog and embedded browser log, and a small
|
||||
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
|
||||
* touching player saves.
|
||||
*/
|
||||
async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promise<void> {
|
||||
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
|
||||
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
|
||||
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
|
||||
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
|
||||
@@ -117,6 +118,9 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
|
||||
let latestClog: ListedFile | null = null;
|
||||
let latestClogIncluded = false;
|
||||
let latestClogOmittedReason: string | null = null;
|
||||
let latestBrowserLog: ListedFile | null = null;
|
||||
let latestBrowserLogIncluded = false;
|
||||
let latestBrowserLogOmittedReason: string | null = null;
|
||||
|
||||
const gameLogsDirStat = await safeStat(gameLogsFolder);
|
||||
if (gameLogsDirStat?.isDirectory()) {
|
||||
@@ -149,11 +153,28 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
|
||||
latestClogIncluded = added.included;
|
||||
latestClogOmittedReason = added.omittedReason;
|
||||
}
|
||||
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
|
||||
if (newestBrowserLog) {
|
||||
latestBrowserLog = {
|
||||
name: newestBrowserLog.name,
|
||||
size: newestBrowserLog.size,
|
||||
modifiedAt: newestBrowserLog.modifiedAt,
|
||||
};
|
||||
const added = await addBoundedClientFile(
|
||||
files,
|
||||
`client-logs/game-logs/${newestBrowserLog.name}`,
|
||||
join(gameLogsFolder, newestBrowserLog.name),
|
||||
newestBrowserLog.size,
|
||||
);
|
||||
latestBrowserLogIncluded = added.included;
|
||||
latestBrowserLogOmittedReason = added.omittedReason;
|
||||
}
|
||||
}
|
||||
|
||||
const summary = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
launcherVersion: app.getVersion(),
|
||||
loggingEnabled,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
osRelease: release(),
|
||||
@@ -180,6 +201,13 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
|
||||
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
|
||||
}
|
||||
: null,
|
||||
latestBrowserLog: latestBrowserLog
|
||||
? {
|
||||
...latestBrowserLog,
|
||||
included: latestBrowserLogIncluded,
|
||||
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Console } from 'node:console';
|
||||
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Writable } from 'node:stream';
|
||||
import { app } from 'electron';
|
||||
@@ -12,13 +12,26 @@ export const LAUNCHER_LOG_FILES = [
|
||||
'launcher.4.log',
|
||||
] as const;
|
||||
|
||||
let loggingEnabled = true;
|
||||
let activeLogPath: string | null = null;
|
||||
let fileFailed = false;
|
||||
let originalConsole = console;
|
||||
|
||||
export function launcherLogFolder(): string {
|
||||
return join(app.getPath('userData'), 'logs');
|
||||
}
|
||||
|
||||
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
||||
export function startLauncherLogging(): void {
|
||||
const originalConsole = console;
|
||||
function readInitialLoggingEnabled(): boolean {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown };
|
||||
return raw?.loggingEnabled !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureLogFileReady(): boolean {
|
||||
if (activeLogPath) return !fileFailed;
|
||||
const folder = launcherLogFolder();
|
||||
const active = join(folder, LAUNCHER_LOG_FILES[0]);
|
||||
try {
|
||||
@@ -28,17 +41,37 @@ export function startLauncherLogging(): void {
|
||||
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
|
||||
}
|
||||
writeFileSync(active, '', { flag: 'wx' });
|
||||
activeLogPath = active;
|
||||
fileFailed = false;
|
||||
return true;
|
||||
} catch (error) {
|
||||
fileFailed = true;
|
||||
originalConsole.error('[logs] opening the launcher log failed:', error);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Enable or disable writing launcher console output to launcher.log at runtime. */
|
||||
export function setLauncherLoggingEnabled(enabled: boolean): void {
|
||||
loggingEnabled = enabled;
|
||||
if (enabled && !activeLogPath && !fileFailed) {
|
||||
if (ensureLogFileReady()) {
|
||||
console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rotate after taking the single-instance lock and keep the original console destinations. */
|
||||
export function startLauncherLogging(): void {
|
||||
originalConsole = console;
|
||||
loggingEnabled = readInitialLoggingEnabled();
|
||||
if (loggingEnabled) ensureLogFileReady();
|
||||
|
||||
let fileFailed = false;
|
||||
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
|
||||
write(chunk: Buffer, _encoding, done) {
|
||||
if (!fileFailed) {
|
||||
if (loggingEnabled && activeLogPath && !fileFailed) {
|
||||
try {
|
||||
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
||||
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
|
||||
} catch (error) {
|
||||
fileFailed = true;
|
||||
originalConsole.error('[logs] writing the launcher log failed:', error);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { isHardlinkableResource } from '@wto/patcher';
|
||||
import type { FolderSize } from '@shared/schemas/install.ts';
|
||||
import { planCopy } from '../install/copy-game.ts';
|
||||
import { hardlinkResource } from '../install/hardlink-files.ts';
|
||||
|
||||
/** Estimate the installation size and the bytes eligible for content verification. */
|
||||
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
|
||||
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
|
||||
export async function measureFolder(root: string): Promise<FolderSize> {
|
||||
const plan = await planCopy(root);
|
||||
const linkableBytes = plan.files.reduce((total, file) =>
|
||||
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
|
||||
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
|
||||
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
|
||||
}
|
||||
@@ -18,6 +18,8 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||
* game creates these folders again when it needs them.
|
||||
*/
|
||||
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
|
||||
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
|
||||
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
|
||||
|
||||
interface CopyEntry {
|
||||
readonly relativePath: string;
|
||||
@@ -46,7 +48,7 @@ export async function planCopy(source: string): Promise<CopyPlan> {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
|
||||
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
|
||||
if (entry.isDirectory()) {
|
||||
folders.push(relative(source, path));
|
||||
pending.push(path);
|
||||
|
||||
@@ -2,30 +2,11 @@ import { createHash } from 'node:crypto';
|
||||
import { createReadStream, type BigIntStats } from 'node:fs';
|
||||
import { link, lstat } from 'node:fs/promises';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' };
|
||||
|
||||
interface ResourceEvidence {
|
||||
readonly bytes: number;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
const resources: Readonly<Record<string, ResourceEvidence>> = evidence.files;
|
||||
|
||||
export function hasHardlinkEvidence(version: string | null | undefined): boolean {
|
||||
return version === evidence.gameVersion;
|
||||
}
|
||||
|
||||
/** Only an exact path and size from the sampled build can be offered as a candidate. */
|
||||
export function hardlinkResource(
|
||||
version: string | null | undefined,
|
||||
relativePath: string,
|
||||
bytes: number,
|
||||
): ResourceEvidence | undefined {
|
||||
if (!hasHardlinkEvidence(version)) return undefined;
|
||||
const path = relativePath.replaceAll('\\', '/').toLowerCase();
|
||||
const resource = Object.hasOwn(resources, path) ? resources[path] : undefined;
|
||||
return resource?.bytes === bytes ? resource : undefined;
|
||||
}
|
||||
export type ResourceMatchResult =
|
||||
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||
| { readonly status: 'mismatch' };
|
||||
|
||||
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||
const hash = createHash('sha256');
|
||||
@@ -33,22 +14,56 @@ export async function fileHash(path: string, signal: AbortSignal): Promise<strin
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
/** Read the measured bytes and retain the observed file identity until the link is created. */
|
||||
export async function verifyHardlinkResource(
|
||||
path: string,
|
||||
resource: ResourceEvidence,
|
||||
signal: AbortSignal,
|
||||
): Promise<BigIntStats | null> {
|
||||
signal.throwIfAborted();
|
||||
const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
||||
export async function statFile(path: string): Promise<BigIntStats | null> {
|
||||
return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
});
|
||||
if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null;
|
||||
const checksum = await fileHash(path, signal);
|
||||
const after = await lstat(path, { bigint: true });
|
||||
if (!sameResource(before, after)) throw new AppError('hardlink_file_changed');
|
||||
return checksum === resource.sha256 ? after : null;
|
||||
}
|
||||
|
||||
/** Capture the file identity of a stock asset right before hardlinking it. */
|
||||
export async function statHardlinkResource(
|
||||
path: string,
|
||||
expectedBytes: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<BigIntStats | null> {
|
||||
signal.throwIfAborted();
|
||||
const stats = await statFile(path);
|
||||
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that an existing copy file and stock file have identical contents before replacing the
|
||||
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
|
||||
*/
|
||||
export async function verifyMatchingResource(
|
||||
copyPath: string,
|
||||
sourcePath: string,
|
||||
expectedBytes: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ResourceMatchResult> {
|
||||
signal.throwIfAborted();
|
||||
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||
const size = BigInt(expectedBytes);
|
||||
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
|
||||
return { status: 'mismatch' };
|
||||
}
|
||||
if (sameResource(copyBefore, sourceBefore)) {
|
||||
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
|
||||
}
|
||||
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
|
||||
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
|
||||
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
return copyHash === sourceHash
|
||||
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
|
||||
: { status: 'mismatch' };
|
||||
}
|
||||
|
||||
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
|
||||
}
|
||||
|
||||
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,18 @@
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { access, mkdir } from 'node:fs/promises';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.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 { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.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, stockBackupPath } from './stock-backup.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,
|
||||
@@ -90,7 +90,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
}
|
||||
try {
|
||||
const copied = request.method === 'copy'
|
||||
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report)
|
||||
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
|
||||
: undefined;
|
||||
|
||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
@@ -141,16 +141,20 @@ async function inspectInstallation(request: InstallRequest) {
|
||||
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)) ||
|
||||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
|
||||
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
|
||||
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 || !hasHardlinkEvidence(game.version))) {
|
||||
if (useHardLinks && !target?.sameDriveAsStock) {
|
||||
throw new AppError('hardlink_unavailable');
|
||||
}
|
||||
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
|
||||
@@ -165,6 +169,28 @@ async function inspectInstallation(request: InstallRequest) {
|
||||
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');
|
||||
@@ -178,16 +204,17 @@ async function copyGame(
|
||||
source: string,
|
||||
target: string,
|
||||
initialFreeBytes: number | null,
|
||||
hardlinkVersion: string | 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 = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, plan, signal, report) : undefined;
|
||||
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 !== hardlinkVersion)) {
|
||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
||||
@@ -200,7 +227,7 @@ async function copyGame(
|
||||
try {
|
||||
await copyPlannedFiles(source, target, plan, signal,
|
||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
||||
if (hardlinks && (await inspectGameFolder(source)).version !== hardlinkVersion) throw new AppError('hardlink_file_changed');
|
||||
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()] } : {}),
|
||||
@@ -214,26 +241,22 @@ async function copyGame(
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmHardlinks(
|
||||
async function prepareHardlinks(
|
||||
source: string,
|
||||
version: string,
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||
const candidates = plan.files.flatMap((file) => {
|
||||
const evidence = hardlinkResource(version, file.relativePath, file.bytes);
|
||||
return evidence ? [{ path: file.relativePath, evidence }] : [];
|
||||
});
|
||||
const totalBytes = candidates.reduce((total, file) => total + file.evidence.bytes, 0);
|
||||
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 { path, evidence } of candidates) {
|
||||
const verified = await verifyHardlinkResource(join(source, path), evidence, signal);
|
||||
if (verified) links.set(path, verified);
|
||||
doneBytes += evidence.bytes;
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
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);
|
||||
await buildForLaunch(job, record, plan, settings);
|
||||
|
||||
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
|
||||
if (signal.aborted) return;
|
||||
@@ -187,10 +187,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
||||
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
|
||||
}
|
||||
|
||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise<void> {
|
||||
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
|
||||
const signal = job.stop.signal;
|
||||
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
|
||||
if (autoSaveBackups) {
|
||||
if (settings.autoSaveBackups) {
|
||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||
signal.throwIfAborted();
|
||||
await saveBackup({ ...record, dataPath }, userId, 'launch');
|
||||
@@ -209,6 +209,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
||||
steamLibraryConfirmed,
|
||||
...resourcePaths(),
|
||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||
hookLogging: settings.loggingEnabled,
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
writtenFiles = filesWritten;
|
||||
|
||||
@@ -34,13 +34,17 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
|
||||
}
|
||||
|
||||
export async function startLocalServer(
|
||||
{ gameFolder, dataFolder, port }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
||||
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
||||
): Promise<LocalServer> {
|
||||
signal.throwIfAborted();
|
||||
const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], {
|
||||
serviceName: 'WTOffline local server',
|
||||
stdio: 'pipe',
|
||||
});
|
||||
const worker = utilityProcess.fork(
|
||||
join(import.meta.dirname, 'server-worker.js'),
|
||||
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
|
||||
{
|
||||
serviceName: 'WTOffline local server',
|
||||
stdio: 'pipe',
|
||||
},
|
||||
);
|
||||
forwardProcessOutput(worker.stdout, 'server', 'info');
|
||||
forwardProcessOutput(worker.stderr, 'server', 'error');
|
||||
|
||||
|
||||
@@ -49,7 +49,10 @@ export async function runOrdinaryLaunch(
|
||||
const args = parseLaunchArguments(settings.launchArguments);
|
||||
if (!args) throw new AppError('launch_game_failed');
|
||||
publish('starting-server');
|
||||
const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal);
|
||||
const server = await startLocalServer(
|
||||
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
|
||||
signal,
|
||||
);
|
||||
const stop = new AbortController();
|
||||
const runSignal = AbortSignal.any([signal, stop.signal]);
|
||||
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface BuildRequest {
|
||||
readonly patches: string;
|
||||
readonly networkHookLibrary: string;
|
||||
readonly decalCache?: string;
|
||||
readonly hookLogging: boolean;
|
||||
readonly acceptedUnavailable: readonly string[];
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ function build(request: BuildRequest): void {
|
||||
port: request.port,
|
||||
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
|
||||
placeholderDecals: decalCache === undefined,
|
||||
hookLogging: request.hookLogging,
|
||||
});
|
||||
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
|
||||
const accepted = new Set(request.acceptedUnavailable);
|
||||
|
||||
@@ -3,13 +3,14 @@ import { startServer } from '@wto/server';
|
||||
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
|
||||
|
||||
async function serve(): Promise<void> {
|
||||
const [gameFolder, dataFolder, portText] = process.argv.slice(2);
|
||||
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
|
||||
const port = Number(portText);
|
||||
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Invalid local server arguments.');
|
||||
}
|
||||
const server = await startServer({ gameFolder, dataFolder, port, report: console.info });
|
||||
console.info('Traffic log:', server.logFolder);
|
||||
const loggingEnabled = loggingFlag !== '0';
|
||||
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
|
||||
if (server.logFolder) console.info('Traffic log:', server.logFolder);
|
||||
process.parentPort.once('message', () => {
|
||||
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
|
||||
console.error('Could not close the local server:', error);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
|
||||
import { ipcInvoke, ipcOn } from './ipc.ts';
|
||||
import { AboutPage } from './pages/about/AboutPage.tsx';
|
||||
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
|
||||
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
|
||||
import { CopyList } from './pages/copies/CopyList.tsx';
|
||||
import { CopySummary } from './pages/copies/CopySummary.tsx';
|
||||
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
|
||||
@@ -68,6 +69,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
// The setting as the window opened: turning it on later does not check right away.
|
||||
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
|
||||
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
||||
const maintenance = useCopyMaintenance(report);
|
||||
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
||||
|
||||
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
|
||||
@@ -149,13 +151,26 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
bar: home,
|
||||
};
|
||||
case 'about':
|
||||
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} appUpdate={appUpdate} />, bar: home };
|
||||
return {
|
||||
side: homeSide,
|
||||
main: (
|
||||
<AboutPage
|
||||
launcherVersion={info.version}
|
||||
supportedVersions={supported}
|
||||
patchPack={patchPack}
|
||||
appUpdate={appUpdate}
|
||||
loggingEnabled={settings.loggingEnabled}
|
||||
onError={report}
|
||||
/>
|
||||
),
|
||||
bar: home,
|
||||
};
|
||||
case 'settings': {
|
||||
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
|
||||
const content = {
|
||||
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
|
||||
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
|
||||
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
||||
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
||||
dev: <DeveloperSettings settings={settings} onError={report} />,
|
||||
};
|
||||
return {
|
||||
@@ -210,7 +225,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
};
|
||||
}
|
||||
if (route.copies === 'maintain') {
|
||||
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home };
|
||||
return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
|
||||
}
|
||||
const main = route.copies === 'features'
|
||||
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
|
||||
|
||||
@@ -157,9 +157,9 @@
|
||||
"copy": "Copy installation (recommended)",
|
||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||
"spaceSaving": "Space-saving copy",
|
||||
"spaceSavingBody": "Shares verified large resources on the same volume. Estimated space required is {{size}}. A Steam update in place can change shared files in the client.",
|
||||
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.",
|
||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||
"spaceSavingUnavailable": "This installation has no large resources eligible for space-saving copying.",
|
||||
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
|
||||
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
||||
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
|
||||
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
|
||||
@@ -188,7 +188,11 @@
|
||||
},
|
||||
"data": {
|
||||
"body": "Select a folder for saves, caches, and logs.",
|
||||
"dialogTitle": "Select the data folder"
|
||||
"dialogTitle": "Select the data folder",
|
||||
"problem": {
|
||||
"overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).",
|
||||
"overlaps_stock": "The data folder cannot lie inside the online installation folder."
|
||||
}
|
||||
},
|
||||
"check": {
|
||||
"running": "Checking patches for the selected game version.",
|
||||
@@ -232,12 +236,13 @@
|
||||
"update": "Update from online installation",
|
||||
"updateAction": "Update client",
|
||||
"newVersion": "Version {{version}} is available from the installation source.",
|
||||
"updateDetaches": "Version {{version}} is available. Updating copies shared resources into independent files and requires additional space.",
|
||||
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
|
||||
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
|
||||
"currentVersion": "Installation source version {{version}}",
|
||||
"noSource": "Installation source unavailable",
|
||||
"spaceSaving": "Save space",
|
||||
"spaceSavingHint": "Share identical verified resources with the source. A Steam update in place can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a client and source installation of the same checked version on the same volume.",
|
||||
"spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.",
|
||||
"compactAction": "Convert",
|
||||
"check": "Recheck patches",
|
||||
"checkHint": "Check the original file backup.",
|
||||
@@ -524,11 +529,15 @@
|
||||
"reset": "Restore default"
|
||||
},
|
||||
"diagnostics": {
|
||||
"recordLogs": "Record runtime logs",
|
||||
"recordLogsToggle": "Write launcher, local server, and hook logs",
|
||||
"recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.",
|
||||
"loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.",
|
||||
"logs": "Logs",
|
||||
"logsHint": "Logs recorded by the launcher",
|
||||
"openLogs": "Open log folder",
|
||||
"export": "Export diagnostics",
|
||||
"exportHint": "Save logs, settings and the installation record to a ZIP file",
|
||||
"exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)",
|
||||
"save": "Export…",
|
||||
"saved": "Diagnostics saved to {{path}}.",
|
||||
"serverStatus": "Local server status",
|
||||
@@ -566,6 +575,12 @@
|
||||
"about": {
|
||||
"launcher": "Launcher {{version}}",
|
||||
"supported": "Supported game versions: {{versions}}",
|
||||
"feedback": {
|
||||
"title": "Feedback and logs",
|
||||
"export": "Save all logs",
|
||||
"exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).",
|
||||
"exportButton": "Save log ZIP…"
|
||||
},
|
||||
"pack": {
|
||||
"title": "Adaptation data",
|
||||
"current": "In use",
|
||||
@@ -623,7 +638,12 @@
|
||||
}
|
||||
},
|
||||
"statement": "Project information",
|
||||
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files."
|
||||
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.",
|
||||
"community": {
|
||||
"discord": "Discord",
|
||||
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
|
||||
"openDiscord": "Open Discord"
|
||||
}
|
||||
},
|
||||
"features": {
|
||||
"A-Offline startup": "Offline startup",
|
||||
@@ -726,8 +746,8 @@
|
||||
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
||||
"patch_check_failed": "An error occurred while checking patches.",
|
||||
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
||||
"hardlink_unavailable": "Space-saving copying requires a verified game version and a destination on the same volume.",
|
||||
"hardlink_no_match": "The files do not match the verified resources for space-saving copying.",
|
||||
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
|
||||
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
|
||||
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
||||
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
||||
"install_busy": "An installation is already in progress.",
|
||||
|
||||
@@ -157,9 +157,9 @@
|
||||
"copy": "复制安装(推荐)",
|
||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||
"spaceSaving": "节省空间的复制",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用已核对的大资源,预计需要 {{size}}。Steam 就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingPending": "正在估算可节省的空间。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的大型资源。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
|
||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
|
||||
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
|
||||
@@ -188,7 +188,11 @@
|
||||
},
|
||||
"data": {
|
||||
"body": "选择用于保存存档、缓存和日志的文件夹。",
|
||||
"dialogTitle": "选择数据目录"
|
||||
"dialogTitle": "选择数据目录",
|
||||
"problem": {
|
||||
"overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。",
|
||||
"overlaps_stock": "数据目录不能位于在线版安装目录内。"
|
||||
}
|
||||
},
|
||||
"check": {
|
||||
"running": "正在检查所选游戏版本的补丁。",
|
||||
@@ -232,12 +236,13 @@
|
||||
"update": "从在线版更新",
|
||||
"updateAction": "更新客户端",
|
||||
"newVersion": "安装来源已更新至 {{version}}。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"currentVersion": "安装来源版本 {{version}}",
|
||||
"noSource": "安装来源不可用",
|
||||
"spaceSaving": "节省空间",
|
||||
"spaceSavingHint": "将内容一致且已核对的资源与原版共用。Steam 就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且使用相同的已核对版本。",
|
||||
"spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。",
|
||||
"compactAction": "转换",
|
||||
"check": "重新检查补丁",
|
||||
"checkHint": "核对原版文件备份。",
|
||||
@@ -524,11 +529,15 @@
|
||||
"reset": "恢复默认"
|
||||
},
|
||||
"diagnostics": {
|
||||
"recordLogs": "生成运行日志",
|
||||
"recordLogsToggle": "记录启动器、本地服务器和钩子日志",
|
||||
"recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。",
|
||||
"loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。",
|
||||
"logs": "日志",
|
||||
"logsHint": "启动器运行日志",
|
||||
"openLogs": "打开日志文件夹",
|
||||
"export": "导出诊断信息",
|
||||
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
|
||||
"exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)",
|
||||
"save": "导出…",
|
||||
"saved": "诊断信息已保存到 {{path}}。",
|
||||
"serverStatus": "本地服务器状态页",
|
||||
@@ -566,6 +575,12 @@
|
||||
"about": {
|
||||
"launcher": "启动器 {{version}}",
|
||||
"supported": "支持的游戏版本:{{versions}}",
|
||||
"feedback": {
|
||||
"title": "问题反馈",
|
||||
"export": "保存全部日志",
|
||||
"exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。",
|
||||
"exportButton": "保存日志 ZIP…"
|
||||
},
|
||||
"pack": {
|
||||
"title": "适配数据",
|
||||
"current": "当前使用",
|
||||
@@ -623,7 +638,12 @@
|
||||
}
|
||||
},
|
||||
"statement": "项目信息",
|
||||
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。"
|
||||
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
|
||||
"community": {
|
||||
"discord": "Discord",
|
||||
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
|
||||
"openDiscord": "打开 Discord"
|
||||
}
|
||||
},
|
||||
"features": {
|
||||
"A-Offline startup": "离线启动",
|
||||
@@ -726,8 +746,8 @@
|
||||
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
||||
"patch_check_failed": "检查补丁时出错。",
|
||||
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
||||
"hardlink_unavailable": "省空间复制需要已核对的游戏版本,并且目标与原版位于同一磁盘卷。",
|
||||
"hardlink_no_match": "文件内容与可共用的实测资源不一致。",
|
||||
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
|
||||
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
|
||||
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
||||
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
||||
"install_busy": "已有安装正在进行。",
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
||||
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
|
||||
|
||||
interface AboutPageProps {
|
||||
readonly launcherVersion: string;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly patchPack: PatchPackState;
|
||||
readonly appUpdate: AppUpdateState;
|
||||
readonly loggingEnabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) {
|
||||
/** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Sheet title={t('nav.about')}>
|
||||
@@ -26,14 +31,79 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
|
||||
{t('about.supported', { versions: supportedVersions.join(', ') })}
|
||||
</div>
|
||||
</div>
|
||||
<AppUpdateSection state={appUpdate} />
|
||||
<PatchPackSection state={patchPack} />
|
||||
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
|
||||
<p className="lead">{t('about.statementBody')}</p>
|
||||
<div className="about-columns">
|
||||
<div className="about-column">
|
||||
<AppUpdateSection state={appUpdate} />
|
||||
<PatchPackSection state={patchPack} />
|
||||
</div>
|
||||
<div className="about-column">
|
||||
<CommunitySection />
|
||||
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
|
||||
<section className="about-card">
|
||||
<h3 className="about-card-title">{t('about.statement')}</h3>
|
||||
<p className="about-card-meta">{t('about.statementBody')}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function CommunitySection() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.community.discord')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
|
||||
{t('about.community.openDiscord')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.community.discordHint')}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function FeedbackLogsSection({ loggingEnabled, onError }: {
|
||||
readonly loggingEnabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||
|
||||
async function save(): Promise<void> {
|
||||
setExporting(true);
|
||||
setSavedPath(null);
|
||||
try {
|
||||
const result = await ipcInvoke('app:exportDiagnostics');
|
||||
setSavedPath(result.path);
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.feedback.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
|
||||
{t('about.feedback.exportButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
|
||||
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
||||
const { t } = useTranslation();
|
||||
const { active, check, busy } = state;
|
||||
@@ -45,25 +115,30 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
|
||||
? t('about.pack.bundledVersion', { version: active.version })
|
||||
: t('about.pack.bundled');
|
||||
return (
|
||||
<>
|
||||
<h3 className="section-title">{t('about.pack.title')}</h3>
|
||||
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}>
|
||||
<span>{current}</span>
|
||||
{active?.source === 'downloaded' && (
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
||||
{t('about.pack.useBundled')}
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.pack.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
||||
</button>
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}>
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
|
||||
</button>
|
||||
</Row>
|
||||
{active?.source === 'downloaded' && (
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
|
||||
{t('about.pack.useBundled')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">
|
||||
<span className="about-card-label">{t('about.pack.current')}</span>
|
||||
{' · '}
|
||||
{current}
|
||||
</p>
|
||||
<p className="small">{t('about.pack.currentHint')}</p>
|
||||
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
|
||||
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
|
||||
{check && busy !== 'checking' && <CheckResult state={state} />}
|
||||
</>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
|
||||
@@ -10,13 +9,16 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
||||
if (!state.supported) return null;
|
||||
const { check, busy, progress } = state;
|
||||
return (
|
||||
<>
|
||||
<h3 className="section-title">{t('about.update.title')}</h3>
|
||||
<Row label={t('about.update.check')}>
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
||||
</button>
|
||||
</Row>
|
||||
<section className="about-card">
|
||||
<div className="about-card-head">
|
||||
<h3 className="about-card-title">{t('about.update.title')}</h3>
|
||||
<div className="about-card-actions">
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="about-card-meta">{t('about.update.check')}</p>
|
||||
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
||||
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
||||
{check?.status === 'available' && busy !== 'checking' && (
|
||||
@@ -43,6 +45,6 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
|
||||
)}
|
||||
</Notice>
|
||||
)}
|
||||
</>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +1,24 @@
|
||||
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 type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
|
||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
|
||||
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
|
||||
|
||||
interface CopyMaintenanceProps {
|
||||
readonly record: InstallRecord;
|
||||
readonly maintenance: CopyMaintenanceState;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
type Operation = MaintenanceRequest['operation'];
|
||||
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
||||
|
||||
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
|
||||
const { t } = useTranslation();
|
||||
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
||||
const [working, setWorking] = useState<Operation | null>(null);
|
||||
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
|
||||
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
||||
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -31,29 +26,17 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
if (mounted) setInfo(value);
|
||||
}).catch(onError);
|
||||
return () => { mounted = false; };
|
||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]);
|
||||
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
|
||||
|
||||
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
|
||||
if (event.id === record.id) setProgress(event);
|
||||
}), [record.id]);
|
||||
|
||||
const run = (operation: Operation, options: OperationOptions = {}): void => {
|
||||
setResult(null);
|
||||
setWorking(operation);
|
||||
setProgress(null);
|
||||
ipcInvoke('copies:maintain', { id: record.id, operation, ...options })
|
||||
.then(() => {
|
||||
setResult(operation);
|
||||
setRemoval(null);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
|
||||
else onError(error);
|
||||
})
|
||||
.finally(() => setWorking(null));
|
||||
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||
if (operation === 'delete') setRemoval(null);
|
||||
maintenance.run(record.id, operation, options);
|
||||
};
|
||||
|
||||
const busy = working !== null;
|
||||
const active = maintenance.active;
|
||||
const busy = active !== null;
|
||||
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
|
||||
|
||||
return (
|
||||
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
|
||||
<CopyMaintenanceActions
|
||||
@@ -71,32 +54,25 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
onOptionsChange={setRemoval}
|
||||
onRemove={(deleteData) => run('delete', { deleteData })}
|
||||
/>
|
||||
{working && (
|
||||
<MaintenanceStatus
|
||||
operation={working}
|
||||
progress={progress}
|
||||
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
|
||||
/>
|
||||
)}
|
||||
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
||||
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface MaintenanceStatusProps {
|
||||
readonly operation: Operation;
|
||||
readonly progress: MaintenanceProgress | null;
|
||||
readonly progress: MaintenanceProgress;
|
||||
readonly onCancel: () => void;
|
||||
}
|
||||
|
||||
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) {
|
||||
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="maintenance-progress" role="status">
|
||||
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
|
||||
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
|
||||
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && (
|
||||
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
|
||||
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
|
||||
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
|
||||
<button type="button" className="button" onClick={onCancel}>
|
||||
{t('wizard.cancel')}
|
||||
</button>
|
||||
|
||||
@@ -32,7 +32,9 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
||||
)}
|
||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||
? t(info.updateAvailable
|
||||
? (record.hardlinkedFiles?.length ? 'copies.maintenance.updateDetaches' : 'copies.maintenance.newVersion')
|
||||
? (record.hardlinkedFiles?.length
|
||||
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||
: 'copies.maintenance.newVersion')
|
||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
: t('copies.maintenance.noSource')}>
|
||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { IpcInput } from '@shared/ipc/contract.ts';
|
||||
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
|
||||
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
|
||||
|
||||
export interface MaintenanceOutcome {
|
||||
readonly copyId: string;
|
||||
readonly outcome: MaintenanceOperation | 'cancelled';
|
||||
}
|
||||
|
||||
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
|
||||
export function useCopyMaintenance(onError: (error: unknown) => void) {
|
||||
const [active, setActive] = useState<MaintenanceProgress | null>(null);
|
||||
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
let receivedEvent = false;
|
||||
const dispose = ipcOn('event:copy-maintenance', (event) => {
|
||||
receivedEvent = true;
|
||||
setActive(event);
|
||||
if (event === null) setRevision((value) => value + 1);
|
||||
});
|
||||
ipcInvoke('copies:maintenanceState').then((state) => {
|
||||
if (mounted && !receivedEvent) setActive(state);
|
||||
}).catch(onError);
|
||||
return () => { mounted = false; dispose(); };
|
||||
}, [onError]);
|
||||
|
||||
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
|
||||
setLastResult(null);
|
||||
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
|
||||
ipcInvoke('copies:maintain', { id, operation, ...options })
|
||||
.then(() => {
|
||||
setLastResult({ copyId: id, outcome: operation });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
|
||||
setLastResult({ copyId: id, outcome: 'cancelled' });
|
||||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
|
||||
});
|
||||
}, [onError]);
|
||||
|
||||
const cancel = useCallback((): void => {
|
||||
ipcInvoke('copies:cancelMaintenance').catch(onError);
|
||||
}, [onError]);
|
||||
|
||||
return { active, lastResult, revision, run, cancel };
|
||||
}
|
||||
|
||||
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { DataFolderProblem } from '@shared/schemas/install.ts';
|
||||
import { FolderField } from '../../components/FolderField.tsx';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
|
||||
interface DataStepProps {
|
||||
readonly dataPath: string;
|
||||
readonly dataProblem: DataFolderProblem | null;
|
||||
readonly decalSource: string | null;
|
||||
readonly steamDataPath: string | null;
|
||||
readonly steamDataConfirmed: boolean;
|
||||
@@ -15,13 +17,14 @@ interface DataStepProps {
|
||||
}
|
||||
|
||||
/** Step 3: where saves, caches and logs of the offline version are kept. */
|
||||
export function DataStep({ dataPath, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
||||
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<p className="lead">{t('data.body')}</p>
|
||||
<FolderField path={dataPath} dialogTitle={t('data.dialogTitle')} onChosen={onDataPath} onError={onError} />
|
||||
{steamDataPath && (
|
||||
{dataProblem && <Notice tone="error">{t(`data.problem.${dataProblem}`)}</Notice>}
|
||||
{!dataProblem && steamDataPath && (
|
||||
<Notice tone="warning">
|
||||
<p>{t('steam.dataWarning')}</p>
|
||||
<p className="small">{steamDataPath}</p>
|
||||
|
||||
@@ -39,6 +39,7 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
||||
{step === 'data' && (
|
||||
<DataStep
|
||||
dataPath={wizard.dataPath}
|
||||
dataProblem={wizard.dataProblem}
|
||||
steamDataPath={wizard.steamDataPath}
|
||||
steamDataConfirmed={wizard.steamDataConfirmed}
|
||||
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import type { DataFolderProblem, FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import { ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
import { useErrorMessage } from '../../useErrorMessage.ts';
|
||||
import { checkUsable } from './CheckStep.tsx';
|
||||
@@ -33,7 +33,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
const [draftId, setDraftId] = useState<string | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [dataPath, setDataPath] = useState('');
|
||||
const [dataInspection, setDataInspection] = useState<{ picked: string; path: string; inSteam: boolean; confirmed: boolean } | null>(null);
|
||||
const [dataInspection, setDataInspection] = useState<{
|
||||
key: string;
|
||||
path: string;
|
||||
inSteam: boolean;
|
||||
problem: DataFolderProblem | null;
|
||||
confirmed: boolean;
|
||||
} | null>(null);
|
||||
const [decalSource, setDecalSource] = useState<string | null>(null);
|
||||
const [check, setCheck] = useState<PatchCheck | null>(null);
|
||||
const [missingAccepted, setMissingAccepted] = useState(false);
|
||||
@@ -53,22 +59,38 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
};
|
||||
}, [source, report]);
|
||||
|
||||
const plannedCopyPath = choice.method === 'in-place' || choice.method === 'existing'
|
||||
? (source?.path ?? null)
|
||||
: (choice.target?.path ?? null);
|
||||
const plannedSourcePath = choice.method === 'copy' || choice.method === 'hardlink'
|
||||
? (source?.path ?? null)
|
||||
: null;
|
||||
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
||||
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !dataPath) return;
|
||||
let current = true;
|
||||
ipcInvoke('install:inspectDataFolder', { path: dataPath })
|
||||
.then(({ path, inSteam }) => {
|
||||
ipcInvoke('install:inspectDataFolder', {
|
||||
path: dataPath,
|
||||
...(plannedCopyPath ? { copyPath: plannedCopyPath } : {}),
|
||||
...(plannedSourcePath ? { sourcePath: plannedSourcePath } : {}),
|
||||
...(plannedStockSourcePath ? { stockSourcePath: plannedStockSourcePath } : {}),
|
||||
})
|
||||
.then(({ path, inSteam, problem }) => {
|
||||
if (!current) return;
|
||||
setDataInspection((previous) => previous?.picked === dataPath && previous.path === path && previous.inSteam === inSteam
|
||||
setDataInspection((previous) => previous?.key === dataInspectionKey && previous.path === path &&
|
||||
previous.inSteam === inSteam && previous.problem === problem
|
||||
? previous
|
||||
: { picked: dataPath, path, inSteam, confirmed: false });
|
||||
: { key: dataInspectionKey, path, inSteam, problem, confirmed: false });
|
||||
})
|
||||
.catch((error: unknown) => current && report(error));
|
||||
return () => { current = false; };
|
||||
}, [active, dataPath, report]);
|
||||
}, [active, dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath, dataInspectionKey, report]);
|
||||
|
||||
const dataChecked = dataInspection?.picked === dataPath ? dataInspection : null;
|
||||
const dataReady = dataChecked !== null && (!dataChecked.inSteam || dataChecked.confirmed);
|
||||
const dataChecked = dataInspection?.key === dataInspectionKey ? dataInspection : null;
|
||||
const dataProblem = dataChecked?.problem ?? null;
|
||||
const dataReady = dataChecked !== null && dataProblem === null && (!dataChecked.inSteam || dataChecked.confirmed);
|
||||
const setSteamDataConfirmed = (confirmed: boolean): void => {
|
||||
setDataInspection((inspection) => inspection ? { ...inspection, confirmed } : null);
|
||||
};
|
||||
@@ -208,7 +230,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
};
|
||||
|
||||
return {
|
||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
|
||||
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
|
||||
};
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
interface DiagnosticsSettingsProps {
|
||||
readonly settings: Settings;
|
||||
readonly serverRunning: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
|
||||
export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [savedPath, setSavedPath] = useState<string | null>(null);
|
||||
|
||||
const updateLogging = (loggingEnabled: boolean): void => {
|
||||
ipcInvoke('settings:update', { loggingEnabled }).catch(onError);
|
||||
};
|
||||
|
||||
async function save(): Promise<void> {
|
||||
setExporting(true);
|
||||
setSavedPath(null);
|
||||
@@ -29,6 +35,16 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
|
||||
|
||||
return (
|
||||
<Sheet title={t('settings.sections.diag')}>
|
||||
<Row label={t('settings.diagnostics.recordLogs')} hint={t('settings.diagnostics.recordLogsHint')}>
|
||||
<label className="check check-inline">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.loggingEnabled}
|
||||
onChange={(event) => updateLogging(event.target.checked)}
|
||||
/>
|
||||
{t('settings.diagnostics.recordLogsToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
|
||||
{t('settings.diagnostics.openLogs')}
|
||||
@@ -44,6 +60,7 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
|
||||
{t('settings.diagnostics.openStatus')}
|
||||
</button>
|
||||
</Row>
|
||||
{!settings.loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
|
||||
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
|
||||
@@ -215,9 +215,13 @@
|
||||
|
||||
/* ===== Buttons and links ===== */
|
||||
.button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 500 14px var(--font-display);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
text-decoration: none;
|
||||
padding: 7px 16px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -371,3 +371,67 @@
|
||||
line-height: 1.6;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.about-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.about-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.about-card {
|
||||
min-width: 0;
|
||||
padding: 14px 16px;
|
||||
background: rgba(0, 0, 0, 0.14);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.about-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.about-card-title {
|
||||
margin: 0;
|
||||
font: 500 14px var(--font-display);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.about-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.about-card-meta {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.about-card-label {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.about-card .notice {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.about-card .notice .button {
|
||||
margin-top: 8px;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
CopiesSchema,
|
||||
CopyIdSchema,
|
||||
CopyNameSchema,
|
||||
DATA_FOLDER_PROBLEMS,
|
||||
FolderSizeSchema,
|
||||
GameFolderInspectionSchema,
|
||||
InstallProgressSchema,
|
||||
@@ -85,8 +86,17 @@ export const ipcContract = {
|
||||
output: TargetFolderInspectionSchema,
|
||||
},
|
||||
'install:inspectDataFolder': {
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
output: z.object({ path: z.string(), inSteam: z.boolean() }),
|
||||
input: z.object({
|
||||
path: z.string().min(1),
|
||||
copyPath: z.string().min(1).optional(),
|
||||
sourcePath: z.string().min(1).optional(),
|
||||
stockSourcePath: z.string().min(1).optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
path: z.string(),
|
||||
inSteam: z.boolean(),
|
||||
problem: z.enum(DATA_FOLDER_PROBLEMS).nullable(),
|
||||
}),
|
||||
},
|
||||
'install:measureFolder': {
|
||||
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
|
||||
@@ -144,6 +154,10 @@ export const ipcContract = {
|
||||
input: z.object({ id: CopyIdSchema }),
|
||||
output: MaintenanceInfoSchema,
|
||||
},
|
||||
'copies:maintenanceState': {
|
||||
input: z.void(),
|
||||
output: MaintenanceProgressSchema.nullable(),
|
||||
},
|
||||
'copies:maintain': {
|
||||
input: MaintenanceRequestSchema,
|
||||
output: CopiesSchema,
|
||||
@@ -324,7 +338,7 @@ export const ipcEvents = {
|
||||
'event:app-update-progress': AppUpdateProgressSchema,
|
||||
'event:launch-state': LaunchStateSchema,
|
||||
'event:copies-changed': CopiesSchema,
|
||||
'event:copy-maintenance': MaintenanceProgressSchema,
|
||||
'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
|
||||
/** Another patch set became active (a pack was installed, or the bundled set restored). */
|
||||
'event:patch-set-changed': ActivePatchSetSchema,
|
||||
} as const;
|
||||
|
||||
@@ -41,6 +41,15 @@ export const TargetFolderInspectionSchema = z.object({
|
||||
});
|
||||
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
|
||||
|
||||
/** Why a folder cannot hold the offline client's saves, caches, and logs. */
|
||||
export const DATA_FOLDER_PROBLEMS = [
|
||||
/** The data folder is the client folder itself, contains it, or lies inside its wtoffline folder. */
|
||||
'overlaps_client',
|
||||
/** The data folder lies inside the stock source folder. */
|
||||
'overlaps_stock',
|
||||
] as const;
|
||||
export type DataFolderProblem = (typeof DATA_FOLDER_PROBLEMS)[number];
|
||||
|
||||
export const FolderSizeSchema = z.object({
|
||||
bytes: z.number(),
|
||||
files: z.number(),
|
||||
|
||||
@@ -14,6 +14,7 @@ export const MaintenanceRequestSchema = z.object({
|
||||
export const MaintenanceInfoSchema = z.object({
|
||||
sourceVersion: z.string().nullable(),
|
||||
updateAvailable: z.boolean(),
|
||||
updatePreservesSpaceSaving: z.boolean(),
|
||||
spaceSavingAvailable: z.boolean(),
|
||||
steamConfirmationRequired: z.boolean(),
|
||||
steamLocations: z.object({
|
||||
|
||||
@@ -28,6 +28,8 @@ export const SettingsSchema = z.object({
|
||||
windowClose: WindowCloseSchema.default('quit'),
|
||||
afterGameStarts: AfterGameStartsSchema.default('minimize'),
|
||||
autoSaveBackups: z.boolean().default(true),
|
||||
/** Write launcher, local server traffic, and wto_ws.log files; does not affect game .game_logs. */
|
||||
loggingEnabled: z.boolean().default(true),
|
||||
launchPortMode: PortModeSchema.default('auto'),
|
||||
launchPort: PortSchema.default(27015),
|
||||
closeServerOnGameExit: z.boolean().default(true),
|
||||
@@ -50,6 +52,7 @@ export const SettingsPatchSchema = z.object({
|
||||
windowClose: WindowCloseSchema.optional(),
|
||||
afterGameStarts: AfterGameStartsSchema.optional(),
|
||||
autoSaveBackups: z.boolean().optional(),
|
||||
loggingEnabled: z.boolean().optional(),
|
||||
launchPortMode: PortModeSchema.optional(),
|
||||
launchPort: PortSchema.optional(),
|
||||
closeServerOnGameExit: z.boolean().optional(),
|
||||
|
||||
@@ -37,6 +37,7 @@ export interface EnqueueBattleInput {
|
||||
readonly modes?: readonly OfferedGameMode[];
|
||||
readonly country: string;
|
||||
readonly slotVehicles: readonly string[];
|
||||
readonly mrankDeltas: ReadonlyMap<string, number>;
|
||||
readonly selectedSlot?: BattleCrewSlot;
|
||||
readonly bannedMissions: ReadonlySet<string>;
|
||||
readonly dislikedMissions: ReadonlySet<string>;
|
||||
@@ -117,13 +118,14 @@ export class BattleMatchmaker {
|
||||
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
|
||||
);
|
||||
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
|
||||
const chosenMode = this.#pickQueuedMode(pvpModes, input.slotVehicles, input.selectedSlot?.unitName);
|
||||
const chosenMode = this.#pickQueuedMode(pvpModes, input);
|
||||
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
|
||||
|
||||
const { declaration } = chosenMode;
|
||||
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
|
||||
const playerMrank = lineupMrank(
|
||||
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
|
||||
input.mrankDeltas,
|
||||
);
|
||||
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
||||
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
|
||||
@@ -158,13 +160,10 @@ export class BattleMatchmaker {
|
||||
};
|
||||
}
|
||||
|
||||
#pickQueuedMode(
|
||||
candidates: readonly OfferedGameMode[],
|
||||
slotVehicles: readonly string[],
|
||||
selectedSlotVehicle: string | undefined,
|
||||
): OfferedGameMode | undefined {
|
||||
const pool = candidates.filter((mode) =>
|
||||
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
|
||||
#pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
|
||||
const pool = candidates.filter((mode) => isModeEligibleForLineup(
|
||||
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
|
||||
));
|
||||
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
|
||||
const classics = pool.filter((mode) => !mode.declaration.tag);
|
||||
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
||||
|
||||
@@ -28,7 +28,7 @@ const RULE_KEYS: readonly string[] = [
|
||||
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
||||
const VERSUS_SWITCHES: readonly string[] = [
|
||||
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
|
||||
'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
|
||||
'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -60,6 +60,8 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
|
||||
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
|
||||
setParam(settings, 'gt_mp_solo', flag(false));
|
||||
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
||||
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
|
||||
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
|
||||
setParam(settings, 'allowSpare', flag(!plan.selectedSlot));
|
||||
if (plan.selectedSlot) {
|
||||
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
|
||||
|
||||
@@ -95,18 +95,28 @@ export function lineupMrank(
|
||||
difficulty: ModeDifficulty,
|
||||
requiredClass: UnitClass,
|
||||
allowedClasses: readonly UnitClass[],
|
||||
mrankDeltas: ReadonlyMap<string, number>,
|
||||
): number {
|
||||
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
|
||||
const vehicle = byName.get(name);
|
||||
if (!vehicle) return [];
|
||||
return [{
|
||||
unitClass: unitClassOfExpClass(vehicle.unitClass),
|
||||
mrank: vehicleMrank(vehicle, difficulty, requiredClass),
|
||||
mrank: lineupVehicleMrank(vehicle, difficulty, requiredClass, mrankDeltas),
|
||||
}];
|
||||
});
|
||||
return maxModeMrank(crafts, requiredClass, allowedClasses);
|
||||
}
|
||||
|
||||
function lineupVehicleMrank(
|
||||
vehicle: CatalogueVehicle,
|
||||
difficulty: ModeDifficulty,
|
||||
requiredClass: UnitClass,
|
||||
mrankDeltas: ReadonlyMap<string, number>,
|
||||
): number {
|
||||
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
|
||||
}
|
||||
|
||||
export function selectCustomBots(
|
||||
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
|
||||
): CustomBotsPool {
|
||||
@@ -203,6 +213,7 @@ export function isModeEligibleForLineup(
|
||||
slotVehicles: readonly string[],
|
||||
selectedSlotVehicle: string | undefined,
|
||||
byName: ReadonlyMap<string, CatalogueVehicle>,
|
||||
mrankDeltas: ReadonlyMap<string, number>,
|
||||
): boolean {
|
||||
if (!declaration.tag && declaration.multiSlot !== false) return true;
|
||||
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
|
||||
@@ -211,7 +222,7 @@ export function isModeEligibleForLineup(
|
||||
const matchingCount = active.filter((name) => {
|
||||
const vehicle = byName.get(name);
|
||||
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
|
||||
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank;
|
||||
return lineupVehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass, mrankDeltas) >= minMrank;
|
||||
}).length;
|
||||
return matchingCount >= minCrafts;
|
||||
}
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
buyWeaponsAction,
|
||||
enableModificationsAction,
|
||||
saveWeaponPresetsAction,
|
||||
setUnitSelectedMrankAction,
|
||||
} from './modification-actions.ts';
|
||||
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
|
||||
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
|
||||
@@ -137,6 +138,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
|
||||
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||
['cln_set_unit_selected_mrank', setUnitSelectedMrankAction(deps.profiles, deps.accounts, deps.equipment)],
|
||||
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
||||
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
|
||||
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
|
||||
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
|
||||
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
|
||||
* cln_set_unit_selected_mrank (scripts/unit/unitmrankselectionstate.nut): unit:t addMrank:i
|
||||
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
|
||||
* <vehicle>{ <modification>:b=yes ... } ...
|
||||
*/
|
||||
@@ -16,6 +17,7 @@ import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
||||
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
|
||||
import { buySpares } from '../../modifications/spare-purchase.ts';
|
||||
import { selectVehicleMrankDelta } from '../../modifications/vehicle-mrank-selection.ts';
|
||||
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
|
||||
import { buyWeapons } from '../../modifications/weapon-purchase.ts';
|
||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||
@@ -81,6 +83,15 @@ export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: Acco
|
||||
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
|
||||
}
|
||||
|
||||
export function setUnitSelectedMrankAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
|
||||
return ruleAction(profiles, accounts, (payload) => {
|
||||
const vehicle = stringParam(payload, 'unit');
|
||||
const delta = intParam(payload, 'addMrank');
|
||||
if (!vehicle || delta === undefined) return undefined;
|
||||
return (profile) => selectVehicleMrankDelta(profile, equipment, vehicle, delta);
|
||||
});
|
||||
}
|
||||
|
||||
function offeredPrice(payload: BlkBlock) {
|
||||
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
* char.vromfs.bin config/wpcost.blk, per vehicle:
|
||||
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
|
||||
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
|
||||
* reqModification:t (repeated) maxCount:i ammoCount:i ... } }
|
||||
* reqModification:t (repeated) maxCount:i ammoCount:i addMrank:i ... } }
|
||||
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
|
||||
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
|
||||
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
|
||||
@@ -39,6 +39,8 @@ export interface ModificationFacts {
|
||||
readonly maxCount: number;
|
||||
/** ammoCount present: an ammunition belt or shell type. */
|
||||
readonly ammunition: boolean;
|
||||
/** addMrank: selectable matchmaking rank increase unlocked by owning this modification. */
|
||||
readonly addMrank?: number;
|
||||
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
|
||||
readonly defaultEnabled: boolean;
|
||||
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
|
||||
@@ -78,7 +80,7 @@ interface GlobalModificationMeta {
|
||||
|
||||
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
|
||||
id: 'vehicle-equipment',
|
||||
version: 4,
|
||||
version: 5,
|
||||
extract: (source) => {
|
||||
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
|
||||
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
|
||||
@@ -119,6 +121,7 @@ function equipmentOf(vehicle: BlkBlock, modMeta: ReadonlyMap<string, GlobalModif
|
||||
|
||||
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
|
||||
const ammunition = numberField(modification, 'ammoCount') !== undefined;
|
||||
const addMrank = numberField(modification, 'addMrank');
|
||||
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
|
||||
const group = stringField(modification, 'group') ?? meta?.group;
|
||||
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
|
||||
@@ -132,6 +135,7 @@ function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | u
|
||||
requires: stringList(modification, 'reqModification'),
|
||||
maxCount: numberField(modification, 'maxCount') ?? 0,
|
||||
ammunition,
|
||||
...(addMrank !== undefined ? { addMrank } : {}),
|
||||
defaultEnabled,
|
||||
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankE
|
||||
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
||||
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
|
||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
|
||||
import type { MatchingRequestHandler } from './matching-requests.ts';
|
||||
@@ -90,6 +91,7 @@ function handleEnqueue(
|
||||
modes,
|
||||
country: playerEntry.country,
|
||||
slotVehicles,
|
||||
mrankDeltas: new Map(slotVehicles.map((vehicle) => [vehicle, vehicleMrankDelta(profile, vehicle)])),
|
||||
...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}),
|
||||
bannedMissions: playerEntry.bannedMissions,
|
||||
dislikedMissions: playerEntry.dislikedMissions,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { ownsVehicle, setVehicleMrankDelta } from '../profile/profile-hangar.ts';
|
||||
import { modificationRecord } from '../profile/profile-modifications.ts';
|
||||
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
|
||||
|
||||
export function selectVehicleMrankDelta(
|
||||
profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, delta: number,
|
||||
): RuleOutcome {
|
||||
const equipment = catalogue.vehicle(vehicle);
|
||||
if (!equipment || !ownsVehicle(profile, vehicle) || !Number.isInteger(delta) || delta < 0) return refused('BAD_PARAMS');
|
||||
|
||||
// Stock getSelectableAddMranks offers zero and each positive addMrank on an owned modification.
|
||||
if (delta > 0 && !equipment.modifications.some((modification) =>
|
||||
modification.addMrank === delta && (modificationRecord(profile, vehicle, modification.name)?.count ?? 0) > 0)) {
|
||||
return refused('NOT_AVAILABLE');
|
||||
}
|
||||
|
||||
setVehicleMrankDelta(profile, vehicle, delta);
|
||||
return ACCEPTED;
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
/**
|
||||
* Owned vehicles in the profile, as in Gaijin's
|
||||
* config/default_user.blk: one empty sub-block per vehicle the player owns.
|
||||
* The profile's hangar has one sub-block per owned vehicle, as in config/default_user.blk.
|
||||
*
|
||||
* hangar{
|
||||
* bf2c_1{
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
|
||||
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { intField } from './blk-fields.ts';
|
||||
|
||||
const HANGAR = 'hangar';
|
||||
const MRANK_DELTA = 'mrankDelta';
|
||||
|
||||
function ownedVehicle(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
|
||||
const hangar = findBlock(profile, HANGAR);
|
||||
return hangar && findBlock(hangar, vehicle);
|
||||
}
|
||||
|
||||
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
|
||||
const hangar = findBlock(profile, HANGAR);
|
||||
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
|
||||
return ownedVehicle(profile, vehicle) !== undefined;
|
||||
}
|
||||
|
||||
export function ownedVehicles(profile: BlkBlock): Set<string> {
|
||||
@@ -25,3 +30,13 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
|
||||
const hangar = ensureBlock(profile, HANGAR);
|
||||
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
|
||||
}
|
||||
|
||||
/** The stock client uses the base rank until it has a non-negative selection. */
|
||||
export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number {
|
||||
return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA));
|
||||
}
|
||||
|
||||
export function setVehicleMrankDelta(profile: BlkBlock, vehicle: string, delta: number): void {
|
||||
const entry = ownedVehicle(profile, vehicle);
|
||||
if (entry) setParam(entry, MRANK_DELTA, { type: 'int', value: delta });
|
||||
}
|
||||
@@ -69,6 +69,8 @@ export interface ServerOptions {
|
||||
readonly port: number;
|
||||
/** Start-up progress lines (static data extraction, game modes). */
|
||||
readonly report?: (line: string) => void;
|
||||
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
|
||||
readonly loggingEnabled?: boolean;
|
||||
}
|
||||
|
||||
export const LOOPBACK = '127.0.0.1';
|
||||
@@ -143,7 +145,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
|
||||
})),
|
||||
new DownloadableContentService(),
|
||||
]);
|
||||
const log = new TrafficLog(options.dataFolder);
|
||||
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
|
||||
const listener = createPortListener(
|
||||
router,
|
||||
matchingRequests({
|
||||
|
||||
@@ -20,11 +20,19 @@ export interface MatchingLogEntry {
|
||||
|
||||
export class TrafficLog {
|
||||
readonly folder: string;
|
||||
readonly #enabled: boolean;
|
||||
readonly #linesPath: string;
|
||||
readonly #bodiesFolder: string;
|
||||
#sequence = 0;
|
||||
|
||||
constructor(dataFolder: string) {
|
||||
constructor(dataFolder: string, enabled = true) {
|
||||
this.#enabled = enabled;
|
||||
if (!enabled) {
|
||||
this.folder = '';
|
||||
this.#linesPath = '';
|
||||
this.#bodiesFolder = '';
|
||||
return;
|
||||
}
|
||||
this.folder = join(dataFolder, 'logs', new Date().toISOString().replace(/[:.]/g, '-'));
|
||||
this.#linesPath = join(this.folder, 'requests.jsonl');
|
||||
this.#bodiesFolder = join(this.folder, 'bodies');
|
||||
@@ -96,11 +104,12 @@ export class TrafficLog {
|
||||
}
|
||||
|
||||
#append(line: object): void {
|
||||
if (!this.#enabled) return;
|
||||
appendFileSync(this.#linesPath, JSON.stringify(line) + '\n');
|
||||
}
|
||||
|
||||
#writeBody(id: number, suffix: string, content: Uint8Array | string | undefined): string | null {
|
||||
if (content === undefined || byteLength(content) === 0) return null;
|
||||
if (!this.#enabled || content === undefined || byteLength(content) === 0) return null;
|
||||
const name = `${String(id).padStart(6, '0')}.${suffix}`;
|
||||
writeFileSync(join(this.#bodiesFolder, name), content);
|
||||
return name;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* wto_ws.cfg, written by the build into the game copy (@wto/patcher network-hook.ts):
|
||||
* port=<local server port> without a valid port the hooks still answer every host name
|
||||
* locally but refuse every connection that would leave the machine
|
||||
* log=0|1 optional, defaults to 1; when 0, wto_ws.log is not opened
|
||||
* exe.time_date_stamp=0x... the executable the native values were resolved for
|
||||
* exe.size_of_image=0x...
|
||||
* native.<name>=<value> what the LocalMP modules need from the executable: RVAs of
|
||||
@@ -33,6 +34,7 @@ typedef struct NativeValue {
|
||||
static wchar_t g_folder[MAX_PATH];
|
||||
static CRITICAL_SECTION g_log_lock;
|
||||
static FILE *g_log;
|
||||
static int g_log_enabled = 1;
|
||||
static NativeValue g_native[NATIVE_VALUES_MAX];
|
||||
static size_t g_native_count;
|
||||
static int64_t g_exe_time_date_stamp = -1;
|
||||
@@ -98,6 +100,8 @@ static void read_settings(void)
|
||||
line[strcspn(line, "\r\n")] = '\0';
|
||||
if (strncmp(line, "port=", 5) == 0)
|
||||
read_port(line + 5);
|
||||
else if (strncmp(line, "log=", 4) == 0)
|
||||
g_log_enabled = atoi(line + 4) != 0;
|
||||
else if (strncmp(line, "exe.time_date_stamp=", 20) == 0)
|
||||
parse_value(line + 20, &g_exe_time_date_stamp);
|
||||
else if (strncmp(line, "exe.size_of_image=", 18) == 0)
|
||||
@@ -140,7 +144,7 @@ void config_load(HMODULE self)
|
||||
InitializeCriticalSection(&g_log_lock);
|
||||
find_folder(self);
|
||||
read_settings();
|
||||
if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
|
||||
if (g_log_enabled && _snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
|
||||
g_log = _wfsopen(path, L"w", _SH_DENYWR);
|
||||
log_line("wto_ws: local server port %u%s", g_service_port, g_service_port ? "" : " (none: outside connections are refused)");
|
||||
log_line("wto_ws: %u native value(s) for the LocalMP modules", (unsigned)g_native_count);
|
||||
|
||||
Generated
+1
-1
@@ -21,7 +21,7 @@
|
||||
},
|
||||
"apps/launcher": {
|
||||
"name": "@wto/launcher",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"dependencies": {
|
||||
"@fontsource/roboto-condensed": "^5.3.0",
|
||||
"@wto/patcher": "*",
|
||||
|
||||
@@ -44,6 +44,8 @@ export interface GameCopyInputs {
|
||||
readonly multiVehiclePackIds: readonly string[];
|
||||
/** Store the placeholder decal index; false when the player's own web cache is copied. */
|
||||
readonly placeholderDecals: boolean;
|
||||
/** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */
|
||||
readonly hookLogging?: boolean;
|
||||
}
|
||||
|
||||
/** One file of the game copy, by its path relative to the copy folder. */
|
||||
@@ -96,7 +98,9 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
|
||||
const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles);
|
||||
|
||||
const executableFolder = dirname(GAME_FILES.executable);
|
||||
const hookSettings = networkHookSettings(endpoint, stockImage, native.values);
|
||||
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
|
||||
loggingEnabled: inputs.hookLogging ?? true,
|
||||
});
|
||||
const files: GameCopyFile[] = [
|
||||
{ path: GAME_FILES.charPack, content: charPack },
|
||||
{ path: GAME_FILES.mainPack, content: mainPack.pack },
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/** Version-independent read-only asset rules for space-saving hardlink copies. */
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
import { GAME_FILES } from './game-copy.ts';
|
||||
|
||||
export interface HardlinkResourceRules {
|
||||
readonly allowedDirectories: readonly string[];
|
||||
readonly allowedExtensions: readonly string[];
|
||||
readonly minBytes: number;
|
||||
}
|
||||
|
||||
const TUNING_FILE = new URL('../tuning/hardlink-resources.jsonc', import.meta.url);
|
||||
const PROTECTED_FILES = new Set(Object.values(GAME_FILES).map((path) => path.replaceAll('\\', '/').toLowerCase()));
|
||||
|
||||
let cached: HardlinkResourceRules | null = null;
|
||||
|
||||
export function hardlinkResourceRules(): HardlinkResourceRules {
|
||||
if (cached) return cached;
|
||||
const value = parseJsonc(readFileSync(TUNING_FILE, 'utf8'));
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw tuningError('the file is not an object');
|
||||
}
|
||||
const fields = value as Record<string, unknown>;
|
||||
const allowedDirectories = readDirectories(fields, 'allowed_directories');
|
||||
const allowedExtensions = readExtensions(fields, 'allowed_extensions');
|
||||
const minBytes = readNonNegativeInteger(fields, 'min_bytes');
|
||||
cached = { allowedDirectories, allowedExtensions, minBytes };
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** Whether a relative path inside a stock client is a static read-only asset safe to hardlink. */
|
||||
export function isHardlinkableResource(relativePath: string, bytes: number): boolean {
|
||||
const rules = hardlinkResourceRules();
|
||||
if (!Number.isFinite(bytes) || bytes < 0 || bytes < rules.minBytes) return false;
|
||||
const normalized = relativePath.replaceAll('\\', '/').toLowerCase();
|
||||
if (!normalized || normalized.startsWith('/') || normalized.includes('../') || normalized === '..') return false;
|
||||
if (normalized.startsWith('wtoffline/') || PROTECTED_FILES.has(normalized)) return false;
|
||||
return rules.allowedDirectories.some((dir) => normalized.startsWith(dir)) &&
|
||||
rules.allowedExtensions.some((ext) => normalized.endsWith(ext));
|
||||
}
|
||||
|
||||
function readDirectories(fields: Record<string, unknown>, key: string): readonly string[] {
|
||||
const raw = fields[key];
|
||||
if (!Array.isArray(raw) || raw.length === 0) throw tuningError(`"${key}" must be a non-empty string array`);
|
||||
return raw.map((item) => {
|
||||
if (typeof item !== 'string' || !item.endsWith('/') || item.startsWith('/') || item.includes('\\') || item.includes('..')) {
|
||||
throw tuningError(`"${key}" entries must be lowercase relative prefixes ending with "/"`);
|
||||
}
|
||||
return item.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function readExtensions(fields: Record<string, unknown>, key: string): readonly string[] {
|
||||
const raw = fields[key];
|
||||
if (!Array.isArray(raw) || raw.length === 0) throw tuningError(`"${key}" must be a non-empty string array`);
|
||||
return raw.map((item) => {
|
||||
if (typeof item !== 'string' || !item.startsWith('.') || item.length < 2 || item.includes('/') || item.includes('\\')) {
|
||||
throw tuningError(`"${key}" entries must be file extensions starting with "."`);
|
||||
}
|
||||
return item.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function readNonNegativeInteger(fields: Record<string, unknown>, key: string): number {
|
||||
const value = fields[key];
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
|
||||
throw tuningError(`"${key}" must be a non-negative integer`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function tuningError(detail: string): Error {
|
||||
return new Error(`tuning/hardlink-resources.jsonc: ${detail}`);
|
||||
}
|
||||
@@ -18,6 +18,11 @@ export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
|
||||
export { executableVersion } from './game-version.ts';
|
||||
export {
|
||||
hardlinkResourceRules,
|
||||
isHardlinkableResource,
|
||||
type HardlinkResourceRules,
|
||||
} from './hardlink-resources.ts';
|
||||
export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';
|
||||
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
|
||||
|
||||
@@ -17,7 +17,12 @@ export function networkHookSettings(
|
||||
endpoint: LocalEndpoint,
|
||||
stock: PeImage,
|
||||
nativeValues: ReadonlyMap<string, number>,
|
||||
options?: { readonly loggingEnabled?: boolean },
|
||||
): { name: string; content: Uint8Array } {
|
||||
const lines = [`port=${endpoint.port}`, ...nativeSettingsLines(stock, nativeValues)];
|
||||
const lines = [
|
||||
`port=${endpoint.port}`,
|
||||
...(options?.loggingEnabled === false ? ['log=0'] : []),
|
||||
...nativeSettingsLines(stock, nativeValues),
|
||||
];
|
||||
return { name: SETTINGS, content: new TextEncoder().encode(`${lines.join('\n')}\n`) };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Rules for space-saving NTFS hardlink copies between the stock client and an offline client.
|
||||
// Matching is version-independent so minor updates keep working without regenerating per-version
|
||||
// hash lists. Only static read-only engine asset archives that the game process never writes to
|
||||
// belong here; executables, vromfs archives, configs, metadata, and hotfix overlays stay copied.
|
||||
{
|
||||
// Relative directory prefixes (lowercase, trailing slash) containing read-only asset packs.
|
||||
"allowed_directories": [
|
||||
"content/",
|
||||
"content.hq/"
|
||||
],
|
||||
|
||||
// Lowercase file suffixes for static texture and model archives.
|
||||
"allowed_extensions": [
|
||||
".dxp.bin",
|
||||
".grp"
|
||||
],
|
||||
|
||||
// Minimum file size in bytes (0 links every matching archive regardless of size).
|
||||
"min_bytes": 0
|
||||
}
|
||||
Reference in new issue
Block a user