merge: bring main into feat/tank-ai-nav
Takes main's mounted gun traverse limits, capture and hit feedback, LocalMP air AI sync, mod tech tree insertions and launcher changes. Conflicts resolved: - wto_ai_runtime.das: fire update runs before navigation, as on main, so a hull-aim request is driven in the same frame; navigation keeps the navmesh state and slot arguments of this branch. - wto_ai_nav_common.das: main's wto_try_hull_aim replaces the old limited-traverse pivot and uses this branch's drive command helper and stuck-watch reset. - build.ps1 and local_mp_internal.h: keep both sides' sources and declarations.
This commit is contained in:
commit
77e4806ffc
114 files changed
+4330
-623
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wto/launcher",
|
||||
"productName": "WTOffline Launcher",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"description": "Installer and launcher of the War Thunder offline project.",
|
||||
"type": "module",
|
||||
|
||||
@@ -11,7 +11,7 @@ import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagn
|
||||
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 { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.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';
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from '../services/mods/mods-service.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
|
||||
import { broadcast, handle } from './register.ts';
|
||||
|
||||
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
||||
@@ -68,11 +69,18 @@ export function registerIpcHandlers(): void {
|
||||
BrowserWindow.fromWebContents(sender)?.close();
|
||||
});
|
||||
|
||||
handle('dialog:pickFolder', async ({ title }, sender) => {
|
||||
handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
|
||||
const window = BrowserWindow.fromWebContents(sender);
|
||||
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
|
||||
const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
|
||||
const options = {
|
||||
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
|
||||
...(title ? { title } : {}),
|
||||
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
|
||||
};
|
||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
|
||||
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
|
||||
if (chosen) await rememberDialogPath('folder', chosen);
|
||||
return { path: chosen };
|
||||
});
|
||||
|
||||
handle('install:prepareCopy', () => createCopyDraft());
|
||||
@@ -156,6 +164,7 @@ export function registerIpcHandlers(): void {
|
||||
return updated;
|
||||
});
|
||||
handle('copies:cancelMaintenance', () => cancelMaintenance());
|
||||
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
|
||||
|
||||
handle('saves:list', ({ copyId }) => getSaveList(copyId));
|
||||
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
|
||||
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 { readClientMarker, writeClientMarker } from '../install/client-marker.ts';
|
||||
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||
import {
|
||||
fileHash,
|
||||
@@ -69,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
||||
signal.throwIfAborted();
|
||||
const check = await checkPatches(game.path, record.dataPath);
|
||||
signal.throwIfAborted();
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
const updated = await changeCopyFiles(root, async (incoming) => {
|
||||
report('copying', 0, copy.totalBytes);
|
||||
let lastReport = 0;
|
||||
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
|
||||
@@ -104,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
|
||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
|
||||
})));
|
||||
if (!preserveHardlinks && linked.length > 0) {
|
||||
const marker = await readClientMarker(root);
|
||||
if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) {
|
||||
await writeClientMarker(root, 'copy');
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
interface UpdateFilePlan {
|
||||
@@ -188,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
||||
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) => {
|
||||
const updated = await changeCopyFiles(root, async (incoming) => {
|
||||
const replacements: string[] = [];
|
||||
const unchanged = new Map<string, BigIntStats>();
|
||||
let checked = 0;
|
||||
@@ -225,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
|
||||
report('applying', total, total);
|
||||
return { replace: replacements, remove: [] };
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||
await writeClientMarker(root, 'hardlink');
|
||||
return updated;
|
||||
}
|
||||
|
||||
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
|
||||
|
||||
@@ -1,21 +1,29 @@
|
||||
import { readdir, rm } from 'node:fs/promises';
|
||||
import { isAbsolute, join, parse, relative } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { isAbsolute, relative } from 'node:path';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
|
||||
import { installationInProgress } from '../install/install-game.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { checkPatches } from '../install/patch-check.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { fileInfo } from './change-copy-files.ts';
|
||||
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
|
||||
import {
|
||||
canDeleteCopyFiles,
|
||||
canRestoreStock,
|
||||
checkedRoot,
|
||||
failLocation,
|
||||
removeCopy,
|
||||
resolveClientOrigin,
|
||||
withCanonicalSources,
|
||||
} from './copy-removal.ts';
|
||||
import { readSource, setCopySource } from './copy-source.ts';
|
||||
|
||||
export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
|
||||
|
||||
let current: {
|
||||
stop: AbortController;
|
||||
interruptible: boolean;
|
||||
@@ -35,9 +43,23 @@ export function cancelMaintenance(): void {
|
||||
}
|
||||
|
||||
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
const record = await requireCopy(id);
|
||||
const source = await readSource(record);
|
||||
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
|
||||
const registry = await listCopies();
|
||||
const record = registry.copies.find((copy) => copy.id === id);
|
||||
if (!record) throw new AppError('copy_not_found');
|
||||
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
|
||||
readSource(record),
|
||||
canonicalCopyPath(record.copyPath),
|
||||
canonicalCopyPath(record.dataPath),
|
||||
withCanonicalSources(registry.copies),
|
||||
]);
|
||||
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
|
||||
readClientMarker(copyPath),
|
||||
detectHardlinkedResources(copyPath),
|
||||
canRestoreStock(record, copyPath),
|
||||
]);
|
||||
const clientOrigin = resolveClientOrigin(record, diskMarker);
|
||||
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
|
||||
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
|
||||
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
|
||||
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
|
||||
return {
|
||||
@@ -47,6 +69,10 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
||||
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
|
||||
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
|
||||
clientOrigin,
|
||||
hasHardlinkedResources,
|
||||
canDeleteFiles,
|
||||
canRestoreAndRemove,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -94,6 +120,19 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
||||
const { id, operation, steamLocations } = request;
|
||||
const record = await requireCopy(id);
|
||||
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
|
||||
if (operation === 'delete') {
|
||||
return removeCopy(
|
||||
record,
|
||||
{
|
||||
deleteFiles: request.deleteFiles === true,
|
||||
restoreStock: request.restoreStock === true,
|
||||
deleteData: request.deleteData === true,
|
||||
},
|
||||
signal,
|
||||
report,
|
||||
labServerUses,
|
||||
);
|
||||
}
|
||||
|
||||
const root = await checkedRoot(record);
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
@@ -101,7 +140,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
||||
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
|
||||
signal.throwIfAborted();
|
||||
|
||||
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) {
|
||||
if (operation !== 'confirm-steam' && needsConfirmation) {
|
||||
throw new AppError('launch_steam_confirmation_required');
|
||||
}
|
||||
|
||||
@@ -123,9 +162,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
|
||||
return updateFromSource(record, root, signal, report);
|
||||
case 'compact':
|
||||
return compactCopy(record, root, signal, report);
|
||||
case 'delete':
|
||||
report('applying');
|
||||
return remove(record, root, request.deleteData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,42 +171,6 @@ 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);
|
||||
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)) {
|
||||
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
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, 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 });
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
async function labServerUses(root: string): Promise<boolean> {
|
||||
const lab = await readInstalledLab().catch(() => null);
|
||||
if (!lab || relative(lab.copyPath, root) !== '') return false;
|
||||
@@ -183,38 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
|
||||
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
|
||||
}));
|
||||
}
|
||||
|
||||
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
|
||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
|
||||
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
|
||||
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
|
||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
|
||||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
|
||||
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
|
||||
}
|
||||
if (!deleteData && copyPathContains(root, data)) {
|
||||
await removeExcept(root, data);
|
||||
} else {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
|
||||
/** Keep the data folder in place when it was chosen inside this copy. */
|
||||
async function removeExcept(folder: string, kept: string): Promise<void> {
|
||||
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (copyPathContains(path, kept)) {
|
||||
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||
await removeExcept(path, kept);
|
||||
} else {
|
||||
await rm(path, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { constants } from 'node:fs';
|
||||
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { rawFs } from '../../util/raw-fs.ts';
|
||||
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
|
||||
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { gameProcessRunning } from '../launch/launch-controller.ts';
|
||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||
import type { Report } from './copy-file-maintenance.ts';
|
||||
|
||||
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
|
||||
|
||||
export interface RemoveCopyOptions {
|
||||
readonly deleteFiles: boolean;
|
||||
readonly restoreStock: boolean;
|
||||
readonly deleteData: boolean;
|
||||
}
|
||||
|
||||
export function failLocation(reason: string, details: Record<string, unknown>): never {
|
||||
console.warn('[copies] maintenance_location:', reason, details);
|
||||
throw new AppError('maintenance_location');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effective client origin by preferring a valid on-disk marker while
|
||||
* keeping in-place registrations conservatively locked as `in-place`.
|
||||
*/
|
||||
export function resolveClientOrigin(
|
||||
record: InstallRecord,
|
||||
diskMarker: ClientMarker | null,
|
||||
): ClientOrigin | null {
|
||||
if (record.method === 'in-place') return 'in-place';
|
||||
if (diskMarker) return diskMarker.origin;
|
||||
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
|
||||
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
|
||||
*/
|
||||
export function canDeleteCopyFiles(
|
||||
record: InstallRecord,
|
||||
root: string,
|
||||
effectiveOrigin: ClientOrigin | null,
|
||||
allCopies: readonly InstallRecord[] = [],
|
||||
): boolean {
|
||||
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
|
||||
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
|
||||
const normalizedRoot = resolve(root);
|
||||
const normalizedCopyPath = resolve(record.copyPath);
|
||||
const sources = record.sourcePath
|
||||
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
|
||||
: allCopies.map((copy) => copy.sourcePath);
|
||||
for (const candidate of sources) {
|
||||
if (!candidate) continue;
|
||||
const source = resolve(candidate);
|
||||
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
|
||||
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
|
||||
try {
|
||||
const safeRoot = await checkedRoot(record);
|
||||
const canonicalRoot = await canonicalCopyPath(root);
|
||||
if (relative(safeRoot, canonicalRoot) !== '') return false;
|
||||
const backup = await requireStockBackupLocation(safeRoot);
|
||||
const fsPromises = rawFs().promises;
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
const stockFile = join(backup, file);
|
||||
const info = await fileInfo(stockFile);
|
||||
if (!info?.isFile()) return false;
|
||||
await fsPromises.access(stockFile, constants.R_OK);
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
|
||||
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
|
||||
return Promise.all(copies.map(async (copy) => (
|
||||
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
|
||||
)));
|
||||
}
|
||||
|
||||
export async function checkedRoot(record: InstallRecord): Promise<string> {
|
||||
const root = await safeFolder(record.copyPath, true);
|
||||
const backup = await canonicalCopyPath(record.stockBackupPath);
|
||||
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 (pathsOverlap(source, root)) {
|
||||
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
export 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, 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 });
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
export async function removeCopy(
|
||||
record: InstallRecord,
|
||||
options: RemoveCopyOptions,
|
||||
signal: AbortSignal,
|
||||
report: Report,
|
||||
labServerUses: (root: string) => Promise<boolean>,
|
||||
): Promise<Copies> {
|
||||
const { deleteFiles, restoreStock, deleteData } = options;
|
||||
if (deleteFiles && restoreStock) {
|
||||
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
|
||||
}
|
||||
|
||||
const canonicalRoot = await canonicalCopyPath(record.copyPath);
|
||||
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
|
||||
throw new AppError('maintenance_busy');
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
|
||||
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
|
||||
// so missing, moved, or damaged client registrations can always be removed safely.
|
||||
if (!deleteFiles && !deleteData && !restoreStock) {
|
||||
report('applying');
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
|
||||
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
|
||||
if ((deleteFiles || deleteData) && copyInSteam) {
|
||||
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
|
||||
method: record.method,
|
||||
copyPath: record.copyPath,
|
||||
root: canonicalRoot,
|
||||
});
|
||||
}
|
||||
|
||||
let root = canonicalRoot;
|
||||
if (deleteFiles) {
|
||||
const allCopies = (await listCopies()).copies;
|
||||
const canonicalCopies = await withCanonicalSources(allCopies);
|
||||
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
|
||||
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
|
||||
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
|
||||
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
|
||||
}
|
||||
root = await checkedRoot(record);
|
||||
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
|
||||
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
|
||||
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
|
||||
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
|
||||
}
|
||||
} else if (restoreStock) {
|
||||
root = await checkedRoot(record);
|
||||
if (!(await canRestoreStock(record, root))) {
|
||||
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
|
||||
}
|
||||
}
|
||||
|
||||
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
|
||||
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
||||
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
|
||||
if (deleteData) {
|
||||
const rawRoot = resolve(record.copyPath);
|
||||
const overlapsSource = source !== null && pathsOverlap(data, source);
|
||||
const containsCopy = deleteFiles
|
||||
? relative(data, root) !== '' && copyPathContains(data, root)
|
||||
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
|
||||
if (overlapsSource || containsCopy) {
|
||||
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
|
||||
}
|
||||
}
|
||||
|
||||
report('applying');
|
||||
const fsPromises = rawFs().promises;
|
||||
if (restoreStock) {
|
||||
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
|
||||
} else if (deleteFiles) {
|
||||
if (!deleteData && copyPathContains(root, data)) {
|
||||
await removeExcept(root, data);
|
||||
} else {
|
||||
await fsPromises.rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
|
||||
await fsPromises.rm(data, { recursive: true, force: true });
|
||||
}
|
||||
return removeCopyRecord(record.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
|
||||
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
|
||||
*/
|
||||
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
|
||||
const fsPromises = rawFs().promises;
|
||||
const backup = await requireStockBackupLocation(root);
|
||||
await changeCopyFiles(root, async (incoming) => {
|
||||
const files = Object.values(GAME_FILES);
|
||||
for (const file of files) {
|
||||
const sourceFile = join(backup, file);
|
||||
if (!(await fileInfo(sourceFile))?.isFile()) {
|
||||
failLocation('stock_backup_source_missing', { root, file, sourceFile });
|
||||
}
|
||||
const targetFile = join(incoming, file);
|
||||
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
|
||||
await fsPromises.copyFile(sourceFile, targetFile);
|
||||
}
|
||||
return { replace: files, remove: [] };
|
||||
}, async () => undefined);
|
||||
|
||||
const exeDir = dirname(GAME_FILES.executable);
|
||||
for (const name of OFFLINE_HOOK_FILES) {
|
||||
const hookFile = await stagedPath(root, join(exeDir, name));
|
||||
const info = await fileInfo(hookFile);
|
||||
if (info && !info.isDirectory()) {
|
||||
await fsPromises.rm(hookFile, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
|
||||
const wtofflineInfo = await fileInfo(wtofflineFolder);
|
||||
if (wtofflineInfo?.isDirectory()) {
|
||||
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
|
||||
await removeExcept(wtofflineFolder, data);
|
||||
} else {
|
||||
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pathsOverlap(left: string, right: string): boolean {
|
||||
return copyPathContains(left, right) || copyPathContains(right, left);
|
||||
}
|
||||
|
||||
/** Keep the data folder in place when it was chosen inside this copy. */
|
||||
async function removeExcept(folder: string, kept: string): Promise<void> {
|
||||
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
|
||||
const fsPromises = rawFs().promises;
|
||||
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (copyPathContains(path, kept)) {
|
||||
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
||||
await removeExcept(path, kept);
|
||||
} else {
|
||||
await fsPromises.rm(path, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
|
||||
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { GameFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
|
||||
@@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
||||
needsStockSource = hasMarkerFile || liveExePatched;
|
||||
}
|
||||
}
|
||||
const [clientMarker, hasHardlinkedResources] = await Promise.all([
|
||||
readClientMarker(resolved),
|
||||
detectHardlinkedResources(resolved),
|
||||
]);
|
||||
return {
|
||||
path,
|
||||
resolvedPath: resolved,
|
||||
@@ -70,6 +75,8 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
||||
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
|
||||
hasOfflineBackup,
|
||||
needsStockSource,
|
||||
clientOrigin: clientMarker?.origin ?? null,
|
||||
hasHardlinkedResources,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { join } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
import { hardlinkResourceRules, isHardlinkableResource } from '@wto/patcher';
|
||||
import { ClientOriginSchema, type ClientOrigin } from '@shared/schemas/install.ts';
|
||||
import { writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
import { rawFs } from '../../util/raw-fs.ts';
|
||||
|
||||
/** Relative path of the self-describing client identity marker inside a client folder. */
|
||||
export const CLIENT_MARKER_FILE = join('wtoffline', 'client.json');
|
||||
|
||||
export const ClientMarkerSchema = z.object({
|
||||
format: z.literal(1),
|
||||
origin: ClientOriginSchema,
|
||||
createdBy: z.literal('wtoffline-launcher'),
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1).optional(),
|
||||
});
|
||||
export type ClientMarker = z.output<typeof ClientMarkerSchema>;
|
||||
|
||||
/** Cap on qualifying resource files inspected when sampling for hard links. */
|
||||
const MAX_RESOURCE_SAMPLES = 64;
|
||||
|
||||
export function clientMarkerPath(copyFolder: string): string {
|
||||
return join(copyFolder, CLIENT_MARKER_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely read and validate `<copyFolder>/wtoffline/client.json`.
|
||||
* Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing.
|
||||
*/
|
||||
export async function readClientMarker(copyFolder: string): Promise<ClientMarker | null> {
|
||||
try {
|
||||
const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8');
|
||||
const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown);
|
||||
return parsed.success ? parsed.data : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically write `<copyFolder>/wtoffline/client.json`.
|
||||
* Preserves `createdAt` and records `updatedAt` when updating an existing valid marker.
|
||||
*/
|
||||
export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise<ClientMarker> {
|
||||
const existing = await readClientMarker(copyFolder);
|
||||
const now = new Date().toISOString();
|
||||
const marker: ClientMarker = existing
|
||||
? {
|
||||
format: 1,
|
||||
origin,
|
||||
createdBy: 'wtoffline-launcher',
|
||||
createdAt: existing.createdAt,
|
||||
updatedAt: now,
|
||||
}
|
||||
: {
|
||||
format: 1,
|
||||
origin,
|
||||
createdBy: 'wtoffline-launcher',
|
||||
createdAt: now,
|
||||
};
|
||||
await writeJsonAtomic(clientMarkerPath(copyFolder), marker);
|
||||
return marker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight probe for hard-linked read-only resource packs under allowed content directories.
|
||||
* Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on
|
||||
* missing/unreadable directories or when no sampled resource is hard-linked.
|
||||
*/
|
||||
export async function detectHardlinkedResources(copyFolder: string): Promise<boolean> {
|
||||
const fsPromises = rawFs().promises;
|
||||
const rules = hardlinkResourceRules();
|
||||
const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => {
|
||||
const clean = dir.replace(/\/+$/, '');
|
||||
return { absDir: join(copyFolder, clean), relDir: clean };
|
||||
});
|
||||
let sampled = 0;
|
||||
|
||||
while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) {
|
||||
const current = queue.shift()!;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fsPromises.readdir(current.absDir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.isSymbolicLink()) continue;
|
||||
const absPath = join(current.absDir, entry.name);
|
||||
const relPath = `${current.relDir}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
queue.push({ absDir: absPath, relDir: relPath });
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
|
||||
const lower = entry.name.toLowerCase();
|
||||
if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue;
|
||||
|
||||
try {
|
||||
const stats = await fsPromises.lstat(absPath);
|
||||
if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue;
|
||||
if (stats.nlink >= 2) return true;
|
||||
sampled += 1;
|
||||
if (sampled >= MAX_RESOURCE_SAMPLES) return false;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -68,6 +68,12 @@ export interface CopyPlan {
|
||||
export interface CopyProgress {
|
||||
readonly doneBytes: number;
|
||||
readonly doneFiles: number;
|
||||
/** Bytes actually written to disk so far (excludes hard-linked files). */
|
||||
readonly copiedBytes: number;
|
||||
/** Bytes shared via hard links so far (occupies no extra disk space). */
|
||||
readonly linkedBytes: number;
|
||||
/** Number of hard-linked files created so far. */
|
||||
readonly linkedFiles: number;
|
||||
}
|
||||
|
||||
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
|
||||
@@ -129,12 +135,19 @@ export async function copyPlannedFiles(
|
||||
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
|
||||
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
||||
let next = 0;
|
||||
let doneBytes = 0;
|
||||
let copiedBytes = 0;
|
||||
let linkedBytes = 0;
|
||||
let linkedFiles = 0;
|
||||
let doneFiles = 0;
|
||||
const emitProgress = (): void => {
|
||||
// Keep doneBytes aligned with actual bytes written to disk so hard-linked files
|
||||
// do not inflate copy progress.
|
||||
onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles });
|
||||
};
|
||||
const countBytes = (): Transform => new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
doneBytes += chunk.length;
|
||||
onProgress({ doneBytes, doneFiles });
|
||||
copiedBytes += chunk.length;
|
||||
emitProgress();
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
@@ -155,7 +168,8 @@ export async function copyPlannedFiles(
|
||||
if (verified) {
|
||||
const linked = await linkVerifiedResource(from, to, verified);
|
||||
linkedTargets?.set(to, linked);
|
||||
doneBytes += file.bytes;
|
||||
linkedBytes += file.bytes;
|
||||
linkedFiles += 1;
|
||||
} else {
|
||||
await pipeline(
|
||||
fs.createReadStream(from),
|
||||
@@ -168,7 +182,7 @@ export async function copyPlannedFiles(
|
||||
await fsPromises.utimes(to, modified, modified);
|
||||
}
|
||||
doneFiles += 1;
|
||||
onProgress({ doneBytes, doneFiles });
|
||||
emitProgress();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!hasError && !stop.signal.aborted && !signal.aborted) {
|
||||
|
||||
@@ -1,6 +1,31 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { DataFolderProblem } from '@shared/schemas/install.ts';
|
||||
import { copyPathContains } from './install-record.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
|
||||
export async function requireUnredirectedData(root: string): Promise<void> {
|
||||
|
||||
@@ -22,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
|
||||
return join(dataPath, CACHE_FOLDER, cacheId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
|
||||
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
|
||||
* valid, or null when absent, invalid, or unreadable.
|
||||
*/
|
||||
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
|
||||
if (!folderPath || !isAbsolute(folderPath)) return null;
|
||||
try {
|
||||
const rawSource = await realpath(folderPath).catch(() => null);
|
||||
if (!rawSource) return null;
|
||||
const resolved = resolvePlayerDecalCacheFolder(rawSource);
|
||||
const canonical = await realpath(resolved).catch(() => null);
|
||||
if (!canonical) return null;
|
||||
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
|
||||
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
|
||||
const data = await canonicalCopyPath(dataPath);
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, type BigIntStats } from 'node:fs';
|
||||
import { link, lstat } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { isHardlinkableResource } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallProgress } from '@shared/schemas/install.ts';
|
||||
import type { CopyPlan } from './copy-game.ts';
|
||||
|
||||
export type ResourceMatchResult =
|
||||
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
|
||||
@@ -83,3 +87,27 @@ function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean
|
||||
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
|
||||
left.size === right.size && left.mtimeNs === right.mtimeNs;
|
||||
}
|
||||
|
||||
/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */
|
||||
export async function prepareHardlinks(
|
||||
source: string,
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
||||
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
||||
const links = new Map<string, BigIntStats>();
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
for (const file of candidates) {
|
||||
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
||||
if (verified) links.set(file.relativePath, verified);
|
||||
doneBytes += file.bytes;
|
||||
doneFiles += 1;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
}
|
||||
if (!links.size) throw new AppError('hardlink_no_match');
|
||||
return links;
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { access, mkdir } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative } from 'node:path';
|
||||
import { dirname, isAbsolute, relative } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
|
||||
import type { ClientOrigin, 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 { readClientMarker, writeClientMarker } from './client-marker.ts';
|
||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
|
||||
import { dataFolderProblem, requireUnredirectedData } from './data-location.ts';
|
||||
import { discardDecalCache, importDecalCache } from './decals.ts';
|
||||
import { statHardlinkResource } from './hardlink-files.ts';
|
||||
import { prepareHardlinks } from './hardlink-files.ts';
|
||||
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { checkPatches } from './patch-check.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts';
|
||||
|
||||
export { dataFolderProblem } from './data-location.ts';
|
||||
|
||||
/**
|
||||
* Install the offline version: check the patches against the player's game,
|
||||
@@ -101,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
? await refreshStockBackup(copyPath)
|
||||
: await backUpStockFiles(copyPath);
|
||||
|
||||
// Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders.
|
||||
let detectedOrigin: ClientOrigin | undefined;
|
||||
if (request.method === 'copy') {
|
||||
await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy');
|
||||
} else if (request.method === 'in-place') {
|
||||
await writeClientMarker(copyPath, 'in-place');
|
||||
} else {
|
||||
detectedOrigin = (await readClientMarker(copyPath))?.origin;
|
||||
}
|
||||
|
||||
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const record: InstallRecord = {
|
||||
id: request.id,
|
||||
@@ -116,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
installedAt: new Date().toISOString(),
|
||||
lastCheckedAt: new Date().toISOString(),
|
||||
...(decalCacheId ? { decalCacheId } : {}),
|
||||
...(detectedOrigin ? { detectedOrigin } : {}),
|
||||
...copied,
|
||||
};
|
||||
await writeInstallRecord(record);
|
||||
@@ -176,28 +189,6 @@ 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');
|
||||
@@ -219,8 +210,10 @@ async function copyGame(
|
||||
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const plan = await planCopy(source);
|
||||
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
|
||||
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
||||
const linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||
const linkTotalFiles = hardlinks ? hardlinks.size : 0;
|
||||
const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes);
|
||||
const neededBytes = copyTotalBytes + SPARE_BYTES;
|
||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
@@ -229,11 +222,26 @@ async function copyGame(
|
||||
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
||||
}
|
||||
const targetExisted = await exists(target);
|
||||
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
|
||||
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
|
||||
// Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives
|
||||
// do not inflate the progress bar or cause sudden jumps when links are created.
|
||||
const totals = {
|
||||
totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length,
|
||||
totalFiles: plan.files.length,
|
||||
copyTotalBytes,
|
||||
...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}),
|
||||
};
|
||||
const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({
|
||||
phase: 'copying',
|
||||
doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles,
|
||||
doneFiles: done.doneFiles,
|
||||
copiedBytes: done.copiedBytes,
|
||||
...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}),
|
||||
...totals,
|
||||
});
|
||||
report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 }));
|
||||
try {
|
||||
await copyPlannedFiles(source, target, plan, signal,
|
||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
||||
(done) => report(toProgress(done)), hardlinks);
|
||||
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
|
||||
return {
|
||||
sourceFiles: plan.files.map((file) => file.relativePath),
|
||||
@@ -248,29 +256,6 @@ async function copyGame(
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareHardlinks(
|
||||
source: string,
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
|
||||
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
|
||||
const links = new Map<string, BigIntStats>();
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
for (const file of candidates) {
|
||||
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
|
||||
if (verified) links.set(file.relativePath, verified);
|
||||
doneBytes += file.bytes;
|
||||
doneFiles += 1;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
}
|
||||
if (!links.size) throw new AppError('hardlink_no_match');
|
||||
return links;
|
||||
}
|
||||
|
||||
async function requireGameFolder(path: string) {
|
||||
const game = await inspectGameFolder(path);
|
||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
||||
|
||||
@@ -17,6 +17,7 @@ import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
|
||||
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
|
||||
import { getSettings, updateSettings } from '../config/settings-store.ts';
|
||||
import { listCopies } from '../install/install-record.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
@@ -236,8 +237,10 @@ export async function exportModPreset(
|
||||
if (!preset) throw new AppError('mods_preset_invalid');
|
||||
|
||||
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
|
||||
const defaultDir = await resolveDialogDefaultPath('mod-preset');
|
||||
const fileName = `${safeName}.wto-mods-preset.json`;
|
||||
const dialogOptions = {
|
||||
defaultPath: `${safeName}.wto-mods-preset.json`,
|
||||
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
|
||||
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||
};
|
||||
const choice = window
|
||||
@@ -252,6 +255,7 @@ export async function exportModPreset(
|
||||
enabled: { ...preset.enabled },
|
||||
};
|
||||
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
||||
await rememberDialogPath('mod-preset', choice.filePath);
|
||||
return { path: choice.filePath };
|
||||
}
|
||||
|
||||
@@ -260,9 +264,11 @@ export async function importModPreset(
|
||||
window: BrowserWindow | null,
|
||||
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const defaultPath = await resolveDialogDefaultPath('mod-preset');
|
||||
const dialogOptions = {
|
||||
properties: ['openFile'] as Array<'openFile'>,
|
||||
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
|
||||
...(defaultPath ? { defaultPath } : {}),
|
||||
};
|
||||
const choice = window
|
||||
? await dialog.showOpenDialog(window, dialogOptions)
|
||||
@@ -270,6 +276,7 @@ export async function importModPreset(
|
||||
if (choice.canceled || !choice.filePaths[0]) {
|
||||
return { imported: false, state: await buildModsStateView(copy) };
|
||||
}
|
||||
await rememberDialogPath('mod-preset', choice.filePaths[0]);
|
||||
|
||||
let parsedRaw: unknown;
|
||||
try {
|
||||
@@ -309,6 +316,7 @@ export async function setModsFolder(copyId: string, folderPath: string | null):
|
||||
}
|
||||
}
|
||||
await updateSettings({ modsFolder: folderPath });
|
||||
if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath);
|
||||
const copy = await requireCopy(copyId);
|
||||
return buildModsStateView(copy);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
||||
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
|
||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
@@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
|
||||
}
|
||||
|
||||
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
|
||||
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
|
||||
const defaultPath = await resolveDialogDefaultPath('save-archive');
|
||||
const options = {
|
||||
properties: ['openFile' as const],
|
||||
filters: [{ name: 'ZIP', extensions: ['zip'] }],
|
||||
...(defaultPath ? { defaultPath } : {}),
|
||||
};
|
||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||
return { path: result.canceled ? null : result.filePaths[0] ?? null };
|
||||
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
|
||||
if (chosen) await rememberDialogPath('save-archive', chosen);
|
||||
return { path: chosen };
|
||||
}
|
||||
|
||||
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
|
||||
const copy = await requireCopy(copyId);
|
||||
await getSaveDetails(copyId, userId);
|
||||
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
|
||||
const defaultDir = await resolveDialogDefaultPath('save-archive');
|
||||
const fileName = `WTOffline-save-${userId}.zip`;
|
||||
const options = {
|
||||
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
|
||||
filters: [{ name: 'ZIP', extensions: ['zip'] }],
|
||||
};
|
||||
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
|
||||
if (result.canceled || !result.filePath) return { path: null };
|
||||
try {
|
||||
@@ -113,6 +126,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser
|
||||
console.error('[saves] could not export the save:', error);
|
||||
throw new AppError('save_operation_failed');
|
||||
}
|
||||
await rememberDialogPath('save-archive', result.filePath);
|
||||
return { path: result.filePath };
|
||||
}
|
||||
|
||||
@@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId:
|
||||
}
|
||||
|
||||
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
|
||||
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
|
||||
const defaultPath = await resolveDialogDefaultPath('official-backups');
|
||||
const options = {
|
||||
properties: ['openFile' as const, 'multiSelections' as const],
|
||||
filters: [{ name: 'BLK', extensions: ['blk'] }],
|
||||
...(defaultPath ? { defaultPath } : {}),
|
||||
};
|
||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
if (result.canceled || result.filePaths.length === 0) return [];
|
||||
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
|
||||
return result.filePaths;
|
||||
}
|
||||
|
||||
export async function previewSelectedBackups(
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { stat } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
|
||||
|
||||
/**
|
||||
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
|
||||
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
|
||||
* behavior is never disrupted.
|
||||
*/
|
||||
|
||||
export type DialogPathCategory =
|
||||
| 'folder'
|
||||
| 'save-archive'
|
||||
| 'official-backups'
|
||||
| 'mods-folder'
|
||||
| 'mod-preset';
|
||||
|
||||
export interface DialogPathStore {
|
||||
resolveDialogDefaultPath(
|
||||
category: DialogPathCategory,
|
||||
explicitPath?: string | null,
|
||||
): Promise<string | undefined>;
|
||||
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
|
||||
}
|
||||
|
||||
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
|
||||
const LAST_KEY = 'last';
|
||||
const MAX_ANCESTOR_STEPS = 128;
|
||||
|
||||
/**
|
||||
* Resolve `candidate` to an existing directory:
|
||||
* - If it is an existing directory, return its normalized path.
|
||||
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
|
||||
* - Return `undefined` when no existing ancestor directory can be reached.
|
||||
*/
|
||||
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
|
||||
if (!candidate) return undefined;
|
||||
const trimmed = candidate.trim();
|
||||
if (!trimmed || !isAbsolute(trimmed)) return undefined;
|
||||
|
||||
let current = resolve(trimmed);
|
||||
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
|
||||
try {
|
||||
const info = await stat(current);
|
||||
if (info.isDirectory()) return current;
|
||||
} catch {
|
||||
// Missing or inaccessible path; continue walking toward the filesystem root.
|
||||
}
|
||||
const parent = dirname(current);
|
||||
if (parent === current) return undefined;
|
||||
current = parent;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
|
||||
export function createDialogPathStore(
|
||||
resolveStorePath: () => Promise<string | null> | string | null,
|
||||
): DialogPathStore {
|
||||
let cached: Map<string, string> | null = null;
|
||||
let loading: Promise<Map<string, string>> | null = null;
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
|
||||
async function loadMap(): Promise<Map<string, string>> {
|
||||
if (cached) return cached;
|
||||
if (loading) return loading;
|
||||
|
||||
loading = (async () => {
|
||||
const map = new Map<string, string>();
|
||||
const storePath = await resolveStorePath();
|
||||
if (storePath) {
|
||||
try {
|
||||
const raw = await readJsonOr(storePath, null);
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (typeof value === 'string' && value.trim().length > 0) {
|
||||
map.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[dialog-paths] failed to read dialog paths:', error);
|
||||
}
|
||||
}
|
||||
cached = map;
|
||||
return map;
|
||||
})().finally(() => {
|
||||
loading = null;
|
||||
});
|
||||
|
||||
return loading;
|
||||
}
|
||||
|
||||
return {
|
||||
async resolveDialogDefaultPath(
|
||||
category: DialogPathCategory,
|
||||
explicitPath?: string | null,
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const explicitDir = await resolveExistingDirectory(explicitPath);
|
||||
if (explicitDir) return explicitDir;
|
||||
|
||||
const map = await loadMap();
|
||||
const categoryPath = map.get(category);
|
||||
if (categoryPath) {
|
||||
const resolved = await resolveExistingDirectory(categoryPath);
|
||||
if (resolved) return resolved;
|
||||
}
|
||||
|
||||
const lastPath = map.get(LAST_KEY);
|
||||
if (lastPath && lastPath !== categoryPath) {
|
||||
const resolved = await resolveExistingDirectory(lastPath);
|
||||
if (resolved) return resolved;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
|
||||
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
|
||||
const dir = await resolveExistingDirectory(selectedPath);
|
||||
if (!dir) return;
|
||||
|
||||
const operation = pending.then(async () => {
|
||||
const map = await loadMap();
|
||||
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
|
||||
|
||||
map.set(category, dir);
|
||||
map.set(LAST_KEY, dir);
|
||||
|
||||
const storePath = await resolveStorePath();
|
||||
if (!storePath) return;
|
||||
try {
|
||||
await writeJsonAtomic(storePath, Object.fromEntries(map));
|
||||
} catch (error) {
|
||||
console.warn('[dialog-paths] failed to save dialog paths:', error);
|
||||
}
|
||||
});
|
||||
pending = operation.then(() => undefined, () => undefined);
|
||||
await operation;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function defaultStorePath(): Promise<string | null> {
|
||||
try {
|
||||
const mod = await import('electron') as {
|
||||
readonly app?: { getPath?: (name: 'userData') => string };
|
||||
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
|
||||
};
|
||||
const electronApp = mod.app ?? mod.default?.app;
|
||||
if (typeof electronApp?.getPath !== 'function') return null;
|
||||
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultStore = createDialogPathStore(defaultStorePath);
|
||||
|
||||
export function resolveDialogDefaultPath(
|
||||
category: DialogPathCategory,
|
||||
explicitPath?: string | null,
|
||||
): Promise<string | undefined> {
|
||||
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
|
||||
}
|
||||
|
||||
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
|
||||
return defaultStore.rememberDialogPath(category, selectedPath);
|
||||
}
|
||||
@@ -5,16 +5,22 @@ interface FolderFieldProps {
|
||||
readonly path: string | null;
|
||||
/** Title of the folder dialog. */
|
||||
readonly dialogTitle: string;
|
||||
/** Optional starting directory when no path is chosen yet. */
|
||||
readonly defaultPath?: string | null | undefined;
|
||||
readonly disabled?: boolean;
|
||||
readonly onChosen: (path: string) => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** A chosen folder and the button that opens the folder dialog. */
|
||||
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) {
|
||||
export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
const choose = (): void => {
|
||||
ipcInvoke('dialog:pickFolder', { title: dialogTitle })
|
||||
const startPath = path ?? defaultPath;
|
||||
ipcInvoke('dialog:pickFolder', {
|
||||
title: dialogTitle,
|
||||
...(startPath ? { defaultPath: startPath } : {}),
|
||||
})
|
||||
.then(({ path: chosen }) => {
|
||||
if (chosen) onChosen(chosen);
|
||||
})
|
||||
|
||||
@@ -97,7 +97,9 @@
|
||||
},
|
||||
"decals": {
|
||||
"source": "Decal source",
|
||||
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
|
||||
"hint": "Select the online game root folder, cache, or cache/content for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
|
||||
"autoDetectedNotice": "Online decal cache detected automatically and will be imported during installation. Click the button above if you prefer placeholder decals.",
|
||||
"importFromSource": "Import from online source",
|
||||
"choose": "Choose decal cache…",
|
||||
"useDefault": "Use placeholder decals",
|
||||
"importing": "Importing decal cache",
|
||||
@@ -158,7 +160,8 @@
|
||||
"copy": "Copy installation (recommended)",
|
||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||
"spaceSaving": "Space-saving copy",
|
||||
"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.",
|
||||
"spaceSavingBody": "Resource packs are shared with the online client via same-volume hard links, requiring only about {{size}} of additional copying. Windows Explorer Properties counts shared files toward both folders, but only the newly copied files use extra disk space. An in-place update to the online client can change shared files.",
|
||||
"spaceSavingBreakdown": "Estimated copy: about {{copy}} · Shared via hard links: about {{shared}} (no extra disk space)",
|
||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||
"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.",
|
||||
@@ -214,6 +217,8 @@
|
||||
"recording": "Finishing installation"
|
||||
},
|
||||
"copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"copiedActual": "Copied to disk: {{copied}} / {{copyTotal}} ({{copiedFiles}} / {{copyTotalFiles}} files)",
|
||||
"linkedShared": "Shared via hard links (no extra space): {{linked}} / {{linkTotal}} ({{linkedFiles}} / {{linkTotalFiles}} resource packs)",
|
||||
"verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"cancelHint": "Can be cancelled at any time; copied files will be deleted",
|
||||
@@ -258,16 +263,31 @@
|
||||
"repair": "Repair client",
|
||||
"repairAction": "Repair",
|
||||
"repairHint": "Restore the original files from the backup. Game files will be generated again at launch.",
|
||||
"delete": "Delete client",
|
||||
"deleteAction": "Delete…",
|
||||
"deleteHint": "The data folder is kept by default.",
|
||||
"unlink": "Remove registration",
|
||||
"unlinkAction": "Remove…",
|
||||
"unlinkHint": "The launcher keeps the Steam game files and data folder in place.",
|
||||
"unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.",
|
||||
"deleteLocation": "Delete the offline client at {{path}}?",
|
||||
"deleteData": "Also delete the data folder at {{path}}",
|
||||
"confirm": "Confirm deletion",
|
||||
"remove": "Remove client",
|
||||
"removeAction": "Remove…",
|
||||
"removeCopyHint": "Removes from the launcher list by default without deleting files on disk.",
|
||||
"removeRestoreHint": "Removes from the launcher list by default; optionally restores original files and removes offline patch files while keeping the base game.",
|
||||
"removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.",
|
||||
"removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.",
|
||||
"removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.",
|
||||
"removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.",
|
||||
"removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.",
|
||||
"originCopy": "Detected client type: full copy (created as an independent copy by the launcher).",
|
||||
"originHardlink": "Detected client type: space-saving hard-linked copy (read-only resource packs are shared; deleting this copy does not affect the original game folder).",
|
||||
"originInPlace": "Detected client type: in-place installation (full folder deletion is disabled to protect the base game).",
|
||||
"originUnknown": "Detected client type: existing folder of unknown origin (no client identity marker found; full folder deletion is disabled for safety).",
|
||||
"originUnknownHardlinked": "Detected client type: existing folder of unknown origin (hard-linked resources were detected without a client identity marker; full folder deletion is disabled for safety).",
|
||||
"deleteFiles": "Also delete the client folder at {{path}}",
|
||||
"deleteHardlinkHint": "Note: This client shares read-only resource packs via hard links; deleting the copy folder will not affect the original game folder.",
|
||||
"deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.",
|
||||
"deleteHardlinkWarning": "This will permanently delete all files in the hard-linked copy folder at {{path}} (the original game folder is unaffected). This action cannot be undone.",
|
||||
"restoreStock": "Restore original files and remove offline patch files (keep base game)",
|
||||
"restoreStockHint": "Restores the 4 original core files from wtoffline\\stock and removes wtoffline\\ along with network hook files (wto_ws.dll / wto_ws.cfg / wto_ws.log). No base game files are deleted.",
|
||||
"deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)",
|
||||
"openFolder": "Open folder",
|
||||
"confirmRemove": "Remove from list",
|
||||
"confirmRestore": "Restore and remove",
|
||||
"confirmDelete": "Confirm deletion",
|
||||
"phase": {
|
||||
"checking": "Checking the client",
|
||||
"copying": "Copying changed files",
|
||||
@@ -280,7 +300,7 @@
|
||||
"repair": "Original files restored.",
|
||||
"update": "Client updated.",
|
||||
"compact": "Space-saving conversion complete.",
|
||||
"delete": "Client deleted.",
|
||||
"delete": "Client removed.",
|
||||
"cancelled": "Maintenance cancelled."
|
||||
}
|
||||
},
|
||||
@@ -1118,7 +1138,7 @@
|
||||
"copy_not_found": "The selected client is no longer available.",
|
||||
"copies_write_failed": "The client registry could not be saved.",
|
||||
"copy_location_in_use": "The client or data location overlaps an existing client.",
|
||||
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).",
|
||||
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose the online game root folder, cache, or cache/content.",
|
||||
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
|
||||
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
|
||||
"maintenance_location": "The operation would affect files outside the registered client or data folder.",
|
||||
|
||||
@@ -97,7 +97,9 @@
|
||||
},
|
||||
"decals": {
|
||||
"source": "贴花来源",
|
||||
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
|
||||
"hint": "可直接选择在线版游戏根目录、cache 或 cache/content,同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
|
||||
"autoDetectedNotice": "已自动检测到在线版贴花缓存,安装时将一并导入。如需使用占位贴花,可点击上方按钮取消。",
|
||||
"importFromSource": "从在线版来源导入",
|
||||
"choose": "选择贴花缓存…",
|
||||
"useDefault": "使用占位贴花",
|
||||
"importing": "正在导入贴花缓存",
|
||||
@@ -158,7 +160,8 @@
|
||||
"copy": "复制安装(推荐)",
|
||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||
"spaceSaving": "节省空间的复制",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingBody": "资源包通过同盘硬链接与在线版共享,仅需额外复制约 {{size}};Windows 资源管理器「属性」会重复统计共享文件大小,实际只占新增复制的磁盘空间。原版就地更新可能改变共享文件。",
|
||||
"spaceSavingBreakdown": "预计实际复制约 {{copy}} · 硬链接共享约 {{shared}}(不额外占用磁盘空间)",
|
||||
"spaceSavingPending": "正在估算可节省的空间。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
|
||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||
@@ -214,6 +217,8 @@
|
||||
"recording": "完成安装"
|
||||
},
|
||||
"copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"copiedActual": "实际复制:已复制 {{copied}} / {{copyTotal}}({{copiedFiles}} / {{copyTotalFiles}} 个文件)",
|
||||
"linkedShared": "硬链接共享(不额外占空间):已链接共享 {{linked}} / {{linkTotal}}({{linkedFiles}} / {{linkTotalFiles}} 个资源包)",
|
||||
"verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"cancelHint": "可随时取消,已复制的文件将被删除",
|
||||
@@ -258,16 +263,31 @@
|
||||
"repair": "修复客户端",
|
||||
"repairAction": "修复",
|
||||
"repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。",
|
||||
"delete": "删除客户端",
|
||||
"deleteAction": "删除…",
|
||||
"deleteHint": "默认保留数据目录。",
|
||||
"unlink": "解除登记",
|
||||
"unlinkAction": "解除登记…",
|
||||
"unlinkHint": "Steam 游戏文件和数据目录将留在原处。",
|
||||
"unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。",
|
||||
"deleteLocation": "确认删除 {{path}} 中的离线客户端?",
|
||||
"deleteData": "同时删除 {{path}} 中的数据",
|
||||
"confirm": "确认删除",
|
||||
"remove": "移除客户端",
|
||||
"removeAction": "移除…",
|
||||
"removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。",
|
||||
"removeRestoreHint": "默认仅从启动器列表移除;也可选还原为原版并清理离线补丁文件(保留游戏本体)。",
|
||||
"removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。",
|
||||
"removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。",
|
||||
"removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。",
|
||||
"removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。",
|
||||
"removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。",
|
||||
"originCopy": "识别结果:完整复制副本(由启动器独立复制创建)。",
|
||||
"originHardlink": "识别结果:省空间硬链接副本(只读资源包与原版共享,删除副本不会影响原版游戏目录)。",
|
||||
"originInPlace": "识别结果:原位安装目录(为保护原版游戏本体,不支持直接删除整个文件夹)。",
|
||||
"originUnknown": "识别结果:未知来源的已有目录(缺少客户端身份标记,为保护游戏文件不支持直接删除整个文件夹)。",
|
||||
"originUnknownHardlinked": "识别结果:未知来源的已有目录(检测到硬链接资源包,但缺少客户端身份标记;为保护原版目录不支持直接删除整个文件夹)。",
|
||||
"deleteFiles": "同时删除客户端文件夹 {{path}}",
|
||||
"deleteHardlinkHint": "提示:此客户端使用同盘硬链接共享资源包,删除副本文件夹不会影响原版游戏目录。",
|
||||
"deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。",
|
||||
"deleteHardlinkWarning": "将永久删除硬链接副本文件夹 {{path}} 中的全部文件(不会影响原版游戏目录),此操作无法撤销。",
|
||||
"restoreStock": "还原为原版并清理离线补丁文件(保留游戏本体)",
|
||||
"restoreStockHint": "将从 wtoffline\\stock 恢复原版 4 个核心文件,并删除 wtoffline\\ 目录与网络钩子文件(wto_ws.dll / wto_ws.cfg / wto_ws.log),绝不删除其他游戏本体文件。",
|
||||
"deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)",
|
||||
"openFolder": "打开所在文件夹",
|
||||
"confirmRemove": "从列表移除",
|
||||
"confirmRestore": "还原并移除",
|
||||
"confirmDelete": "确认删除",
|
||||
"phase": {
|
||||
"checking": "正在检查客户端",
|
||||
"copying": "正在复制有变化的文件",
|
||||
@@ -280,7 +300,7 @@
|
||||
"repair": "原版文件已还原。",
|
||||
"update": "客户端已更新。",
|
||||
"compact": "省空间转换已完成。",
|
||||
"delete": "客户端已删除。",
|
||||
"delete": "客户端已移除。",
|
||||
"cancelled": "维护已取消。"
|
||||
}
|
||||
},
|
||||
@@ -1118,7 +1138,7 @@
|
||||
"copy_not_found": "所选客户端已不可用。",
|
||||
"copies_write_failed": "无法保存客户端记录。",
|
||||
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
|
||||
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
|
||||
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版游戏根目录、cache 或 cache/content。",
|
||||
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
|
||||
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
|
||||
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
|
||||
|
||||
@@ -20,6 +20,10 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
||||
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
|
||||
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setRemoval(null);
|
||||
}, [record.id]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
setInfo(null);
|
||||
@@ -60,7 +64,8 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
|
||||
busy={busy}
|
||||
options={removal}
|
||||
onOptionsChange={setRemoval}
|
||||
onRemove={(deleteData) => run('delete', { deleteData })}
|
||||
onRemove={(options) => run('delete', options)}
|
||||
onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }}
|
||||
/>
|
||||
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
|
||||
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
|
||||
|
||||
@@ -69,44 +69,112 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSour
|
||||
}
|
||||
|
||||
export interface CopyRemovalOptions {
|
||||
readonly deleteFiles: boolean;
|
||||
readonly restoreStock: boolean;
|
||||
readonly deleteData: boolean;
|
||||
}
|
||||
|
||||
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
|
||||
readonly options: CopyRemovalOptions | null;
|
||||
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
|
||||
readonly onRemove: (deleteData: boolean) => void;
|
||||
readonly onRemove: (options: CopyRemovalOptions) => void;
|
||||
readonly onOpenFolder: () => void;
|
||||
}
|
||||
|
||||
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) {
|
||||
function clientOriginNoteKey(info: MaintenanceInfo): string {
|
||||
if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy';
|
||||
if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink';
|
||||
if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace';
|
||||
return info.hasHardlinkedResources
|
||||
? 'copies.maintenance.originUnknownHardlinked'
|
||||
: 'copies.maintenance.originUnknown';
|
||||
}
|
||||
|
||||
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) {
|
||||
const { t } = useTranslation();
|
||||
const steam = info?.steamLocations;
|
||||
const unlinkOnly = steam?.copyInSteam === true;
|
||||
const canDeleteData = !unlinkOnly && !steam?.dataInSteam;
|
||||
const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm');
|
||||
const copyInSteam = steam?.copyInSteam === true;
|
||||
const dataInSteam = steam?.dataInSteam === true;
|
||||
const canDeleteFiles = info?.canDeleteFiles === true;
|
||||
const isHardlinkCopy = info?.clientOrigin === 'hardlink';
|
||||
const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove;
|
||||
const canDeleteData = info !== null && !copyInSteam && !dataInSteam;
|
||||
const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true;
|
||||
const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true;
|
||||
const willDeleteData = canDeleteData && options?.deleteData === true;
|
||||
const action = t(
|
||||
willDeleteFiles || willDeleteData
|
||||
? 'copies.maintenance.confirmDelete'
|
||||
: willRestoreStock
|
||||
? 'copies.maintenance.confirmRestore'
|
||||
: 'copies.maintenance.confirmRemove',
|
||||
);
|
||||
const rowHint = copyInSteam
|
||||
? t('copies.maintenance.removeSteamHint')
|
||||
: canDeleteFiles
|
||||
? t('copies.maintenance.removeCopyHint')
|
||||
: canRestoreAndRemove
|
||||
? t('copies.maintenance.removeRestoreHint')
|
||||
: t('copies.maintenance.removeUnlinkHint');
|
||||
const confirmNotice = copyInSteam
|
||||
? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath })
|
||||
: canDeleteFiles
|
||||
? t('copies.maintenance.removeCopyNotice', { path: record.copyPath })
|
||||
: t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath });
|
||||
|
||||
return (
|
||||
<>
|
||||
<Row label={t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.delete')}
|
||||
hint={t(unlinkOnly ? 'copies.maintenance.unlinkHint' : 'copies.maintenance.deleteHint')}>
|
||||
<button type="button" className="button" disabled={busy || !info}
|
||||
onClick={() => onOptionsChange({ deleteData: false })}>
|
||||
{t(unlinkOnly ? 'copies.maintenance.unlinkAction' : 'copies.maintenance.deleteAction')}
|
||||
<Row label={t('copies.maintenance.remove')} hint={rowHint}>
|
||||
<button type="button" className="button" disabled={busy}
|
||||
onClick={() => onOptionsChange({ deleteFiles: false, restoreStock: false, deleteData: false })}>
|
||||
{t('copies.maintenance.removeAction')}
|
||||
</button>
|
||||
</Row>
|
||||
{options && (
|
||||
<section className="maintenance-confirm" role="group" aria-label={action}>
|
||||
<p>{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}</p>
|
||||
<p>{confirmNotice}</p>
|
||||
{info && <p className="small">{t(clientOriginNoteKey(info))}</p>}
|
||||
{canDeleteFiles && (
|
||||
<>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={options.deleteFiles} disabled={busy}
|
||||
onChange={(event) => onOptionsChange({ ...options, deleteFiles: event.target.checked, restoreStock: false })} />
|
||||
{t('copies.maintenance.deleteFiles', { path: record.copyPath })}
|
||||
</label>
|
||||
{isHardlinkCopy && <p className="small">{t('copies.maintenance.deleteHardlinkHint')}</p>}
|
||||
</>
|
||||
)}
|
||||
{willDeleteFiles && (
|
||||
<Notice tone="warning">
|
||||
<p>{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}</p>
|
||||
</Notice>
|
||||
)}
|
||||
{canRestoreAndRemove && (
|
||||
<>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={options.restoreStock} disabled={busy}
|
||||
onChange={(event) => onOptionsChange({ ...options, restoreStock: event.target.checked, deleteFiles: false })} />
|
||||
{t('copies.maintenance.restoreStock')}
|
||||
</label>
|
||||
<p className="small">{t('copies.maintenance.restoreStockHint')}</p>
|
||||
</>
|
||||
)}
|
||||
{canDeleteData && (
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={options.deleteData} disabled={busy}
|
||||
onChange={(event) => onOptionsChange({ deleteData: event.target.checked })} />
|
||||
onChange={(event) => onOptionsChange({ ...options, deleteData: event.target.checked })} />
|
||||
{t('copies.maintenance.deleteData', { path: record.dataPath })}
|
||||
</label>
|
||||
)}
|
||||
<div className="copy-list-actions">
|
||||
{!canDeleteFiles && (
|
||||
<button type="button" className="button" disabled={busy || record.folderMissing === true} onClick={onOpenFolder}>
|
||||
{t('copies.maintenance.openFolder')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
|
||||
<button type="button" className="button button-primary" disabled={busy} onClick={() => onRemove(canDeleteData && options.deleteData)}>
|
||||
<button type="button" className="button button-primary" disabled={busy}
|
||||
onClick={() => onRemove({ deleteFiles: willDeleteFiles, restoreStock: willRestoreStock, deleteData: willDeleteData })}>
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
|
||||
const { t, i18n } = useTranslation();
|
||||
const [name, setName] = useState(record.name);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [detectedSourceDecals, setDetectedSourceDecals] = useState<string | null>(null);
|
||||
useEffect(() => setName(record.name), [record.id, record.name]);
|
||||
// Read-only probe of the copy's registered online source for a usable decal cache.
|
||||
useEffect(() => {
|
||||
setDetectedSourceDecals(null);
|
||||
if (!record.sourcePath) return;
|
||||
let current = true;
|
||||
ipcInvoke('decals:detectSource', { path: record.sourcePath })
|
||||
.then(({ path }) => {
|
||||
if (current) setDetectedSourceDecals(path);
|
||||
})
|
||||
.catch(() => {
|
||||
if (current) setDetectedSourceDecals(null);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [record.id, record.sourcePath]);
|
||||
const missing = missingFeatures(record).length;
|
||||
const verified = isVerified(record.gameVersion, supportedVersions);
|
||||
const importFromSource = async (): Promise<void> => {
|
||||
if (!detectedSourceDecals) return;
|
||||
setImporting(true);
|
||||
try {
|
||||
await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals });
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
const applyDecals = async (chooseFolder: boolean): Promise<void> => {
|
||||
setImporting(true);
|
||||
try {
|
||||
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null;
|
||||
const path = chooseFolder
|
||||
? (await ipcInvoke('dialog:pickFolder', {
|
||||
title: t('decals.choose'),
|
||||
...(record.sourcePath ? { defaultPath: record.sourcePath } : {}),
|
||||
})).path
|
||||
: null;
|
||||
if (chooseFolder && path === null) return;
|
||||
await ipcInvoke('copies:setDecalSource', { id: record.id, path });
|
||||
} catch (error) {
|
||||
@@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
|
||||
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
|
||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
|
||||
{detectedSourceDecals && (
|
||||
<button type="button" className="button" disabled={importing} onClick={() => { void importFromSource(); }}>
|
||||
{t('decals.importFromSource')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
|
||||
{t('decals.choose')}
|
||||
</button>
|
||||
|
||||
@@ -4,7 +4,10 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
|
||||
|
||||
export type MaintenanceOperation = MaintenanceRequest['operation'];
|
||||
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations' | 'sourcePath'>;
|
||||
export type MaintenanceOptions = Pick<
|
||||
IpcInput<'copies:maintain'>,
|
||||
'deleteFiles' | 'restoreStock' | 'deleteData' | 'steamLocations' | 'sourcePath'
|
||||
>;
|
||||
|
||||
export interface MaintenanceOutcome {
|
||||
readonly copyId: string;
|
||||
|
||||
@@ -8,6 +8,8 @@ interface DataStepProps {
|
||||
readonly dataPath: string;
|
||||
readonly dataProblem: DataFolderProblem | null;
|
||||
readonly decalSource: string | null;
|
||||
readonly decalAutoDetected: boolean;
|
||||
readonly defaultDecalPath?: string | null | undefined;
|
||||
readonly steamDataPath: string | null;
|
||||
readonly steamDataConfirmed: boolean;
|
||||
readonly onSteamDataConfirmed: (confirmed: boolean) => void;
|
||||
@@ -17,7 +19,19 @@ interface DataStepProps {
|
||||
}
|
||||
|
||||
/** Step 3: where saves, caches and logs of the offline version are kept. */
|
||||
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
|
||||
export function DataStep({
|
||||
dataPath,
|
||||
dataProblem,
|
||||
decalSource,
|
||||
decalAutoDetected,
|
||||
defaultDecalPath,
|
||||
steamDataPath,
|
||||
steamDataConfirmed,
|
||||
onSteamDataConfirmed,
|
||||
onDataPath,
|
||||
onDecalSource,
|
||||
onError,
|
||||
}: DataStepProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
@@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st
|
||||
</Notice>
|
||||
)}
|
||||
<Row label={t('decals.source')} hint={t('decals.hint')}>
|
||||
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} />
|
||||
<FolderField
|
||||
path={decalSource}
|
||||
defaultPath={defaultDecalPath}
|
||||
dialogTitle={t('decals.choose')}
|
||||
onChosen={onDecalSource}
|
||||
onError={onError}
|
||||
/>
|
||||
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
|
||||
</Row>
|
||||
{decalAutoDetected && decalSource && <Notice tone="info">{t('decals.autoDetectedNotice')}</Notice>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
|
||||
: t('method.spaceSavingPending')}
|
||||
onSelect={() => choose('hardlink')}
|
||||
>
|
||||
{sourceSize && savingAvailable && (
|
||||
<p className="small">
|
||||
{t('method.spaceSavingBreakdown', {
|
||||
copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')),
|
||||
shared: formatBytes(sourceSize.linkableBytes ?? 0),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{targetPicker}
|
||||
</Choice>
|
||||
<Choice
|
||||
|
||||
@@ -19,6 +19,27 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
||||
const current = phases.indexOf(phase);
|
||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
|
||||
const hardlinkStats = phase === 'copying'
|
||||
&& useHardLinks
|
||||
&& progress !== null
|
||||
&& progress.copiedBytes !== undefined
|
||||
&& progress.copyTotalBytes !== undefined
|
||||
&& progress.linkedBytes !== undefined
|
||||
&& progress.linkTotalBytes !== undefined
|
||||
&& progress.linkedFiles !== undefined
|
||||
&& progress.linkTotalFiles !== undefined
|
||||
&& progress.linkTotalFiles > 0
|
||||
? {
|
||||
copiedBytes: progress.copiedBytes,
|
||||
copyTotalBytes: progress.copyTotalBytes,
|
||||
linkedBytes: progress.linkedBytes,
|
||||
linkTotalBytes: progress.linkTotalBytes,
|
||||
linkedFiles: progress.linkedFiles,
|
||||
linkTotalFiles: progress.linkTotalFiles,
|
||||
copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles),
|
||||
copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles),
|
||||
}
|
||||
: null;
|
||||
return (
|
||||
<>
|
||||
{phases.map((name, position) => {
|
||||
@@ -32,14 +53,35 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
|
||||
})}
|
||||
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
|
||||
{tracking && (
|
||||
<div className="progress-caption">
|
||||
{t(caption, {
|
||||
done: formatBytes(progress.doneBytes),
|
||||
total: formatBytes(progress.totalBytes),
|
||||
doneFiles: progress.doneFiles.toLocaleString(),
|
||||
totalFiles: progress.totalFiles.toLocaleString(),
|
||||
})}
|
||||
</div>
|
||||
hardlinkStats ? (
|
||||
<>
|
||||
<div className="progress-caption">
|
||||
{t('progress.copiedActual', {
|
||||
copied: formatBytes(hardlinkStats.copiedBytes),
|
||||
copyTotal: formatBytes(hardlinkStats.copyTotalBytes),
|
||||
copiedFiles: hardlinkStats.copiedFiles.toLocaleString(),
|
||||
copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(),
|
||||
})}
|
||||
</div>
|
||||
<div className="progress-caption">
|
||||
{t('progress.linkedShared', {
|
||||
linked: formatBytes(hardlinkStats.linkedBytes),
|
||||
linkTotal: formatBytes(hardlinkStats.linkTotalBytes),
|
||||
linkedFiles: hardlinkStats.linkedFiles.toLocaleString(),
|
||||
linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(),
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="progress-caption">
|
||||
{t(caption, {
|
||||
done: formatBytes(progress.doneBytes),
|
||||
total: formatBytes(progress.totalBytes),
|
||||
doneFiles: progress.doneFiles.toLocaleString(),
|
||||
totalFiles: progress.totalFiles.toLocaleString(),
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
||||
steamDataConfirmed={wizard.steamDataConfirmed}
|
||||
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
|
||||
decalSource={wizard.decalSource}
|
||||
decalAutoDetected={wizard.decalAutoDetected}
|
||||
defaultDecalPath={wizard.decalProbePath}
|
||||
onDataPath={wizard.setDataPath}
|
||||
onDecalSource={wizard.setDecalSource}
|
||||
onError={wizard.report}
|
||||
|
||||
@@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
problem: DataFolderProblem | null;
|
||||
confirmed: boolean;
|
||||
} | null>(null);
|
||||
const [decalSource, setDecalSource] = useState<string | null>(null);
|
||||
const [decalSource, setDecalSourceState] = useState<string | null>(null);
|
||||
const [decalAutoDetected, setDecalAutoDetected] = useState(false);
|
||||
const [decalManuallyEdited, setDecalManuallyEdited] = useState(false);
|
||||
const [check, setCheck] = useState<PatchCheck | null>(null);
|
||||
const [missingAccepted, setMissingAccepted] = useState(false);
|
||||
const [progress, setProgress] = useState<InstallProgress | null>(null);
|
||||
@@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
? (source?.path ?? null)
|
||||
: null;
|
||||
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
|
||||
const decalProbePath = stockSource?.path ?? source?.path ?? null;
|
||||
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
|
||||
|
||||
// Read-only probe of the player-selected source folder for a usable decal cache.
|
||||
useEffect(() => {
|
||||
if (!active || !decalProbePath || decalManuallyEdited) return;
|
||||
let current = true;
|
||||
ipcInvoke('decals:detectSource', { path: decalProbePath })
|
||||
.then(({ path }) => {
|
||||
if (!current) return;
|
||||
if (path) {
|
||||
setDecalSourceState(path);
|
||||
setDecalAutoDetected(true);
|
||||
} else {
|
||||
setDecalSourceState(null);
|
||||
setDecalAutoDetected(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!current) return;
|
||||
setDecalSourceState(null);
|
||||
setDecalAutoDetected(false);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [active, decalProbePath, decalManuallyEdited]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !dataPath) return;
|
||||
let current = true;
|
||||
@@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
|
||||
useEffect(() => ipcOn('event:install-progress', setProgress), []);
|
||||
|
||||
const resetDecals = (): void => {
|
||||
setDecalSourceState(null);
|
||||
setDecalAutoDetected(false);
|
||||
setDecalManuallyEdited(false);
|
||||
};
|
||||
|
||||
const start = (): void => {
|
||||
clear();
|
||||
setMode('new');
|
||||
@@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
setDraftId(null);
|
||||
setDataPath('');
|
||||
setDataInspection(null);
|
||||
setDecalSource(null);
|
||||
resetDecals();
|
||||
setActive(true);
|
||||
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
|
||||
setDraftId(id);
|
||||
@@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
setStockSource(null);
|
||||
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
|
||||
setName('');
|
||||
resetDecals();
|
||||
};
|
||||
|
||||
const chooseSource = (found: GameFolderInspection | null): void => {
|
||||
setSource(found);
|
||||
setStockSource(null);
|
||||
resetDecals();
|
||||
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
|
||||
const defaultMethod = isExisting ? 'existing' : 'copy';
|
||||
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
|
||||
@@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
const chooseStockSource = (found: GameFolderInspection | null): void => {
|
||||
setStockSource(found);
|
||||
resetDecals();
|
||||
};
|
||||
|
||||
const setDecalSource = (path: string | null): void => {
|
||||
setDecalSourceState(path);
|
||||
setDecalAutoDetected(false);
|
||||
setDecalManuallyEdited(true);
|
||||
};
|
||||
|
||||
const install = (): void => {
|
||||
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
|
||||
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
|
||||
@@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
};
|
||||
|
||||
return {
|
||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
|
||||
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, 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,
|
||||
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource: chooseStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [
|
||||
'install:',
|
||||
/** Listing and managing installed copies. */
|
||||
'copies:',
|
||||
/** Read-only detection of decal cache folders in player-selected or registered sources. */
|
||||
'decals:',
|
||||
/** Settings shared by the saves of a game copy. */
|
||||
'tuning:',
|
||||
/** Additive mods repository, per-copy ordering/toggles, and presets. */
|
||||
|
||||
@@ -65,8 +65,11 @@ export const ipcContract = {
|
||||
output: z.object({ path: z.string().nullable() }),
|
||||
},
|
||||
'dialog:pickFolder': {
|
||||
/** The dialog title, already translated by the window. */
|
||||
input: z.object({ title: z.string().optional() }),
|
||||
/** The dialog title, already translated by the window, and an optional starting path. */
|
||||
input: z.object({
|
||||
title: z.string().optional(),
|
||||
defaultPath: z.string().optional(),
|
||||
}),
|
||||
/** The chosen folder, or null when the player cancelled. */
|
||||
output: z.object({ path: z.string().nullable() }),
|
||||
},
|
||||
@@ -167,6 +170,11 @@ export const ipcContract = {
|
||||
input: z.void(),
|
||||
output: z.void(),
|
||||
},
|
||||
'decals:detectSource': {
|
||||
/** Read-only check for a usable decal cache inside a player-chosen or registered folder. */
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
output: z.object({ path: z.string().nullable() }),
|
||||
},
|
||||
'saves:list': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: SaveListSchema,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/** Self-described origin of an offline client folder recorded in wtoffline/client.json. */
|
||||
export const CLIENT_ORIGINS = ['copy', 'hardlink', 'in-place'] as const;
|
||||
export const ClientOriginSchema = z.enum(CLIENT_ORIGINS);
|
||||
export type ClientOrigin = z.output<typeof ClientOriginSchema>;
|
||||
|
||||
/** What the launcher found in a folder the player chose as their War Thunder installation. */
|
||||
export const GameFolderInspectionSchema = z.object({
|
||||
path: z.string(),
|
||||
@@ -16,6 +21,10 @@ export const GameFolderInspectionSchema = z.object({
|
||||
hasOfflineBackup: z.boolean(),
|
||||
/** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */
|
||||
needsStockSource: z.boolean(),
|
||||
/** Client origin recorded in wtoffline/client.json when present and valid, or null otherwise. */
|
||||
clientOrigin: ClientOriginSchema.nullable().optional(),
|
||||
/** True when at least one eligible read-only resource pack has multiple hard links (nlink >= 2). */
|
||||
hasHardlinkedResources: z.boolean().optional(),
|
||||
});
|
||||
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
|
||||
|
||||
@@ -143,6 +152,18 @@ export const InstallProgressSchema = z.object({
|
||||
totalBytes: z.number(),
|
||||
doneFiles: z.number(),
|
||||
totalFiles: z.number(),
|
||||
/** Actual bytes written to disk during copying (excludes hard-linked files). */
|
||||
copiedBytes: z.number().nonnegative().optional(),
|
||||
/** Total bytes planned to be written to disk during copying (excludes hard-linked files). */
|
||||
copyTotalBytes: z.number().nonnegative().optional(),
|
||||
/** Bytes shared via hard links so far (occupies no extra disk space). */
|
||||
linkedBytes: z.number().nonnegative().optional(),
|
||||
/** Total bytes planned to be shared via hard links. */
|
||||
linkTotalBytes: z.number().nonnegative().optional(),
|
||||
/** Number of hard-linked files created so far. */
|
||||
linkedFiles: z.number().nonnegative().optional(),
|
||||
/** Total number of files planned to be shared via hard links. */
|
||||
linkTotalFiles: z.number().nonnegative().optional(),
|
||||
});
|
||||
export type InstallProgress = z.output<typeof InstallProgressSchema>;
|
||||
|
||||
@@ -173,6 +194,8 @@ export const InstallRecordSchema = z.object({
|
||||
sourceFiles: z.array(z.string().min(1)).optional(),
|
||||
/** Relative resource paths linked to the source and detached on a version update. */
|
||||
hardlinkedFiles: z.array(z.string().min(1)).optional(),
|
||||
/** Client origin read from wtoffline/client.json when registering an existing folder. */
|
||||
detectedOrigin: ClientOriginSchema.optional(),
|
||||
/** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */
|
||||
folderMissing: z.boolean().optional(),
|
||||
});
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { z } from 'zod';
|
||||
import { CopyIdSchema } from './install.ts';
|
||||
import { ClientOriginSchema, CopyIdSchema } from './install.ts';
|
||||
|
||||
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
|
||||
export const MaintenanceRequestSchema = z.object({
|
||||
id: CopyIdSchema,
|
||||
operation: MaintenanceOperationSchema,
|
||||
deleteFiles: z.boolean().default(false),
|
||||
restoreStock: z.boolean().default(false),
|
||||
deleteData: z.boolean().default(false),
|
||||
sourcePath: z.string().min(1).optional(),
|
||||
steamLocations: z.object({
|
||||
@@ -24,6 +26,10 @@ export const MaintenanceInfoSchema = z.object({
|
||||
copyInSteam: z.boolean(),
|
||||
dataInSteam: z.boolean(),
|
||||
}).nullable(),
|
||||
clientOrigin: ClientOriginSchema.nullable(),
|
||||
hasHardlinkedResources: z.boolean(),
|
||||
canDeleteFiles: z.boolean(),
|
||||
canRestoreAndRemove: z.boolean(),
|
||||
});
|
||||
export const MaintenanceProgressSchema = z.object({
|
||||
id: CopyIdSchema,
|
||||
|
||||
@@ -53,6 +53,8 @@ export interface BattleSettlementDeps {
|
||||
readonly streaks: BattleStreaks;
|
||||
readonly items: ItemCatalogue;
|
||||
readonly repair: RepairRules;
|
||||
/** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */
|
||||
readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined;
|
||||
}
|
||||
|
||||
const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' };
|
||||
@@ -87,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
|
||||
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
|
||||
}
|
||||
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
|
||||
const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), {
|
||||
const vehicleRps = rewards.vehicles.map(vehicleRpOf);
|
||||
const research = investBattleRp(profile, vehicleRps, {
|
||||
country: session.country,
|
||||
requiredClass: session.requiredClass,
|
||||
difficulty,
|
||||
nowUnixSec: log.timeSec,
|
||||
}, deps);
|
||||
const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0);
|
||||
if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec);
|
||||
recordBoosterUses(profile, boosters.uses, log);
|
||||
const wager = activeWager(profile, deps.items);
|
||||
const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, {
|
||||
|
||||
@@ -16,12 +16,19 @@ export interface BackupSpawn {
|
||||
readonly backup: string;
|
||||
}
|
||||
|
||||
/** Strip native model folder prefixes (e.g. "tankModels/cn_type_59" -> "cn_type_59"). */
|
||||
export function normalizeBackupUnitName(unit: string): string {
|
||||
const slash = unit.lastIndexOf('/');
|
||||
return slash >= 0 ? unit.slice(slash + 1) : unit;
|
||||
}
|
||||
|
||||
function receiptKey(session: BattleSession, slot: number): string {
|
||||
return `${session.sessionId}_${slot}`;
|
||||
}
|
||||
|
||||
export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean {
|
||||
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit
|
||||
const unit = normalizeBackupUnitName(spawn.unit);
|
||||
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === unit
|
||||
&& recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot));
|
||||
}
|
||||
|
||||
@@ -32,11 +39,12 @@ export function consumeBattleSpares(
|
||||
const seenSlots = new Set<number>();
|
||||
const consumed = new Map<string, number>();
|
||||
for (const spawn of spawns) {
|
||||
const { slot, unit, backup } = spawn;
|
||||
const { slot, backup } = spawn;
|
||||
const unit = normalizeBackupUnitName(spawn.unit);
|
||||
if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue;
|
||||
seenSlots.add(slot);
|
||||
if (backup === DAILY_BACKUP) {
|
||||
recordDailyBackupSpawn(profile, session, spawn);
|
||||
recordDailyBackupSpawn(profile, session, { slot, unit, backup });
|
||||
continue;
|
||||
}
|
||||
if (dailySparesLeft(profile, session.startedAtSec) > 0
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { BattleEconomy } from '../../battle/battle-economy.ts';
|
||||
import type { BattleStreaks } from '../../battle/battle-streaks.ts';
|
||||
import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts';
|
||||
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
|
||||
import type { ClanStore } from '../../clans/clan-store.ts';
|
||||
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
|
||||
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
|
||||
import { clientProfile } from '../../profile/client-profile.ts';
|
||||
@@ -41,6 +42,7 @@ export interface FinishBattleContext {
|
||||
readonly crew: CrewSkillCatalogue;
|
||||
readonly items: ItemCatalogue;
|
||||
readonly repair: RepairRules;
|
||||
readonly clans?: { readonly store: ClanStore } | undefined;
|
||||
}
|
||||
|
||||
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
|
||||
@@ -67,7 +69,15 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
|
||||
// The result log and expenses are written together. A retry can arrive after the profile
|
||||
// was saved but before the session was marked settled.
|
||||
if (hasBattleResultLog(profile, session.roomId)) return false;
|
||||
settleBattle(profile, report, session, settlementDeps);
|
||||
settleBattle(profile, report, session, {
|
||||
...settlementDeps,
|
||||
onBattleRpEarned: ctx.clans
|
||||
? (baseVehicleRp, nowSec) => {
|
||||
ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec);
|
||||
ctx.clans!.store.syncProfile(profile, account, nowSec);
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
battle.onAfterSettle?.({
|
||||
userId: account.userId,
|
||||
roomId: session.sessionId,
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
|
||||
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
|
||||
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
|
||||
* auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
|
||||
* auto-repair / auto-refill / auto-buy-modifications, map preferences, and per-vehicle
|
||||
* preferences (`hangar/<vehicle>` `lastSkin`, `lastWeapon`, `lastBullets0..5`, and flight
|
||||
* trims `aileronTrim`/`elevatorTrim`/`rudderTrim`). On returning from
|
||||
* a stock training mission, the client also reports completion in `missionAwards` while
|
||||
* `pveProgress` is empty. Answers the whole updated profile.
|
||||
*/
|
||||
|
||||
@@ -8,18 +8,24 @@
|
||||
*/
|
||||
import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import type { LocalizedText } from '../../game-data/datasets/unit-names.ts';
|
||||
import { clientProfile } from '../../profile/client-profile.ts';
|
||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||
import { serverTimeNow } from '../../profile/server-time.ts';
|
||||
import type { RuleOutcome } from '../../research/rule-outcome.ts';
|
||||
import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts';
|
||||
import { buyGoldEntitlement } from '../../store/store-purchase.ts';
|
||||
import { freePaymentLabelForStore } from '../../store/store-tuning.ts';
|
||||
import type { CharActionHandler } from '../char-action.ts';
|
||||
import { withAccount } from './account-context.ts';
|
||||
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
|
||||
|
||||
export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler {
|
||||
const table = buildEntitlementsPriceBlk(store.allProducts());
|
||||
export function entitlementsPriceEx(
|
||||
store: StoreCatalogue,
|
||||
freePaymentLabel?: LocalizedText,
|
||||
): CharActionHandler {
|
||||
const label = freePaymentLabel ?? freePaymentLabelForStore(store);
|
||||
const table = buildEntitlementsPriceBlk(store.allProducts(), label);
|
||||
return () => ({ kind: 'data', blk: table });
|
||||
}
|
||||
|
||||
@@ -42,8 +48,15 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account
|
||||
});
|
||||
}
|
||||
|
||||
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock {
|
||||
function buildEntitlementsPriceBlk(
|
||||
products: readonly StoreProduct[],
|
||||
freePaymentLabel: LocalizedText,
|
||||
): BlkBlock {
|
||||
const root = emptyBlock();
|
||||
// Top-level string params are ignored by stock blockCount() enumeration and read by the
|
||||
// free-offline-payment-method GUI patch to localize the no-GJN payment option.
|
||||
setParam(root, 'wtoFreePaymentLabelZh', { type: 'string', value: freePaymentLabel.zh });
|
||||
setParam(root, 'wtoFreePaymentLabelEn', { type: 'string', value: freePaymentLabel.en });
|
||||
for (const product of products) {
|
||||
const block = emptyBlock(product.id);
|
||||
setParam(block, 'chapter', { type: 'string', value: product.chapter });
|
||||
|
||||
@@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray<keyof Omit<ClanLogEntry, 'id' | 'e
|
||||
export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock {
|
||||
const todayDay = Math.floor(nowSec / 86400);
|
||||
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity;
|
||||
// `clanInfoTable.nut:269` passes `nextRewardDayId` straight to `time.buildDateTimeStr`
|
||||
// (`clanAverageActivityModal.nut:60-62`), which expects a Unix timestamp in seconds.
|
||||
// `clan_get_clan_info` (`aces.exe` 0x1787130) returns the raw DataBlock, and Squirrel
|
||||
// `sqDataBlock` (`0x460da35`) pushes `TYPE_INT64` as a 64-bit integer.
|
||||
const anchorDay = clan.lastRewardDay ?? todayDay;
|
||||
const candidateNextDay = anchorDay + rewardPeriodDays;
|
||||
const nextRewardDay = candidateNextDay > todayDay ? candidateNextDay : todayDay + rewardPeriodDays;
|
||||
const nextRewardSec = nextRewardDay * 86400;
|
||||
return {
|
||||
name: '',
|
||||
params: [
|
||||
@@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat
|
||||
int('rewardPeriodDays', rewardPeriodDays),
|
||||
bool('expRewardEnabled', true),
|
||||
int('historyDepth', historyDepthDays),
|
||||
int('nextRewardDayId', todayDay + rewardPeriodDays),
|
||||
int64('nextRewardDayId', BigInt(nextRewardSec)),
|
||||
],
|
||||
blocks: [
|
||||
buildAstatBlock(clan, tuning),
|
||||
@@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] {
|
||||
function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock {
|
||||
const periods = member.periods.length > 0
|
||||
? member.periods
|
||||
: [{ day: todayDay, activity: member.curActivity, exp: 20000 }];
|
||||
: (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []);
|
||||
|
||||
return {
|
||||
name: member.uid,
|
||||
@@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam {
|
||||
return { name, value: { type: 'int', value: Math.trunc(value) } };
|
||||
}
|
||||
|
||||
function int64(name: string, value: bigint): BlkParam {
|
||||
return { name, value: { type: 'int64', value } };
|
||||
}
|
||||
|
||||
function bool(name: string, value: boolean): BlkParam {
|
||||
return { name, value: { type: 'bool', value } };
|
||||
}
|
||||
@@ -54,13 +54,15 @@ export function addMemberToClan(
|
||||
): void {
|
||||
if (clan.members.some((m) => m.uid === uid)) return;
|
||||
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
|
||||
const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity);
|
||||
const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0);
|
||||
clan.members.push({
|
||||
uid,
|
||||
nick,
|
||||
role,
|
||||
joinDateSec: nowSec,
|
||||
curActivity: tuning.activity.maxPerPeriod,
|
||||
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
|
||||
curActivity,
|
||||
totalActivity: periods.length > 0 ? periodActivitySum : curActivity,
|
||||
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
|
||||
ratingArc: tuning.playerRating.joiner.arc,
|
||||
ratingHist: tuning.playerRating.joiner.hist,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk`
|
||||
* (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May,
|
||||
* Jul, Sep, and Nov at 00:00:00 UTC.
|
||||
*
|
||||
* Wire contract verified in stock `aces.exe` (2.61.0.58):
|
||||
* - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level
|
||||
* profile parameters on every profile-returning char transaction:
|
||||
* - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay`
|
||||
* - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay`
|
||||
* - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber`
|
||||
* - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear`
|
||||
* - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim.
|
||||
* - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using
|
||||
* `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1`
|
||||
* (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the
|
||||
* end time with `time.buildDateTimeStr(info.rewardDay, false, false)`.
|
||||
*/
|
||||
|
||||
export interface ClanSeasonInfo {
|
||||
/** UTC 00:00:00 start of the active season as Unix seconds. */
|
||||
readonly startDaySec: number;
|
||||
/** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */
|
||||
readonly rewardDaySec: number;
|
||||
/** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */
|
||||
readonly numberInYear: number;
|
||||
/** Monotonic positive ordinal season number across years. */
|
||||
readonly ordinalNumber: number;
|
||||
}
|
||||
|
||||
/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */
|
||||
export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [
|
||||
{ month: 1, day: 1 },
|
||||
{ month: 3, day: 1 },
|
||||
{ month: 5, day: 1 },
|
||||
{ month: 7, day: 1 },
|
||||
{ month: 9, day: 1 },
|
||||
{ month: 11, day: 1 },
|
||||
];
|
||||
|
||||
const SEASON_ORDINAL_BASE_YEAR = 2016;
|
||||
|
||||
/** Compute the active squadron battle season for a given Unix timestamp in seconds. */
|
||||
export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo {
|
||||
const now = new Date(Math.trunc(nowSec) * 1000);
|
||||
const year = now.getUTCFullYear();
|
||||
const seasonCount = CLAN_SEASON_STARTS.length;
|
||||
|
||||
let activeIndex = 0;
|
||||
let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000;
|
||||
|
||||
for (let i = seasonCount - 1; i >= 0; i--) {
|
||||
const entry = CLAN_SEASON_STARTS[i]!;
|
||||
const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000;
|
||||
if (nowSec >= candidateSec) {
|
||||
activeIndex = i;
|
||||
startSec = candidateSec;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const nextIndex = (activeIndex + 1) % seasonCount;
|
||||
const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year;
|
||||
const nextEntry = CLAN_SEASON_STARTS[nextIndex]!;
|
||||
const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000;
|
||||
|
||||
const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1);
|
||||
|
||||
return {
|
||||
startDaySec: startSec,
|
||||
rewardDaySec: rewardSec,
|
||||
numberInYear: activeIndex,
|
||||
ordinalNumber,
|
||||
};
|
||||
}
|
||||
@@ -3,25 +3,75 @@
|
||||
* The directory is written when the server first creates `<data>/clans.json`.
|
||||
*/
|
||||
import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts';
|
||||
import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts';
|
||||
import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts';
|
||||
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
|
||||
export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] {
|
||||
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
|
||||
const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY;
|
||||
return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
|
||||
return tuning.presetClans.clans.map((spec, specIndex) =>
|
||||
buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
|
||||
}
|
||||
|
||||
/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */
|
||||
export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] {
|
||||
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity;
|
||||
/**
|
||||
* The activity periods a member starts with: `periodCount` periods (defaulting to
|
||||
* `activity.startingPeriods`), each with the given activity and the squadron RP it earns.
|
||||
*/
|
||||
export function buildDefaultPeriods(
|
||||
todayDay: number,
|
||||
tuning: ClanTuning,
|
||||
periodActivity = tuning.activity.maxPerPeriod,
|
||||
periodCount = tuning.activity.startingPeriods,
|
||||
): ClanActivityPeriodEntry[] {
|
||||
if (periodCount <= 0) return [];
|
||||
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity;
|
||||
const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod);
|
||||
return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
|
||||
return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
|
||||
}
|
||||
|
||||
function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord {
|
||||
const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
|
||||
/**
|
||||
* Idempotently appends deterministic filler NPCs to an existing preset clan whose
|
||||
* persisted roster is smaller than its configured `targetMemberCount`, without altering
|
||||
* any existing player or NPC members.
|
||||
*/
|
||||
export function backfillPresetClanMembers(
|
||||
clan: ClanRecord,
|
||||
spec: PresetClan,
|
||||
specIndex: number,
|
||||
todayDay: number,
|
||||
tuning: ClanTuning,
|
||||
): boolean {
|
||||
const targetCount = Math.min(clan.mlimit, spec.targetMemberCount);
|
||||
if (clan.members.length >= targetCount) return false;
|
||||
|
||||
const existingUids = new Set(clan.members.map((m) => m.uid));
|
||||
const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning);
|
||||
let added = false;
|
||||
for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) {
|
||||
const npc = fillerSpecs[i]!;
|
||||
if (existingUids.has(npc.uid)) continue;
|
||||
existingUids.add(npc.uid);
|
||||
const memberIdx = spec.members.length + i;
|
||||
clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning));
|
||||
added = true;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
function buildSeededClan(
|
||||
spec: PresetClan,
|
||||
specIndex: number,
|
||||
cdateSec: number,
|
||||
todayDay: number,
|
||||
tuning: ClanTuning,
|
||||
): ClanRecord {
|
||||
const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
|
||||
const allSpecs: PresetMember[] = [
|
||||
...spec.members,
|
||||
...buildPresetFillerSpecs(spec, specIndex, tuning),
|
||||
].slice(0, mlimit);
|
||||
const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
|
||||
const leader = spec.members[0]!;
|
||||
return {
|
||||
id: spec.id,
|
||||
@@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
|
||||
region: spec.region,
|
||||
status: 'open',
|
||||
autoaccept: spec.autoAccept,
|
||||
mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
|
||||
mlimit,
|
||||
mspent: 0,
|
||||
cdateSec,
|
||||
changedByUid: leader.uid,
|
||||
changedByNick: leader.nick,
|
||||
changedTimeSec: cdateSec,
|
||||
regionLastUpdatedSec: 0,
|
||||
lastRewardDay: todayDay,
|
||||
stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats },
|
||||
members,
|
||||
candidates: [],
|
||||
@@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
|
||||
};
|
||||
}
|
||||
|
||||
function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord {
|
||||
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity);
|
||||
function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] {
|
||||
const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
|
||||
const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount));
|
||||
const needed = targetCount - spec.members.length;
|
||||
if (needed <= 0) return [];
|
||||
|
||||
const filler = tuning.presetClans.fillerMembers;
|
||||
const clanSlot = presetClanSlot(spec.id, specIndex);
|
||||
const usedUids = new Set(spec.members.map((m) => m.uid));
|
||||
const span = Math.max(0, filler.activityMax - filler.activityMin);
|
||||
const result: PresetMember[] = [];
|
||||
|
||||
let ordinal = spec.members.length + 1;
|
||||
while (result.length < needed) {
|
||||
const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal);
|
||||
if (usedUids.has(uid)) {
|
||||
ordinal++;
|
||||
continue;
|
||||
}
|
||||
usedUids.add(uid);
|
||||
const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!;
|
||||
const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!;
|
||||
const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!;
|
||||
const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!;
|
||||
const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0;
|
||||
const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset);
|
||||
result.push({
|
||||
uid,
|
||||
nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`,
|
||||
role: ClanRole.REGULAR,
|
||||
title,
|
||||
icon,
|
||||
unit,
|
||||
activity,
|
||||
});
|
||||
ordinal++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function presetClanSlot(clanId: string, specIndex: number): number {
|
||||
const parsed = Number(clanId);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) {
|
||||
const remainder = parsed % 1000;
|
||||
if (remainder > 0) return remainder;
|
||||
}
|
||||
return specIndex + 1;
|
||||
}
|
||||
|
||||
function buildSeededMember(
|
||||
spec: PresetClan,
|
||||
npc: PresetMember,
|
||||
idx: number,
|
||||
cdateSec: number,
|
||||
todayDay: number,
|
||||
tuning: ClanTuning,
|
||||
): ClanMemberRecord {
|
||||
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods);
|
||||
const { step, floor } = tuning.presetClans.memberRating;
|
||||
return {
|
||||
uid: npc.uid,
|
||||
@@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda
|
||||
npcFrame: '',
|
||||
npcShowcaseUnit: npc.unit,
|
||||
curActivity: npc.activity,
|
||||
totalActivity: periods.reduce((sum, p) => sum + p.activity, 0),
|
||||
totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity,
|
||||
earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0),
|
||||
ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc),
|
||||
ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist),
|
||||
|
||||
@@ -39,10 +39,12 @@ import {
|
||||
type MembershipRequestQuery,
|
||||
} from './clan-membership.ts';
|
||||
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
|
||||
import { createDefaultClans } from './clan-seeds.ts';
|
||||
import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts';
|
||||
import type { ClanTuning } from './clan-tuning.ts';
|
||||
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
|
||||
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
|
||||
export type { LeaderboardQuery };
|
||||
|
||||
export class ClanStore {
|
||||
@@ -51,18 +53,36 @@ export class ClanStore {
|
||||
readonly tuning: ClanTuning;
|
||||
#state: StoredClansState;
|
||||
|
||||
constructor(dataFolder: string, tuning: ClanTuning) {
|
||||
constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) {
|
||||
this.#filePath = join(dataFolder, 'clans.json');
|
||||
this.tuning = tuning;
|
||||
this.#state = this.#loadOrSeed();
|
||||
this.#state = this.#loadOrSeed(nowSec);
|
||||
}
|
||||
|
||||
#loadOrSeed(): StoredClansState {
|
||||
#loadOrSeed(nowSec: number): StoredClansState {
|
||||
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
|
||||
if (existsSync(this.#filePath)) {
|
||||
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
|
||||
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed;
|
||||
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') {
|
||||
let mutated = false;
|
||||
for (let i = 0; i < this.tuning.presetClans.clans.length; i++) {
|
||||
const spec = this.tuning.presetClans.clans[i]!;
|
||||
const existing = parsed.clans.find((c) => c.id === spec.id);
|
||||
if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) {
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
for (const clan of parsed.clans) {
|
||||
if (clan.lastRewardDay === undefined) {
|
||||
clan.lastRewardDay = todayDay;
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
if (mutated) this.#save(parsed);
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) };
|
||||
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) };
|
||||
this.#save(seeded);
|
||||
return seeded;
|
||||
}
|
||||
@@ -71,19 +91,7 @@ export class ClanStore {
|
||||
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
|
||||
}
|
||||
|
||||
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
|
||||
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
|
||||
}
|
||||
|
||||
byId(clanId: string): ClanRecord | undefined {
|
||||
return this.#state.clans.find((c) => c.id === clanId);
|
||||
}
|
||||
|
||||
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
|
||||
return findClanInList(this.#state.clans, query);
|
||||
}
|
||||
|
||||
clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
|
||||
#findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
|
||||
for (const clan of this.#state.clans) {
|
||||
const member = clan.members.find((m) => m.uid === userId);
|
||||
if (member) return { clan, member };
|
||||
@@ -91,12 +99,147 @@ export class ClanStore {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
|
||||
return clanId && clanId !== '-1'
|
||||
? this.#state.clans.find((c) => c.id === clanId)
|
||||
: this.#findUserClan(userId)?.clan;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily settles expired activity reward periods for all squadrons using the stock
|
||||
* client formula (`clanAverageActivityModal.nut:44-54`):
|
||||
* `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)`
|
||||
* Player members' current-period activity resets to 0 for the new period while NPC
|
||||
* members keep their active roster contribution.
|
||||
*/
|
||||
settleExpiredPeriods(nowSec = nowSeconds()): boolean {
|
||||
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
|
||||
const {
|
||||
maxPerPeriod,
|
||||
squadronRpPerFullPeriod: maxClanActivity,
|
||||
rewardPeriodDays,
|
||||
historyDepthDays,
|
||||
} = this.tuning.activity;
|
||||
|
||||
let mutated = false;
|
||||
for (const clan of this.#state.clans) {
|
||||
if (clan.lastRewardDay === undefined) {
|
||||
clan.lastRewardDay = todayDay;
|
||||
mutated = true;
|
||||
continue;
|
||||
}
|
||||
const elapsedDays = todayDay - clan.lastRewardDay;
|
||||
if (elapsedDays < rewardPeriodDays) continue;
|
||||
|
||||
const anchorDay = clan.lastRewardDay;
|
||||
const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays);
|
||||
const settlementDay = anchorDay + rewardPeriodDays;
|
||||
const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays;
|
||||
const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0);
|
||||
const maxActivity = maxPerPeriod * clan.members.length;
|
||||
const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0;
|
||||
const minKeptDay = settlementDay - historyDepthDays;
|
||||
|
||||
clan.members = clan.members.map((member) => {
|
||||
const myActivity = Math.max(0, member.curActivity);
|
||||
const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0;
|
||||
const myExp = (myPercent > 0 && clanPercent > 0)
|
||||
? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity))
|
||||
: 0;
|
||||
const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay));
|
||||
const settledEntry = (myActivity > 0 || myExp > 0)
|
||||
? [{ day: settlementDay, activity: myActivity, exp: myExp }]
|
||||
: [];
|
||||
const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay);
|
||||
if (member.isNpc) {
|
||||
return {
|
||||
...member,
|
||||
totalActivity: member.totalActivity + myActivity,
|
||||
earnedSquadronExp: member.earnedSquadronExp + myExp,
|
||||
periods: nextPeriods,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...member,
|
||||
curActivity: 0,
|
||||
earnedSquadronExp: member.earnedSquadronExp + myExp,
|
||||
periods: nextPeriods,
|
||||
};
|
||||
});
|
||||
|
||||
clan.lastRewardDay = nextAnchorDay;
|
||||
mutated = true;
|
||||
}
|
||||
|
||||
if (mutated) this.#save();
|
||||
return mutated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulates current-period squadron activity from battle base vehicle RP
|
||||
* (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`).
|
||||
* Returns the activity points actually added.
|
||||
*/
|
||||
recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0;
|
||||
const found = this.#findUserClan(userId);
|
||||
if (!found) return 0;
|
||||
|
||||
const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity;
|
||||
const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint);
|
||||
if (rawGain <= 0) return 0;
|
||||
|
||||
const { clan, member } = found;
|
||||
const remaining = Math.max(0, maxPerPeriod - member.curActivity);
|
||||
const added = Math.min(rawGain, remaining);
|
||||
if (added <= 0) return 0;
|
||||
|
||||
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
|
||||
const periodStartDay = clan.lastRewardDay ?? todayDay;
|
||||
const nextCurActivity = member.curActivity + added;
|
||||
const nextTotalActivity = member.totalActivity + added;
|
||||
const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay);
|
||||
const nextPeriods = existingInProgressIdx >= 0
|
||||
? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p))
|
||||
: [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods];
|
||||
|
||||
const memberIdx = clan.members.findIndex((m) => m.uid === userId);
|
||||
if (memberIdx < 0) return 0;
|
||||
clan.members[memberIdx] = {
|
||||
...member,
|
||||
curActivity: nextCurActivity,
|
||||
totalActivity: nextTotalActivity,
|
||||
periods: nextPeriods,
|
||||
};
|
||||
this.#save();
|
||||
return added;
|
||||
}
|
||||
|
||||
byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
return this.#state.clans.find((c) => c.id === clanId);
|
||||
}
|
||||
|
||||
findClan(
|
||||
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
|
||||
nowSec = nowSeconds(),
|
||||
): ClanRecord | undefined {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
return findClanInList(this.#state.clans, query);
|
||||
}
|
||||
|
||||
clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
return this.#findUserClan(userId);
|
||||
}
|
||||
|
||||
pendingRequestOfUser(userId: string): ClanRecord | undefined {
|
||||
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
|
||||
}
|
||||
|
||||
earnedSquadronExpOf(userId: string): number {
|
||||
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0;
|
||||
earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number {
|
||||
return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0;
|
||||
}
|
||||
|
||||
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
|
||||
@@ -107,8 +250,8 @@ export class ClanStore {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
syncProfile(profile: BlkBlock, account: Account): void {
|
||||
const found = this.clanOfUser(account.userId);
|
||||
syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void {
|
||||
const found = this.clanOfUser(account.userId, nowSec);
|
||||
if (found) {
|
||||
const { clan, member } = found;
|
||||
if (member.nick !== account.nick) {
|
||||
@@ -131,15 +274,31 @@ export class ClanStore {
|
||||
}
|
||||
}
|
||||
|
||||
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
|
||||
queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
|
||||
}
|
||||
|
||||
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
|
||||
if (outcome.ok) {
|
||||
const created = this.#state.clans[0];
|
||||
if (created) {
|
||||
created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY);
|
||||
const founder = created.members[0];
|
||||
if (founder && founder.uid === account.userId) {
|
||||
const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity);
|
||||
const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0);
|
||||
created.members[0] = {
|
||||
...founder,
|
||||
curActivity,
|
||||
totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity,
|
||||
};
|
||||
}
|
||||
}
|
||||
this.#save();
|
||||
this.syncProfile(profile, account);
|
||||
this.syncProfile(profile, account, nowSec);
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
@@ -189,10 +348,11 @@ export class ClanStore {
|
||||
}
|
||||
|
||||
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
|
||||
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning);
|
||||
this.settleExpiredPeriods(nowSec);
|
||||
const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning);
|
||||
if (res.mutated) {
|
||||
this.#save();
|
||||
this.syncProfile(profile, account);
|
||||
this.syncProfile(profile, account, nowSec);
|
||||
}
|
||||
return res.outcome;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,17 @@ export interface PresetMember {
|
||||
readonly activity: number;
|
||||
}
|
||||
|
||||
export interface PresetFillerMembers {
|
||||
readonly activityMin: number;
|
||||
readonly activityMax: number;
|
||||
readonly uidBase: number;
|
||||
readonly uidStride: number;
|
||||
readonly callsigns: readonly string[];
|
||||
readonly titles: readonly string[];
|
||||
readonly icons: readonly string[];
|
||||
readonly units: readonly string[];
|
||||
}
|
||||
|
||||
export interface PresetClan {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
@@ -37,6 +48,7 @@ export interface PresetClan {
|
||||
readonly region: string;
|
||||
readonly autoAccept: boolean;
|
||||
readonly createdAfterDays: number;
|
||||
readonly targetMemberCount: number;
|
||||
readonly rating: ModeTriple;
|
||||
readonly members: readonly PresetMember[];
|
||||
}
|
||||
@@ -47,6 +59,8 @@ export interface ClanTuning {
|
||||
readonly squadronRpPerFullPeriod: number;
|
||||
readonly rewardPeriodDays: number;
|
||||
readonly historyDepthDays: number;
|
||||
readonly rpPerActivityPoint: number;
|
||||
readonly startingActivity: number;
|
||||
readonly startingPeriods: number;
|
||||
};
|
||||
readonly memberLimits: { readonly normal: number; readonly battalionInitial: number };
|
||||
@@ -56,6 +70,8 @@ export interface ClanTuning {
|
||||
readonly presetClans: {
|
||||
readonly createdDaysAgo: number;
|
||||
readonly memberJoinSpacingMinutes: number;
|
||||
readonly npcHistoryPeriods: number;
|
||||
readonly fillerMembers: PresetFillerMembers;
|
||||
readonly stats: PresetClanStats;
|
||||
readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple };
|
||||
readonly clans: readonly PresetClan[];
|
||||
@@ -64,6 +80,7 @@ export interface ClanTuning {
|
||||
|
||||
export function readClanTuning(file: TuningReader): ClanTuning {
|
||||
const activity = file.object('activity');
|
||||
const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 });
|
||||
const limits = file.object('memberLimits');
|
||||
const leaderboard = file.object('leaderboard');
|
||||
const preset = file.object('presetClans');
|
||||
@@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning {
|
||||
const rating = preset.object('memberRating');
|
||||
return {
|
||||
activity: {
|
||||
maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }),
|
||||
maxPerPeriod,
|
||||
squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }),
|
||||
rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }),
|
||||
historyDepthDays: activity.int('historyDepthDays', { min: 1 }),
|
||||
rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }),
|
||||
startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }),
|
||||
startingPeriods: activity.int('startingPeriods', { min: 0 }),
|
||||
},
|
||||
memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) },
|
||||
@@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning {
|
||||
presetClans: {
|
||||
createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }),
|
||||
memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }),
|
||||
npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }),
|
||||
fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod),
|
||||
stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats,
|
||||
memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) },
|
||||
clans: preset.list('clans', readPresetClan),
|
||||
@@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning {
|
||||
};
|
||||
}
|
||||
|
||||
function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers {
|
||||
const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod });
|
||||
const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod });
|
||||
const callsigns = entry.stringList('callsigns');
|
||||
const titles = entry.stringList('titles');
|
||||
const icons = entry.stringList('icons');
|
||||
const units = entry.stringList('units');
|
||||
if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) {
|
||||
throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty');
|
||||
}
|
||||
return {
|
||||
activityMin,
|
||||
activityMax,
|
||||
uidBase: entry.int('uidBase', { min: 1 }),
|
||||
uidStride: entry.int('uidStride', { min: 1 }),
|
||||
callsigns,
|
||||
titles,
|
||||
icons,
|
||||
units,
|
||||
};
|
||||
}
|
||||
|
||||
function readPresetClan(entry: TuningReader): PresetClan {
|
||||
const type = entry.string('type');
|
||||
if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`);
|
||||
const members = entry.list('members', readPresetMember);
|
||||
if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`);
|
||||
const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length;
|
||||
return {
|
||||
id: entry.string('id'),
|
||||
tag: entry.string('tag'),
|
||||
@@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan {
|
||||
region: entry.string('region'),
|
||||
autoAccept: entry.bool('autoAccept'),
|
||||
createdAfterDays: entry.int('createdAfterDays', { min: 0 }),
|
||||
targetMemberCount: Math.max(members.length, rawTarget),
|
||||
rating: triple(entry.object('rating')),
|
||||
members,
|
||||
};
|
||||
|
||||
@@ -171,6 +171,8 @@ export interface ClanRecord {
|
||||
changedByNick: string;
|
||||
changedTimeSec: number;
|
||||
regionLastUpdatedSec: number;
|
||||
/** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */
|
||||
lastRewardDay?: number;
|
||||
stats: ClanStats;
|
||||
members: ClanMemberRecord[];
|
||||
candidates: ClanCandidateRecord[];
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
* `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients.
|
||||
*/
|
||||
import { gjnText } from '../store/redeem-codes.ts';
|
||||
import { DEFAULT_FREE_PAYMENT_LABEL } from '../store/store-tuning.ts';
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { AccountStore } from '../accounts/account-store.ts';
|
||||
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
|
||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||
import { balanceOf } from '../profile/profile-currency.ts';
|
||||
import { externalInventoryItems } from '../profile/profile-external-inventory.ts';
|
||||
@@ -36,6 +38,7 @@ export class MarketplaceService implements Service {
|
||||
readonly #notifyInventoryChanged: () => void;
|
||||
readonly #maxPerPurchase: number;
|
||||
readonly #sellFeeRate: number;
|
||||
readonly #freePaymentLabel: LocalizedText;
|
||||
|
||||
constructor(
|
||||
accounts: AccountStore,
|
||||
@@ -43,6 +46,7 @@ export class MarketplaceService implements Service {
|
||||
catalogue: InventoryCatalogue,
|
||||
notifyInventoryChanged: () => void,
|
||||
tuning: Pick<MarketplaceTuning, 'maxPerPurchase' | 'sellFeeRate'>,
|
||||
freePaymentLabel: LocalizedText = DEFAULT_FREE_PAYMENT_LABEL,
|
||||
) {
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
@@ -50,6 +54,7 @@ export class MarketplaceService implements Service {
|
||||
this.#notifyInventoryChanged = notifyInventoryChanged;
|
||||
this.#maxPerPurchase = tuning.maxPerPurchase;
|
||||
this.#sellFeeRate = tuning.sellFeeRate;
|
||||
this.#freePaymentLabel = freePaymentLabel;
|
||||
}
|
||||
|
||||
accepts(request: ServiceRequest): boolean {
|
||||
@@ -96,6 +101,7 @@ export class MarketplaceService implements Service {
|
||||
currentUserId: account?.userId ?? '',
|
||||
balance,
|
||||
sellFeeRate: this.#sellFeeRate,
|
||||
freePaymentLabel: this.#freePaymentLabel,
|
||||
listings,
|
||||
}, `marketplace state (${account?.userId ?? 'no-account'})`);
|
||||
}
|
||||
@@ -158,7 +164,13 @@ export class MarketplaceService implements Service {
|
||||
});
|
||||
|
||||
if (errorReason === 'NOT_ENOUGH_GJN') {
|
||||
return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可直接点「老福爷付过了」,或在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. Use "老福爷付过了" or a GJN code on the Redeem tab of the store.' } }, `marketplace buy ${itemdefId}: NOMONEY`);
|
||||
return jsonResponse({
|
||||
ok: false,
|
||||
message: {
|
||||
zh: `GJN 不够。可直接点「${this.#freePaymentLabel.zh}」,或在商店的"兑换码"页用 GJN 充值码补充。`,
|
||||
en: `Not enough GJN. Use "${this.#freePaymentLabel.en}" or a GJN code on the Redeem tab of the store.`,
|
||||
},
|
||||
}, `marketplace buy ${itemdefId}: NOMONEY`);
|
||||
}
|
||||
if (errorReason) {
|
||||
return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`);
|
||||
@@ -166,15 +178,23 @@ export class MarketplaceService implements Service {
|
||||
|
||||
this.#notifyInventoryChanged();
|
||||
const costSummary = isFree ? 'free' : `${gjnText(listing.gjnCostCents * quantity)} GJN`;
|
||||
return jsonResponse({ ok: true, message: buySuccessMessage(listing, quantity, isFree) }, `marketplace buy ${itemdefId} x${quantity} (${costSummary})`);
|
||||
return jsonResponse(
|
||||
{ ok: true, message: buySuccessMessage(listing, quantity, isFree, this.#freePaymentLabel) },
|
||||
`marketplace buy ${itemdefId} x${quantity} (${costSummary})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function buySuccessMessage(listing: MarketplaceListing, quantity: number, isFree: boolean): { zh: string; en: string } {
|
||||
function buySuccessMessage(
|
||||
listing: MarketplaceListing,
|
||||
quantity: number,
|
||||
isFree: boolean,
|
||||
freePaymentLabel: LocalizedText,
|
||||
): LocalizedText {
|
||||
return isFree
|
||||
? {
|
||||
zh: `老福爷付过了!「${listing.title.zh}」兑换券 ×${quantity} 已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
|
||||
en: `Paid by 老福爷! ${quantity} × "${listing.title.en}" coupon is in your inventory (Items → Inventory in the hangar).`,
|
||||
zh: `已通过「${freePaymentLabel.zh}」获得「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
|
||||
en: `Claimed ${quantity} × "${listing.title.en}" coupon via "${freePaymentLabel.en}". It is in your inventory (Items → Inventory in the hangar).`,
|
||||
}
|
||||
: {
|
||||
zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
|
||||
|
||||
@@ -9,7 +9,7 @@ const T = {
|
||||
heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)',
|
||||
catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像',
|
||||
allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有',
|
||||
buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
|
||||
buy: '购买', freeBuy: '直接获取', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
|
||||
buyPrice: '系统售价:<b>{price}</b> GJN', sellPrice: '卖给系统:<b>{price}</b> GJN(扣 {fee}% 手续费)', youHave: '你拥有:<b>{n}</b>',
|
||||
tradeUnconfirmed: '无法确认交易结果,请先查看余额和库存。',
|
||||
tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。',
|
||||
@@ -19,7 +19,7 @@ const T = {
|
||||
heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)',
|
||||
catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars',
|
||||
allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned',
|
||||
buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
|
||||
buy: 'Buy', freeBuy: 'Direct Claim', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
|
||||
buyPrice: 'System price: <b>{price}</b> GJN', sellPrice: 'Sell to system: <b>{price}</b> GJN ({fee}% fee)', youHave: 'You own: <b>{n}</b>',
|
||||
tradeUnconfirmed: 'Could not confirm the trade. Check your balance and inventory.',
|
||||
tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.',
|
||||
@@ -33,7 +33,11 @@ const t = (key, params) => WtoUi.tr(T, key, params);
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const wantedItem = WtoUi.query.get('n') || '';
|
||||
|
||||
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [] };
|
||||
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [], freePaymentLabel: null };
|
||||
|
||||
function freePaymentLabel() {
|
||||
return WtoUi.text(state.freePaymentLabel) || t('freeBuy');
|
||||
}
|
||||
const activeCats = new Set();
|
||||
let openedWanted = false;
|
||||
let tradeNoticeId = 0;
|
||||
@@ -173,7 +177,7 @@ function fillOrderColumns(detail, listing) {
|
||||
sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 })));
|
||||
const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount });
|
||||
buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing);
|
||||
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount });
|
||||
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: freePaymentLabel(), disabled: noAccount });
|
||||
freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing);
|
||||
buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) })));
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.
|
||||
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
|
||||
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
|
||||
import type { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts';
|
||||
import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
|
||||
import { DAILY_BACKUP, normalizeBackupUnitName, recordDailyBackupSpawn } from '../battle/battle-spares.ts';
|
||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
|
||||
import { dailySparesLeft } from '../profile/profile-daily-spares.ts';
|
||||
@@ -50,8 +50,9 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin
|
||||
return { error: 'BAD_PARAMS' };
|
||||
}
|
||||
const battle = deps.sessions.findForUser(sessionId, userId);
|
||||
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' };
|
||||
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP }));
|
||||
const normalizedUnit = normalizeBackupUnitName(unit);
|
||||
if (!battle || battle.settled || battle.spareSlots?.get(slot) !== normalizedUnit) return { error: 'BAD_PARAMS' };
|
||||
deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit: normalizedUnit, backup: DAILY_BACKUP }));
|
||||
return {};
|
||||
}],
|
||||
];
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
/**
|
||||
* The profile as the char service hands it to the client: the saved profile plus the
|
||||
* account data and server clock the char server attaches on the wire.
|
||||
* account data, server clock, and active squadron season metadata the char server attaches
|
||||
* on the wire.
|
||||
*
|
||||
* charDrivenNick: the client reads the player's nick from this top-level string when it
|
||||
* loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d).
|
||||
*
|
||||
* serverTime:i64: the char server's clock; without it the client
|
||||
* takes the server time as 0 and every expiry and time limit is wrong.
|
||||
*
|
||||
* clanDuelNextReward:i64, clanSeasonStart:i64, clanSeasonOrdinal:i, clanSeasonInYear:i:
|
||||
* parsed by GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.58 0xebc728..0xebc7b4)
|
||||
* on every profile-returning char response and exposed by clan_get_current_season_info
|
||||
* (0x178aff0..0x178b227). Without them all fields default to 0, causing the squadron
|
||||
* leaderboard to display "1970-I" and "1970-01-01".
|
||||
*/
|
||||
import { setParam, type BlkBlock } from '@wto/blk';
|
||||
import type { Account } from '../accounts/account-store.ts';
|
||||
import { currentClanSeason } from '../clans/clan-season.ts';
|
||||
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
|
||||
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
|
||||
import { clearStoreCart } from './profile-store-cart.ts';
|
||||
import { clientHangarSpares } from './profile-vehicle-state.ts';
|
||||
import { serverTimeNow } from './server-time.ts';
|
||||
import { serverTimeFromUnixMs } from './server-time.ts';
|
||||
|
||||
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
|
||||
export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.now()): BlkBlock {
|
||||
// Clone the hangar entries whose spare count has a different wire representation.
|
||||
const profile: BlkBlock = {
|
||||
name: saved.name,
|
||||
@@ -26,8 +34,13 @@ export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
|
||||
};
|
||||
clearStoreCart(profile);
|
||||
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
|
||||
const season = currentClanSeason(Math.floor(nowMs / 1000));
|
||||
setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon });
|
||||
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
|
||||
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
|
||||
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeFromUnixMs(nowMs) });
|
||||
setParam(profile, 'clanDuelNextReward', { type: 'int64', value: BigInt(season.rewardDaySec) });
|
||||
setParam(profile, 'clanSeasonStart', { type: 'int64', value: BigInt(season.startDaySec) });
|
||||
setParam(profile, 'clanSeasonOrdinal', { type: 'int', value: season.ordinalNumber });
|
||||
setParam(profile, 'clanSeasonInYear', { type: 'int', value: season.numberInYear });
|
||||
return profile;
|
||||
}
|
||||
@@ -5,7 +5,14 @@
|
||||
* - hangar toggles `autoRefillWeapons:b`, `autoRepairAircrafts:b`, `autoBuyModifications:b` (0x918ef0);
|
||||
* - privacy / save metadata `onlineSaveVersion:i`, `allowToBeAddedToContacts:b`, `allowToBeAddedToLB:b` (0x9179d4..0x917a4c);
|
||||
* - `classinessMarkPriorities:i64` (0x92b2cb);
|
||||
* - sub-block `mapPreferences` (0x927530 -> 0x9483d0).
|
||||
* - sub-block `mapPreferences` (0x927530 -> 0x9483d0);
|
||||
* - per-vehicle `hangar/<vehicle>` client preferences (`AircraftInfo::serialize` mode 0x20/0x80,
|
||||
* owned vehicles only per the stock chard guard at 0x938081):
|
||||
* - `lastSkin:t` (2.61.0.37 0x940fbc/0x94111b, 2.61.0.58 0x943a2f/0x943b8e);
|
||||
* - `lastWeapon:t` (2.61.0.37 0x940ff4/0x941084, 2.61.0.58 0x943a67/0x943af7);
|
||||
* - `lastBullets0..5:t` (2.61.0.37 0x94078d..0x940914 / 0x940b2c..0x940f8d, 2.61.0.58 0x943200..0x94393e);
|
||||
* - `aileronTrim:r`, `elevatorTrim:r`, `rudderTrim:r` (2.61.0.37 0x941682..0x941720 / 0x9411e7..0x9412db,
|
||||
* 2.61.0.58 0x943c7a..0x944119).
|
||||
*
|
||||
* Empty shell blocks that `saveOnline` (mode 0x20) also emits (`entitlementsInfo{}`,
|
||||
* `pveProgress{}`, `weaponPresets{}` — custom weapon presets use `cln_save_weapon_presets`, and
|
||||
@@ -13,6 +20,7 @@
|
||||
* state is preserved.
|
||||
*/
|
||||
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { updateOwnedVehicle } from './profile-hangar.ts';
|
||||
import { disableUserLogs } from './profile-trophies-log.ts';
|
||||
|
||||
const BOOL_SETTINGS = [
|
||||
@@ -23,6 +31,23 @@ const BOOL_SETTINGS = [
|
||||
'allowToBeAddedToLB',
|
||||
] as const;
|
||||
|
||||
const VEHICLE_STRING_SETTINGS = [
|
||||
'lastSkin',
|
||||
'lastWeapon',
|
||||
'lastBullets0',
|
||||
'lastBullets1',
|
||||
'lastBullets2',
|
||||
'lastBullets3',
|
||||
'lastBullets4',
|
||||
'lastBullets5',
|
||||
] as const;
|
||||
|
||||
const VEHICLE_TRIM_SETTINGS = [
|
||||
'aileronTrim',
|
||||
'elevatorTrim',
|
||||
'rudderTrim',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Whether hangar ammunition/expendable auto-refill is enabled (`EconomicState` +0xe979).
|
||||
* Defaults to `true` when absent from `profile.blk`, matching `aces.exe` 0x90b6a0 and 0x918ef0.
|
||||
@@ -57,6 +82,10 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock):
|
||||
target.blocks = cloned.blocks;
|
||||
}
|
||||
|
||||
for (const vehicle of findBlock(request, 'hangar')?.blocks ?? []) {
|
||||
applyVehicleClientSettings(profile, vehicle);
|
||||
}
|
||||
|
||||
const userlogs = findBlock(request, 'userlogs');
|
||||
if (userlogs) {
|
||||
const idsToDisable = userlogs.blocks
|
||||
@@ -68,3 +97,16 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock):
|
||||
if (idsToDisable.length > 0) disableUserLogs(profile, idsToDisable);
|
||||
}
|
||||
}
|
||||
|
||||
function applyVehicleClientSettings(profile: BlkBlock, vehicle: BlkBlock): void {
|
||||
updateOwnedVehicle(profile, vehicle.name, (entry) => {
|
||||
for (const name of VEHICLE_STRING_SETTINGS) {
|
||||
const param = findParam(vehicle, name)?.value;
|
||||
if (param?.type === 'string') setParam(entry, name, param);
|
||||
}
|
||||
for (const name of VEHICLE_TRIM_SETTINGS) {
|
||||
const param = findParam(vehicle, name)?.value;
|
||||
if (param?.type === 'real' && Number.isFinite(param.value)) setParam(entry, name, param);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -31,6 +31,12 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
|
||||
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
|
||||
}
|
||||
|
||||
/** Update an owned vehicle's hangar entry in place; ignores vehicles the player does not own. */
|
||||
export function updateOwnedVehicle(profile: BlkBlock, vehicle: string, update: (entry: BlkBlock) => void): void {
|
||||
const entry = ownedVehicle(profile, vehicle);
|
||||
if (entry) update(entry);
|
||||
}
|
||||
|
||||
/** 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));
|
||||
|
||||
@@ -60,6 +60,7 @@ import { Router } from './transport/router.ts';
|
||||
import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts';
|
||||
import { StoreCatalogue } from './store/store-catalogue.ts';
|
||||
import { StoreService } from './store/store-service.ts';
|
||||
import { bindStoreFreePaymentLabel } from './store/store-tuning.ts';
|
||||
import { TrainingCatalogue } from './training/training-completion.ts';
|
||||
import { TrafficLog } from './traffic-log/traffic-log.ts';
|
||||
import { loadTuning, type Tuning } from './tuning/tuning.ts';
|
||||
@@ -235,7 +236,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
|
||||
webUi,
|
||||
new RegistrationService(accounts),
|
||||
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
|
||||
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
|
||||
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace, tuning.store.freePaymentLabel),
|
||||
new InventoryService(accounts, profiles, catalogues.inventory),
|
||||
new LoginService(accounts),
|
||||
new CharService(actionTable({
|
||||
@@ -310,12 +311,14 @@ function loadDomainCatalogues(
|
||||
localizedUnitNames: UnitNamesMap,
|
||||
) {
|
||||
const classicItemDefs = datasets.load(itemCatalogue);
|
||||
const store = new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store);
|
||||
bindStoreFreePaymentLabel(store, tuning.store.freePaymentLabel);
|
||||
return {
|
||||
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
|
||||
decor: new DecorShop(datasets.load(decorCatalogue)),
|
||||
unlocks: new UnlockShop(datasets.load(unlockPrices)),
|
||||
items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase),
|
||||
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
|
||||
store,
|
||||
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
|
||||
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
|
||||
training: new TrainingCatalogue(datasets.load(trainingMissions)),
|
||||
|
||||
@@ -39,7 +39,27 @@ export interface MultiVehiclePack extends VehiclePackContent {
|
||||
readonly vehicles: readonly string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_FREE_PAYMENT_LABEL: LocalizedText = {
|
||||
zh: '直接获取',
|
||||
en: 'Direct Claim',
|
||||
};
|
||||
|
||||
const MAX_FREE_PAYMENT_LABEL_LENGTH = 64;
|
||||
const freePaymentLabelsByStore = new WeakMap<object, LocalizedText>();
|
||||
|
||||
/** Associate a configured free payment label with a StoreCatalogue instance. */
|
||||
export function bindStoreFreePaymentLabel(store: object, label: LocalizedText): void {
|
||||
freePaymentLabelsByStore.set(store, label);
|
||||
}
|
||||
|
||||
/** Return the configured free payment label for a StoreCatalogue instance, falling back to the default. */
|
||||
export function freePaymentLabelForStore(store: object): LocalizedText {
|
||||
return freePaymentLabelsByStore.get(store) ?? DEFAULT_FREE_PAYMENT_LABEL;
|
||||
}
|
||||
|
||||
export interface StoreTuning {
|
||||
/** Localized label for the no-GJN offline payment button in the game dialog, local store, and marketplace. */
|
||||
readonly freePaymentLabel: LocalizedText;
|
||||
readonly goldenEaglePacks: readonly GoldenEaglePack[];
|
||||
readonly silverLionPacks: readonly SilverLionPack[];
|
||||
readonly premiumForGoldenEagles: readonly PremiumTier[];
|
||||
@@ -53,6 +73,7 @@ export interface StoreTuning {
|
||||
}
|
||||
|
||||
export function readStoreTuning(file: TuningReader): StoreTuning {
|
||||
const freePaymentLabel = readFreePaymentLabel(file);
|
||||
const packs = file.object('vehiclePacks');
|
||||
const byRank = packs.list('byRank', (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), ...packContent(entry) }))
|
||||
.sort((a, b) => a.upToRank - b.upToRank);
|
||||
@@ -66,6 +87,7 @@ export function readStoreTuning(file: TuningReader): StoreTuning {
|
||||
|
||||
validateStoreUniqueness(goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, premiumForGjn, multiVehiclePacks);
|
||||
return {
|
||||
freePaymentLabel,
|
||||
goldenEaglePacks,
|
||||
silverLionPacks,
|
||||
premiumForGoldenEagles,
|
||||
@@ -76,6 +98,27 @@ export function readStoreTuning(file: TuningReader): StoreTuning {
|
||||
};
|
||||
}
|
||||
|
||||
function readFreePaymentLabel(file: TuningReader): LocalizedText {
|
||||
const labelObj = file.object('freePaymentLabel');
|
||||
return {
|
||||
zh: readFreePaymentLabelPart(labelObj, 'zh'),
|
||||
en: readFreePaymentLabelPart(labelObj, 'en'),
|
||||
};
|
||||
}
|
||||
|
||||
function readFreePaymentLabelPart(entry: TuningReader, key: 'zh' | 'en'): string {
|
||||
const trimmed = entry.string(key).trim();
|
||||
if (trimmed === '') {
|
||||
throw new TuningError(`tuning file store.jsonc: freePaymentLabel.${key} must not be blank`);
|
||||
}
|
||||
if (trimmed.length > MAX_FREE_PAYMENT_LABEL_LENGTH) {
|
||||
throw new TuningError(
|
||||
`tuning file store.jsonc: freePaymentLabel.${key} must be at most ${MAX_FREE_PAYMENT_LABEL_LENGTH} characters`,
|
||||
);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** The pack content for a vehicle: its own entry over the first rank tier that covers its rank (the last tier above the highest). */
|
||||
export function vehiclePackContent(tuning: StoreTuning, vehicle: string, rank: number): VehiclePackContent {
|
||||
const tier = tuning.vehiclePacksByRank.find((entry) => rank <= entry.upToRank) ?? tuning.vehiclePacksByRank[tuning.vehiclePacksByRank.length - 1]!;
|
||||
|
||||
@@ -20,6 +20,7 @@ import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } fro
|
||||
import type { RedeemTuning } from './redeem-tuning.ts';
|
||||
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
|
||||
import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts';
|
||||
import { freePaymentLabelForStore } from './store-tuning.ts';
|
||||
|
||||
const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' };
|
||||
|
||||
@@ -31,12 +32,20 @@ export class StoreWebApi {
|
||||
readonly #profiles: PlayerProfiles;
|
||||
readonly #catalogue: StoreCatalogue;
|
||||
readonly #redeemCodes: RedeemTuning;
|
||||
readonly #freePaymentLabel: LocalizedText;
|
||||
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
|
||||
constructor(
|
||||
accounts: AccountStore,
|
||||
profiles: PlayerProfiles,
|
||||
catalogue: StoreCatalogue,
|
||||
redeemCodes: RedeemTuning,
|
||||
freePaymentLabel?: LocalizedText,
|
||||
) {
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
this.#catalogue = catalogue;
|
||||
this.#redeemCodes = redeemCodes;
|
||||
this.#freePaymentLabel = freePaymentLabel ?? freePaymentLabelForStore(catalogue);
|
||||
}
|
||||
|
||||
/** The answer for /store/api/<name>, or undefined when it is not an API request. */
|
||||
@@ -64,6 +73,7 @@ export class StoreWebApi {
|
||||
products,
|
||||
cartProductIds: profile ? storeCartIds(profile) : [],
|
||||
redeemHelp: describeRedeemCodes(this.#redeemCodes),
|
||||
freePaymentLabel: this.#freePaymentLabel,
|
||||
}, `store web state (${account?.userId ?? 'no account'})`);
|
||||
}
|
||||
|
||||
@@ -94,7 +104,10 @@ export class StoreWebApi {
|
||||
return true;
|
||||
});
|
||||
const modeTag = isFree ? 'free' : 'gjn';
|
||||
return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
|
||||
return jsonResponse(
|
||||
{ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree, this.#freePaymentLabel) },
|
||||
`store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`,
|
||||
);
|
||||
}
|
||||
|
||||
#cart(request: ServiceRequest): ServiceResponse {
|
||||
@@ -153,7 +166,7 @@ export class StoreWebApi {
|
||||
return false;
|
||||
}
|
||||
const outcome = buyStoreCart(profile, products, payMethod, now);
|
||||
message = checkoutMessage(outcome, products, payMethod);
|
||||
message = checkoutMessage(outcome, products, payMethod, this.#freePaymentLabel);
|
||||
if (!outcome.ok) return false;
|
||||
clearStoreCart(profile);
|
||||
cartProductIds = [];
|
||||
@@ -177,13 +190,18 @@ export class StoreWebApi {
|
||||
}
|
||||
}
|
||||
|
||||
function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText {
|
||||
function purchaseMessage(
|
||||
outcome: GjnPurchaseOutcome,
|
||||
product: StoreProduct,
|
||||
isFree: boolean,
|
||||
freePaymentLabel: LocalizedText,
|
||||
): LocalizedText {
|
||||
const cost = gjnText(product.gjnCostCents ?? 0);
|
||||
if (outcome.ok) {
|
||||
return isFree
|
||||
? {
|
||||
zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
|
||||
en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`,
|
||||
zh: `已通过「${freePaymentLabel.zh}」获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
|
||||
en: `Claimed "${product.title.en}" via "${freePaymentLabel.en}". Close the store window to refresh the hangar.`,
|
||||
}
|
||||
: {
|
||||
zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`,
|
||||
@@ -191,7 +209,10 @@ function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isF
|
||||
};
|
||||
}
|
||||
if (outcome.reason === 'NOT_ENOUGH_GJN') {
|
||||
return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` };
|
||||
return {
|
||||
zh: `GJN 不够:需要 ${cost} GJN。可直接点「${freePaymentLabel.zh}」,或在"兑换码"页用 GJN 充值码补充。`,
|
||||
en: `Not enough GJN: ${cost} GJN needed. Use "${freePaymentLabel.en}" or a GJN code on the Redeem tab.`,
|
||||
};
|
||||
}
|
||||
if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product);
|
||||
return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' };
|
||||
@@ -208,19 +229,23 @@ function checkoutMessage(
|
||||
outcome: StoreCheckoutOutcome,
|
||||
products: readonly StoreProduct[],
|
||||
payMethod: 'gjn' | 'free',
|
||||
freePaymentLabel: LocalizedText,
|
||||
): LocalizedText {
|
||||
if (outcome.ok) {
|
||||
const count = products.length;
|
||||
const cost = gjnText(outcome.costCents);
|
||||
return payMethod === 'free'
|
||||
? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
|
||||
en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` }
|
||||
? { zh: `已通过「${freePaymentLabel.zh}」领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
|
||||
en: `Claimed ${count} items via "${freePaymentLabel.en}". Close the store to refresh the hangar.` }
|
||||
: { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`,
|
||||
en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` };
|
||||
}
|
||||
if (outcome.reason === 'NOT_ENOUGH_GJN') {
|
||||
const cost = gjnText(outcome.costCents);
|
||||
return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` };
|
||||
return {
|
||||
zh: `购物车共需 ${cost} GJN,当前余额不足。可直接点「${freePaymentLabel.zh}」。`,
|
||||
en: `Your cart costs ${cost} GJN. Your balance is too low. Use "${freePaymentLabel.en}" instead.`,
|
||||
};
|
||||
}
|
||||
const product = products.find((item) => item.id === outcome.productId);
|
||||
return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT;
|
||||
|
||||
@@ -9,7 +9,7 @@ const T = {
|
||||
search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级',
|
||||
sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低',
|
||||
containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户',
|
||||
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号',
|
||||
buy: '购买', freeBuy: '直接获取', owned: '已拥有', pickAccount: '请先选择账号',
|
||||
redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品',
|
||||
featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格',
|
||||
includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益',
|
||||
@@ -31,7 +31,7 @@ const T = {
|
||||
search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}',
|
||||
sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low',
|
||||
containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account',
|
||||
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first',
|
||||
buy: 'Buy', freeBuy: 'Direct Claim', owned: 'Owned', pickAccount: 'Pick an account first',
|
||||
redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters',
|
||||
featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price',
|
||||
includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses',
|
||||
@@ -53,7 +53,7 @@ const t = (key, params) => WtoUi.tr(T, key, params);
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
let initialGuid = (WtoUi.query.get('item') || '').toUpperCase();
|
||||
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] };
|
||||
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [], freePaymentLabel: null };
|
||||
let currentTab = 'vehicle-pack';
|
||||
let detailId = '';
|
||||
let catalogScroll = 0;
|
||||
@@ -61,9 +61,14 @@ let loadVersion = 0;
|
||||
let loading = true;
|
||||
const checkout = createStoreCheckout(loadState);
|
||||
|
||||
function freePaymentLabel() {
|
||||
return WtoUi.text(state.freePaymentLabel) || t('freeBuy');
|
||||
}
|
||||
|
||||
function applyStaticTexts() {
|
||||
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
|
||||
for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label));
|
||||
$('payFree').textContent = freePaymentLabel();
|
||||
$('searchInput').placeholder = t('search');
|
||||
$('codeInput').placeholder = t('codePlaceholder');
|
||||
$('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/');
|
||||
@@ -88,6 +93,7 @@ async function loadState(userId) {
|
||||
return await loadState('');
|
||||
}
|
||||
state = next;
|
||||
$('payFree').textContent = freePaymentLabel();
|
||||
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId);
|
||||
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
|
||||
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
|
||||
|
||||
@@ -2,19 +2,25 @@
|
||||
{
|
||||
// Set activity and squadron RP. The service reports maxActivityPerPeriod, maxClanActivity, rewardPeriodDays, and historyDepth in squadron replies.
|
||||
"activity": {
|
||||
"maxPerPeriod": 360, // Activity cap per reward period.
|
||||
"maxPerPeriod": 360, // Activity cap per reward period.
|
||||
"squadronRpPerFullPeriod": 20000, // Squadron RP awarded for a full activity period.
|
||||
"rewardPeriodDays": 3, // Reward period in days.
|
||||
"historyDepthDays": 14, // Activity history displayed by the client, in days.
|
||||
// Seed full periods on creation or joining so squadron research can start immediately.
|
||||
"startingPeriods": 3
|
||||
// Base vehicle RP from battles required for 1 squadron activity point (stock rule: 200 RP = 1 point).
|
||||
"rpPerActivityPoint": 200,
|
||||
// Starting current-period activity for a player creating or joining a squadron (0..maxPerPeriod).
|
||||
// Set to 360 together with startingPeriods > 0 in <data>/tuning/clans.jsonc to start at full activity immediately.
|
||||
"startingActivity": 0,
|
||||
// Full past activity periods granted on creation or joining (default 0: earn activity through battles).
|
||||
// Increase (e.g. 1 or 3) in <data>/tuning/clans.jsonc to grant immediate squadron RP on joining.
|
||||
"startingPeriods": 0
|
||||
},
|
||||
|
||||
// Set the full squadron cap and initial battalion cap. Expansion cost and step size are read from warpoints.blk.
|
||||
"memberLimits": { "normal": 128, "battalionInitial": 10 },
|
||||
|
||||
// Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier), so small NPC rosters can represent full squadrons.
|
||||
"leaderboard": { "activityMultiplier": 10, "maxActivity": 100000 },
|
||||
// Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier).
|
||||
"leaderboard": { "activityMultiplier": 1, "maxActivity": 100000 },
|
||||
|
||||
// Starting ID for player-created squadrons.
|
||||
"firstNewClanId": 600001,
|
||||
@@ -29,6 +35,37 @@
|
||||
"presetClans": {
|
||||
"createdDaysAgo": 180, // Age of the first seeded squadron before applying each squadron's createdAfterDays offset.
|
||||
"memberJoinSpacingMinutes": 60,
|
||||
"npcHistoryPeriods": 3, // Past activity periods seeded for preset NPC members.
|
||||
// Deterministic filler NPC pool used when a preset clan's targetMemberCount exceeds its named roster.
|
||||
"fillerMembers": {
|
||||
"activityMin": 340,
|
||||
"activityMax": 360,
|
||||
"uidBase": 900000000,
|
||||
"uidStride": 1000,
|
||||
"callsigns": [
|
||||
"Vanguard", "Falcon", "Striker", "Sentinel", "Raptor", "Valkyrie",
|
||||
"Tempest", "Bastion", "Corsair", "Drago", "Harrier", "Kestrel",
|
||||
"Lancer", "Mirage", "Nomad", "Osprey", "Paladin", "Reaper",
|
||||
"Sabre", "Talon", "Vector", "Warden", "Zephyr", "Aegis",
|
||||
"Cobra", "Hornet", "Jaguar", "Lynx", "Mantis", "Puma"
|
||||
],
|
||||
"titles": [
|
||||
"title_pilot", "title_tankman", "title_ace", "title_sniper",
|
||||
"title_scout", "title_eagle", "title_tank_destroyer", "title_jet_powered"
|
||||
],
|
||||
"icons": [
|
||||
"cardicon_03", "cardicon_05", "cardicon_07", "cardicon_08",
|
||||
"cardicon_09", "cardicon_11", "cardicon_12", "cardicon_14",
|
||||
"cardicon_15", "cardicon_16", "cardicon_18", "cardicon_19",
|
||||
"cardicon_20", "cardicon_22", "cardicon_25", "cardicon_28"
|
||||
],
|
||||
"units": [
|
||||
"cn_ztz_99a", "su_27sm", "germ_leopard_2a7v", "f_14b",
|
||||
"jp_destroyer_shimakaze", "sw_strv_122b_plus", "j_11a", "jh_7a",
|
||||
"cn_vt_4a1", "f_15j_kai", "ussr_t_90m", "us_m1a2_sep2_abrams",
|
||||
"uk_challenger_2_black_night", "us_hstvl", "it_centauro_rgo_120"
|
||||
]
|
||||
},
|
||||
// Lifetime stats displayed for each seeded squadron.
|
||||
"stats": {
|
||||
"akills_arc": 4280, "akills_hist": 6150, "akills_sim": 1420,
|
||||
@@ -45,7 +82,7 @@
|
||||
"slogan": "离线天空与钢铁防线 · 自由研发全部联队载具",
|
||||
"desc": "War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。",
|
||||
"announcement": "欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。",
|
||||
"region": "CN / Global", "autoAccept": true, "createdAfterDays": 0,
|
||||
"region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, "targetMemberCount": 60,
|
||||
"rating": { "arc": 1840, "hist": 2150, "sim": 1620 },
|
||||
"members": [
|
||||
{ "uid": "900001001", "nick": "Lin_Wei", "role": "LEADER", "title": "title_marshall", "icon": "cardicon_28", "unit": "cn_ztz_99a", "activity": 360 },
|
||||
@@ -61,7 +98,7 @@
|
||||
"slogan": "鹰击长空 · 现代喷气空战与陆空协同联队",
|
||||
"desc": "专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。",
|
||||
"announcement": "本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。",
|
||||
"region": "Asia", "autoAccept": true, "createdAfterDays": 12,
|
||||
"region": "Asia", "autoAccept": true, "createdAfterDays": 12, "targetMemberCount": 60,
|
||||
"rating": { "arc": 1690, "hist": 2040, "sim": 1780 },
|
||||
"members": [
|
||||
{ "uid": "900002001", "nick": "SkyDragon_J20", "role": "LEADER", "title": "title_ace", "icon": "cardicon_25", "unit": "j_11a", "activity": 360 },
|
||||
@@ -75,7 +112,7 @@
|
||||
"slogan": "Steel & Fire — Heavy Armor Historical Squadron",
|
||||
"desc": "Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.",
|
||||
"announcement": "Squadron vehicles ready for research at full 20,000 RP per period.",
|
||||
"region": "EU / Global", "autoAccept": true, "createdAfterDays": 24,
|
||||
"region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, "targetMemberCount": 60,
|
||||
"rating": { "arc": 1920, "hist": 1980, "sim": 1510 },
|
||||
"members": [
|
||||
{ "uid": "900003001", "nick": "Kommissar_KVs", "role": "LEADER", "title": "title_hero", "icon": "cardicon_22", "unit": "ussr_t_90m", "activity": 360 },
|
||||
@@ -88,7 +125,7 @@
|
||||
"slogan": "All The Way — Air, Ground & Naval Task Force",
|
||||
"desc": "需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。",
|
||||
"announcement": "Manual application review enabled for testing request/cancel workflow.",
|
||||
"region": "NA", "autoAccept": false, "createdAfterDays": 35,
|
||||
"region": "NA", "autoAccept": false, "createdAfterDays": 35, "targetMemberCount": 58,
|
||||
"rating": { "arc": 1550, "hist": 1760, "sim": 1490 },
|
||||
"members": [
|
||||
{ "uid": "900004001", "nick": "Major_Winters", "role": "LEADER", "title": "title_brother_in_arms", "icon": "cardicon_03", "unit": "us_m1a2_sep2_abrams", "activity": 360 },
|
||||
@@ -100,7 +137,7 @@
|
||||
"slogan": "轻量级战术分队 · 侦察与快速反应",
|
||||
"desc": "战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。",
|
||||
"announcement": "轻装侦察分队常驻开放。",
|
||||
"region": "Global", "autoAccept": true, "createdAfterDays": 48,
|
||||
"region": "Global", "autoAccept": true, "createdAfterDays": 48, "targetMemberCount": 2,
|
||||
"rating": { "arc": 1410, "hist": 1610, "sim": 1320 },
|
||||
"members": [
|
||||
{ "uid": "900005001", "nick": "Ghost_Scout", "role": "LEADER", "title": "title_scout", "icon": "cardicon_15", "unit": "us_hstvl", "activity": 360 },
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// Local store products and prices.
|
||||
// The client receives these prices from the local server.
|
||||
{
|
||||
// Button label for the no-GJN offline payment method shown in the in-game payment dialog,
|
||||
// local web store, and local marketplace. Players can override it in <data>/tuning/store.jsonc.
|
||||
"freePaymentLabel": { "zh": "直接获取", "en": "Direct Claim" },
|
||||
|
||||
// GJN prices use the official USD prices at 1 GJN per USD.
|
||||
|
||||
// Golden Eagle packs use GJN in both the in-game payment dialog and the local web store.
|
||||
|
||||
Reference in new issue
Block a user