feat(saves): add save archives and copy transfers

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:55:23 +08:00
1 parent 073a907617
commit d0a767e692
19 files changed
+660 -25

No files matched your search

+9 -1
View File
@@ -13,7 +13,7 @@ import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentC
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { createSave, getSaveDetails, getSaveList, saveWriteInProgress, selectSave, setSaveCurrencies } from '../services/saves/manage-saves.ts';
import { createSave, exportSave, getSaveDetails, getSaveList, listSaveBackups, pickSaveArchive, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -110,6 +110,14 @@ export function registerIpcHandlers(): void {
handle('saves:create', (request) => createSave(request));
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
handle('saves:pickArchive', (_input, sender) => pickSaveArchive(BrowserWindow.fromWebContents(sender)));
handle('saves:export', ({ copyId, userId }, sender) => exportSave(copyId, userId, BrowserWindow.fromWebContents(sender)));
handle('saves:transfer', (request) => transferSave(request));
handle('saves:delete', ({ copyId, userId }) => removeSave(copyId, userId));
handle('saves:listBackups', ({ copyId, userId }) => listSaveBackups(copyId, userId));
handle('saves:takeBackup', ({ copyId, userId }) => takeSaveBackup(copyId, userId));
handle('saves:restoreBackup', ({ copyId, userId, name }) => restoreSaveBackup(copyId, userId, name));
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
@@ -4,12 +4,14 @@ import { createServer } from 'node:net';
import { isAbsolute, join, relative } from 'node:path';
import { promisify } from 'node:util';
import { BrowserWindow, shell } from 'electron';
import { AccountStore } from '@wto/server';
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
@@ -123,6 +125,12 @@ async function launch(job: LaunchJob): Promise<void> {
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
if (games) throw new AppError('launch_game_running');
await checkPort(lab.port);
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port: lab.port });
await buildCopy({
@@ -1,14 +1,16 @@
import { join } from 'node:path';
import { utilityProcess } from 'electron';
import { dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { CurrencyEdits, SaveDetails, SaveList, SaveRegistration } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { forwardProcessOutput } from '../launch/process-output.ts';
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
let writing = false;
@@ -61,6 +63,103 @@ 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 result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : result.filePaths[0] ?? null };
}
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 result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
try {
await writeArchive(result.filePath, await captureSave(copy, userId));
} catch (error) {
if (error instanceof AppError) throw error;
console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed');
}
return { path: result.filePath };
}
export async function transferSave({ source, copyId, login, password, nick }: SaveTransfer): Promise<SaveList> {
return write(async () => {
const target = await requireCopy(copyId);
let archive: SaveArchive;
if (source.kind === 'file') {
archive = await readArchive(source.path);
} else {
const parent = await requireCopy(source.copyId);
await getSaveDetails(parent.id, source.userId);
archive = await captureSave(parent, source.userId);
}
await validateProfile(archive, target);
const { userId } = await run({ operation: 'create', ...location(target), login, password, nick }) as { userId: string };
try {
await restoreDirectory(target, userId, archive);
} catch (error) {
await run({ operation: 'remove', ...location(target), userId }).catch((failure) =>
console.error('[saves] could not remove the unfinished registration:', failure));
throw error;
}
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
return getSaveList(copyId);
});
}
export async function removeSave(copyId: string, userId: string): Promise<SaveList> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
await changeSaveFolder(copy, userId, () => run({ operation: 'remove', ...location(copy), userId }));
if (copy.currentSaveId === userId) {
await updateCopyRecord(copyId, (record) => {
if (record.currentSaveId !== userId) return record;
const { currentSaveId: _removed, ...rest } = record;
return rest;
});
}
return getSaveList(copyId);
});
}
export async function listSaveBackups(copyId: string, userId: string): Promise<SaveBackup[]> {
const copy = await requireCopy(copyId);
return backupList(copy, userId);
}
export async function takeSaveBackup(copyId: string, userId: string): Promise<SaveBackup[]> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
await saveBackup(copy, userId, 'manual');
return backupList(copy, userId);
});
}
export async function restoreSaveBackup(copyId: string, userId: string, name: string): Promise<SaveDetails> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const archive = await archivedBackup(copy, userId, name);
await validateProfile(archive, copy);
await saveBackup(copy, userId, 'restore');
await restoreDirectory(copy, userId, archive);
return getSaveDetails(copyId, userId);
});
}
async function validateProfile(archive: SaveArchive, copy: InstallRecord): Promise<void> {
const profile = archive.files['profile.blk'];
if (!profile) return;
const filter = archive.gameVersion === null || copy.gameVersion === null ||
compareVersions(archive.gameVersion, copy.gameVersion) > 0;
archive.files['profile.blk'] = await run({ operation: 'filter', ...location(copy), profile, filter }) as Uint8Array;
}
async function write<T>(operation: () => Promise<T>): Promise<T> {
if (writing || launchInProgress() || maintenanceInProgress()) throw new AppError('save_read_only');
writing = true;
@@ -69,6 +168,10 @@ async function write<T>(operation: () => Promise<T>): Promise<T> {
throw new AppError('save_read_only');
}
return await operation();
} catch (error) {
if (error instanceof AppError) throw error;
console.error('[saves] could not write the save:', error);
throw new AppError('save_operation_failed');
} finally {
writing = false;
}
@@ -0,0 +1,194 @@
import { randomUUID } from 'node:crypto';
import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { unzipSync, zipSync } from 'fflate';
import { z } from 'zod';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { SaveBackupNameSchema, type SaveBackup } from '@shared/schemas/saves.ts';
import { fileInfo } from '../copies/change-copy-files.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
const MANIFEST = 'wto-save.json';
const FILES = [
'save.json', 'profile.blk',
'cloud-settings/meta.json',
'cloud-settings/GBT_GENERAL_SETTINGS.blk',
'cloud-settings/GBT_GENERAL_MACHINE_SETTINGS.blk',
'cloud-settings/GBT_GENERAL_STORAGE.blk',
] as const;
const LIMIT = 256 * 1024 * 1024;
const Manifest = z.object({ version: z.literal(1), gameVersion: z.string().nullable() });
const SavedInfo = z.object({ formatVersion: z.number().int().positive(), created: z.string(), updated: z.string() });
export interface SaveArchive {
readonly gameVersion: string | null;
readonly files: Record<string, Uint8Array>;
}
function saveFolder(copy: InstallRecord, userId: string): string {
if (!/^\d+$/.test(userId)) throw new AppError('save_not_found');
return join(copy.dataPath, 'saves', userId);
}
async function checkedSaveFolder(copy: InstallRecord, userId: string): Promise<string> {
const root = await canonicalCopyPath(copy.dataPath);
const folder = await canonicalCopyPath(saveFolder(copy, userId));
if (relative(join(root, 'saves', userId), folder) !== '') throw new AppError('save_archive_invalid');
return folder;
}
async function readFileIfRegular(file: string, root: string): Promise<Buffer | undefined> {
const stats = await fileInfo(file);
if (!stats) return undefined;
if (!stats.isFile() || !copyPathContains(root, await canonicalCopyPath(dirname(file)))) {
throw new AppError('save_archive_invalid');
}
if (stats.size > LIMIT) throw new AppError('save_archive_invalid');
return readFile(file);
}
export async function captureSave(copy: InstallRecord, userId: string): Promise<SaveArchive> {
const source = await checkedSaveFolder(copy, userId);
const files: SaveArchive['files'] = {};
for (const name of FILES) {
const data = await readFileIfRegular(join(source, name), source);
if (data) files[name] = data;
}
const archive = { gameVersion: copy.gameVersion, files };
validateSave(archive);
return archive;
}
export function encodeSave(archive: SaveArchive): Uint8Array {
const manifest = JSON.stringify({ version: 1, gameVersion: archive.gameVersion });
return zipSync({ ...archive.files, [MANIFEST]: Buffer.from(manifest, 'utf8') });
}
export async function readArchive(path: string): Promise<SaveArchive> {
try {
const raw = await readFileIfRegular(path, await canonicalCopyPath(dirname(path)));
if (!raw) throw new Error('Save archive missing.');
let expandedSize = 0;
const files = unzipSync(raw, { filter(file) {
expandedSize += file.originalSize;
if (expandedSize > LIMIT || (file.name !== MANIFEST && !(FILES as readonly string[]).includes(file.name))) {
throw new Error('Unexpected contents in a save archive.');
}
return true;
} });
const manifest = files[MANIFEST];
if (!manifest) throw new Error('Save manifest missing.');
const { gameVersion } = Manifest.parse(JSON.parse(Buffer.from(manifest).toString('utf8')));
delete files[MANIFEST];
const archive = { gameVersion, files };
validateSave(archive);
return archive;
} catch (error) {
console.warn('[saves] could not open a save archive:', error);
throw new AppError('save_archive_invalid');
}
}
function validateSave(archive: SaveArchive): void {
const { files } = archive;
if (!!files['save.json'] !== !!files['profile.blk']) throw new AppError('save_archive_invalid');
if (files['save.json']) SavedInfo.parse(JSON.parse(Buffer.from(files['save.json']).toString('utf8')));
}
/** A save file is either replaced completely or the previous file remains available. */
export async function writeArchive(path: string, archive: SaveArchive): Promise<void> {
const temporary = path + '.' + randomUUID() + '.tmp';
try {
await writeFile(temporary, encodeSave(archive), { flag: 'wx' });
await rename(temporary, path);
} catch (error) {
await rm(temporary, { force: true }).catch(() => {});
throw error;
}
}
/** Keep the original directory beside the save until its replacement or account edit succeeds. */
export async function changeSaveFolder<T>(copy: InstallRecord, userId: string, operation: (folder: string, work: string) => Promise<T>): Promise<T> {
const folder = await checkedSaveFolder(copy, userId);
const parent = dirname(folder);
await mkdir(parent, { recursive: true });
const work = await mkdtemp(join(parent, '.wto-save-'));
const original = join(work, 'original');
let moved = false;
let keepOriginal = false;
try {
if (await fileInfo(folder)) {
await rename(folder, original);
moved = true;
}
return await operation(folder, work);
} catch (error) {
if (moved) {
try {
await rename(original, folder);
} catch (failure) {
keepOriginal = true;
console.error('[saves] could not restore the save directory. The original is at', original, failure);
}
}
throw error;
} finally {
if (!keepOriginal && relative(parent, dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[saves] clearing temporary files failed:', work, error));
}
}
}
export async function restoreDirectory(copy: InstallRecord, userId: string, archive: SaveArchive): Promise<void> {
await changeSaveFolder(copy, userId, async (folder, work) => {
const staging = join(work, 'incoming');
await mkdir(staging);
for (const name of FILES) {
const bytes = archive.files[name];
if (!bytes) continue;
const path = join(staging, name);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, bytes, { flag: 'wx' });
}
await rename(staging, folder);
});
}
async function backupFolder(copy: InstallRecord, userId: string): Promise<string> {
if (!/^\d+$/.test(userId)) throw new AppError('save_not_found');
const root = await canonicalCopyPath(copy.dataPath);
const directory = join(root, 'save-backups', userId);
if (relative(directory, await canonicalCopyPath(directory)) !== '') throw new AppError('save_archive_invalid');
return directory;
}
export async function backupList(copy: InstallRecord, userId: string): Promise<SaveBackup[]> {
const path = await backupFolder(copy, userId);
if (!(await fileInfo(path))?.isDirectory()) return [];
const backups: SaveBackup[] = [];
for (const entry of (await readdir(path, { withFileTypes: true })).sort((a, b) => b.name.localeCompare(a.name))) {
if (!entry.isFile() || !SaveBackupNameSchema.safeParse(entry.name).success) continue;
const stats = await fileInfo(join(path, entry.name));
if (stats) backups.push({
name: entry.name, createdAt: stats.mtime.toISOString(),
type: entry.name.split('.')[1] as SaveBackup['type'], size: stats.size,
});
}
return backups;
}
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
const root = await backupFolder(copy, userId);
await mkdir(root, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
if (type === 'launch') {
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
for (const backup of older) await rm(join(root, backup.name), { force: true });
}
}
export async function archivedBackup(copy: InstallRecord, userId: string, name: string): Promise<SaveArchive> {
return readArchive(join(await backupFolder(copy, userId), SaveBackupNameSchema.parse(name)));
}
@@ -10,7 +10,9 @@ export type SaveTask = Location & (
| { readonly operation: 'list' }
| { readonly operation: 'details'; readonly userId: string }
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
| { readonly operation: 'remove'; readonly userId: string }
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
);
export type SaveResult = SaveList['saves'] | SaveDetails | { userId: string } | null;
export type SaveResult = SaveList['saves'] | SaveDetails | { userId: string } | Uint8Array | null;
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
@@ -1,5 +1,5 @@
import type { MessageEvent } from 'electron';
import { AccountStore, editSaveCurrencies, listSaveSummaries, readSaveDetails } from '@wto/server';
import { AccountStore, editSaveCurrencies, listSaveSummaries, prepareTransferredProfile, readSaveDetails } from '@wto/server';
import type { SaveTask, SaveReply } from './save-protocol.ts';
function execute(task: SaveTask): SaveReply {
@@ -13,6 +13,11 @@ function execute(task: SaveTask): SaveReply {
case 'edit':
return editSaveCurrencies(task, task.userId, task.values)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
case 'remove':
return new AccountStore(task.dataFolder).remove(task.userId)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
case 'filter':
return { ok: true, result: prepareTransferredProfile(task, task.profile, task.filter) };
case 'create': {
const result = new AccountStore(task.dataFolder).register(task.login, task.password, task.nick);
switch (result.kind) {
+1 -1
View File
@@ -134,7 +134,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
return {
side: <SubNav sections={SAVE_SECTIONS} active={route.saves} label={(section) => t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />,
main: record
? <SavesPage key={record.id} copy={record} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
bar: home,
};
@@ -257,7 +257,29 @@
"list": "All saves",
"overview": "Overview",
"battles": "Battle history",
"vehicles": "Vehicles and research"
"vehicles": "Vehicles and research",
"backup": "Backup and restore"
},
"archive": {
"fromCopy": "Copy from another copy",
"import": "Import save file…",
"sourceCopy": "Source copy",
"transfer": "Create from save",
"copy": "Copy",
"export": "Export…",
"delete": "Delete…",
"confirmDelete": "Delete the local account and save for {{name}}?",
"automatic": "Back up before launch",
"retention": "The latest 10 automatic backups are retained for each save.",
"backup": "Back up now",
"restore": "Restore",
"noBackups": "There are no backups for this save.",
"confirmRestore": "Restore this backup? The current save will be backed up first.",
"type": {
"manual": "Manual backup",
"launch": "Before launch",
"restore": "Before restore"
}
},
"create": "Create save",
"login": "Login",
@@ -398,6 +420,7 @@
"internal_error": "An internal launcher error occurred.",
"logs_folder_open_failed": "The launcher log folder could not be opened.",
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
"save_archive_invalid": "The selected file is not a supported WTOffline save archive.",
"save_not_found": "The selected save could not be found.",
"save_read_only": "Saves are read-only while the game or local server is running.",
"save_operation_failed": "The save operation failed. See the launcher log.",
@@ -257,7 +257,29 @@
"list": "全部存档",
"overview": "概览",
"battles": "战绩",
"vehicles": "载具与研发"
"vehicles": "载具与研发",
"backup": "备份与还原"
},
"archive": {
"fromCopy": "从其他副本复制",
"import": "导入存档文件…",
"sourceCopy": "来源副本",
"transfer": "创建存档",
"copy": "复制",
"export": "导出…",
"delete": "删除…",
"confirmDelete": "确认删除 {{name}} 的本地账号和存档?",
"automatic": "启动前自动备份",
"retention": "每个存档保留最近 10 份自动备份。",
"backup": "立即备份",
"restore": "还原",
"noBackups": "此存档没有备份。",
"confirmRestore": "还原此备份?将先备份当前存档。",
"type": {
"manual": "手动备份",
"launch": "启动前自动备份",
"restore": "还原前自动备份"
}
},
"create": "新建存档",
"login": "登录账号",
@@ -398,6 +420,7 @@
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"save_archive_invalid": "所选文件不是受支持的 WTOffline 存档归档。",
"save_not_found": "找不到所选存档。",
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
"save_operation_failed": "存档操作失败。请查看启动器日志。",
@@ -0,0 +1,76 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { SaveBackup, SaveDetails } from '@shared/schemas/saves.ts';
import { Row } from '../../components/Row.tsx';
import { formatBytes } from '../../format.ts';
import { ipcInvoke } from '../../ipc.ts';
interface Props {
readonly copyId: string;
readonly userId: string;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
readonly onRestored: (details: SaveDetails) => void;
}
export function SaveBackups({ copyId, userId, readOnly, onError, onRestored }: Props) {
const { t, i18n } = useTranslation();
const [backups, setBackups] = useState<SaveBackup[]>([]);
const [automatic, setAutomatic] = useState(true);
const [busy, setBusy] = useState(false);
const [restore, setRestore] = useState<SaveBackup | null>(null);
const keys = { copyId, userId };
useEffect(() => {
let mounted = true;
Promise.all([ipcInvoke('saves:listBackups', { copyId, userId }), ipcInvoke('settings:get')]).then(([list, settings]) => {
if (!mounted) return;
setBackups(list);
setAutomatic(settings.autoSaveBackups);
}).catch(onError);
return () => { mounted = false; };
}, [copyId, userId, onError]);
function take(): void {
setBusy(true);
ipcInvoke('saves:takeBackup', keys).then(setBackups).catch(onError).finally(() => setBusy(false));
}
function apply(name: string): void {
setBusy(true);
ipcInvoke('saves:restoreBackup', { ...keys, name }).then(async (details) => {
onRestored(details);
setRestore(null);
setBackups(await ipcInvoke('saves:listBackups', keys));
}).catch(onError).finally(() => setBusy(false));
}
return (
<>
<Row label={t('saves.archive.automatic')} hint={t('saves.archive.retention')}>
<input type="checkbox" aria-label={t('saves.archive.automatic')} checked={automatic} onChange={(event) => {
ipcInvoke('settings:update', { autoSaveBackups: event.target.checked })
.then((settings) => setAutomatic(settings.autoSaveBackups)).catch(onError);
}} />
</Row>
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
<button type="button" className="button" disabled={busy || readOnly} onClick={take}>{t('saves.archive.backup')}</button>
{backups.length === 0 && <p className="lead">{t('saves.archive.noBackups')}</p>}
{backups.map((backup) => (
<Row key={backup.name} label={new Date(backup.createdAt).toLocaleString(i18n.language)} hint={t(`saves.archive.type.${backup.type}`)}>
<span>{formatBytes(backup.size)}</span>
<button type="button" className="button" disabled={busy || readOnly} onClick={() => setRestore(backup)}>{t('saves.archive.restore')}</button>
</Row>
))}
{restore && (
<div className="maintenance-confirm">
<p>{t('saves.archive.confirmRestore')}</p>
<div className="copy-list-actions">
<button type="button" className="button" disabled={busy} onClick={() => setRestore(null)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={busy || readOnly} onClick={() => apply(restore.name)}>{t('saves.archive.restore')}</button>
</div>
</div>
)}
</>
);
}
@@ -1,14 +1,16 @@
import { useEffect, useState, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { CurrencyEdits, SaveDetails, SaveList } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, SaveDetails, SaveList, SaveTransfer } from '@shared/schemas/saves.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { SaveSection } from '../../shell/navigation.ts';
import { SaveBackups } from './SaveBackups.tsx';
interface SavesPageProps {
readonly copy: InstallRecord;
readonly copies: readonly InstallRecord[];
readonly section: SaveSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
@@ -16,11 +18,15 @@ interface SavesPageProps {
const CURRENCIES = ['silverLions', 'goldenEagles', 'gjnCents', 'freeRp'] as const;
export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps) {
export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPageProps) {
const { t, i18n } = useTranslation();
const [list, setList] = useState<SaveList | null>(null);
const [details, setDetails] = useState<SaveDetails | null>(null);
const [creating, setCreating] = useState(false);
const [source, setSource] = useState<SaveTransfer['source'] | null>(null);
const [selectingSource, setSelectingSource] = useState(false);
const [other, setOther] = useState<{ copyId: string; saves: SaveList['saves'] } | null>(null);
const [deleting, setDeleting] = useState<SaveList['saves'][number] | null>(null);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState('');
const userId = list?.current ?? null;
@@ -45,6 +51,18 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
const date = (time: number | null): string => time ? new Date(time * 1000).toLocaleString(i18n.language) : '—';
const format = new Intl.NumberFormat(i18n.language);
const begin = (from: SaveTransfer['source'] | null): void => {
setSelectingSource(false);
setSource(from);
setMessage('');
setCreating(true);
};
const updateDetails = (updated: SaveDetails): void => {
setDetails(updated);
setList((current) => current && { ...current, saves: current.saves.map((save) => save.userId === updated.save.userId ? updated.save : save) });
};
const submitNew = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const data = new FormData(event.currentTarget);
@@ -55,7 +73,9 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
}
setSaving(true);
setMessage('');
ipcInvoke('saves:create', { copyId: copy.id, login: String(data.get('login') ?? ''), password, nick: String(data.get('nick') ?? '') })
const request = { copyId: copy.id, login: String(data.get('login') ?? ''), password, nick: String(data.get('nick') ?? '') };
const operation = source ? ipcInvoke('saves:transfer', { ...request, source }) : ipcInvoke('saves:create', request);
operation
.then((next) => { setList(next); setCreating(false); })
.catch(onError)
.finally(() => setSaving(false));
@@ -74,8 +94,7 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
setMessage('');
ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values })
.then((updated) => {
setDetails(updated);
setList((current) => current && { ...current, saves: current.saves.map((save) => save.userId === userId ? updated.save : save) });
updateDetails(updated);
setMessage(t('saves.saved'));
})
.catch(onError)
@@ -87,10 +106,37 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
return (
<Sheet title={title} aside={copy.name}>
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
<button type="button" className="button button-primary" disabled={readOnly || creating} onClick={() => {
setMessage('');
setCreating(true);
}}>{t('saves.create')}</button>
<div className="copy-list-actions">
<button type="button" className="button button-primary" disabled={readOnly || creating} onClick={() => begin(null)}>{t('saves.create')}</button>
<button type="button" className="button" disabled={readOnly || creating || copies.length <= 1} onClick={() => setSelectingSource(!selectingSource)}>
{t('saves.archive.fromCopy')}
</button>
<button type="button" className="button" disabled={readOnly || creating} onClick={() => {
ipcInvoke('saves:pickArchive').then(({ path }) => { if (path) begin({ kind: 'file', path }); }).catch(onError);
}}>{t('saves.archive.import')}</button>
</div>
{selectingSource && (
<div className="maintenance-confirm">
<Row label={t('saves.archive.sourceCopy')}>
<select className="select" aria-label={t('saves.archive.sourceCopy')} value={other?.copyId ?? ''} onChange={(event) => {
const copyId = event.target.value;
if (!copyId) { setOther(null); return; }
setOther({ copyId, saves: [] });
ipcInvoke('saves:list', { copyId }).then(({ saves }) =>
setOther((previous) => previous?.copyId === copyId ? { copyId, saves } : previous)).catch(onError);
}}>
<option value="">{t('folder.none')}</option>
{copies.filter(({ id }) => id !== copy.id).map(({ id, name }) => <option key={id} value={id}>{name}</option>)}
</select>
</Row>
{other?.saves.map((save) => (
<button key={save.userId} type="button" className="button" onClick={() => begin({ kind: 'save', copyId: other.copyId, userId: save.userId })}>
{save.nick} · {save.login}
</button>
))}
{other && other.saves.length === 0 && <p className="small">{t('saves.empty')}</p>}
</div>
)}
{creating && (
<form className="maintenance-confirm" onSubmit={submitNew}>
<Row label={t('saves.login')}><input className="input" aria-label={t('saves.login')} autoComplete="username" name="login" required /></Row>
@@ -100,7 +146,7 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
{message && <p className="error-text" role="alert">{message}</p>}
<div className="copy-list-actions">
<button type="button" className="button" disabled={saving} onClick={() => setCreating(false)}>{t('wizard.cancel')}</button>
<button type="submit" className="button button-primary" disabled={saving || readOnly}>{t('saves.create')}</button>
<button type="submit" className="button button-primary" disabled={saving || readOnly}>{t(source ? 'saves.archive.transfer' : 'saves.create')}</button>
</div>
</form>
)}
@@ -119,14 +165,40 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
<dt>{t('saves.battles')}</dt><dd>{format.format(save.battleCount)}</dd>
<dt>{t('saves.lastBattle')}</dt><dd>{date(save.lastBattle)}</dd>
</dl>
{save.userId !== list.current && (
<button type="button" className="button" onClick={() => {
ipcInvoke('saves:setCurrent', { copyId: copy.id, userId: save.userId }).then(setList).catch(onError);
}}>{t('copies.list.select')}</button>
)}
<div className="copy-list-actions">
{save.userId !== list.current && (
<button type="button" className="button" onClick={() => {
ipcInvoke('saves:setCurrent', { copyId: copy.id, userId: save.userId }).then(setList).catch(onError);
}}>{t('copies.list.select')}</button>
)}
<button type="button" className="button" disabled={readOnly || creating} onClick={() => begin({ kind: 'save', copyId: copy.id, userId: save.userId })}>
{t('saves.archive.copy')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('saves:export', { copyId: copy.id, userId: save.userId }).catch(onError)}>
{t('saves.archive.export')}
</button>
<button type="button" className="button" disabled={readOnly || saving} onClick={() => setDeleting(save)}>
{t('saves.archive.delete')}
</button>
</div>
</article>
))}
</div>
{deleting && (
<div className="maintenance-confirm">
<p>{t('saves.archive.confirmDelete', { name: deleting.nick })}</p>
<div className="copy-list-actions">
<button type="button" className="button" disabled={saving} onClick={() => setDeleting(null)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={readOnly || saving} onClick={() => {
setSaving(true);
ipcInvoke('saves:delete', { copyId: copy.id, userId: deleting.userId }).then((next) => {
setList(next);
setDeleting(null);
}).catch(onError).finally(() => setSaving(false));
}}>{t('saves.archive.delete')}</button>
</div>
</div>
)}
</Sheet>
);
}
@@ -164,6 +236,7 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
</Row>
))
)}
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
{section === 'vehicles' && (
<>
<Row label={t('saves.owned')}>{details.owned.length ? details.owned.join(', ') : '—'}</Row>
@@ -6,7 +6,7 @@
export const PAGES = ['home', 'saves', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles'] as const;
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'backup'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
+1
View File
@@ -18,6 +18,7 @@ export const APP_ERROR_CODES = [
'diagnostics_export_failed',
'copy_not_found',
'save_not_found',
'save_archive_invalid',
'save_read_only',
'save_operation_failed',
'save_login_invalid',
+29 -1
View File
@@ -15,7 +15,7 @@ import {
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { CurrencyEditsSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema } from '../schemas/saves.ts';
import { CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
/**
@@ -148,6 +148,34 @@ export const ipcContract = {
input: SaveKeysSchema.extend({ values: CurrencyEditsSchema }),
output: SaveDetailsSchema,
},
'saves:pickArchive': {
input: z.void(),
output: z.object({ path: z.string().nullable() }),
},
'saves:export': {
input: SaveKeysSchema,
output: z.object({ path: z.string().nullable() }),
},
'saves:transfer': {
input: SaveTransferSchema,
output: SaveListSchema,
},
'saves:delete': {
input: SaveKeysSchema,
output: SaveListSchema,
},
'saves:listBackups': {
input: SaveKeysSchema,
output: z.array(SaveBackupSchema),
},
'saves:takeBackup': {
input: SaveKeysSchema,
output: z.array(SaveBackupSchema),
},
'saves:restoreBackup': {
input: SaveKeysSchema.extend({ name: SaveBackupNameSchema }),
output: SaveDetailsSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
+14
View File
@@ -40,6 +40,20 @@ export const SaveRegistrationSchema = z.object({
copyId: CopyIdSchema, login: z.string(), password: z.string(), nick: z.string(),
});
export const SaveTransferSchema = SaveRegistrationSchema.extend({
source: z.discriminatedUnion('kind', [
z.object({ kind: z.literal('save'), copyId: CopyIdSchema, userId: LocalUserIdSchema }),
z.object({ kind: z.literal('file'), path: z.string().min(1) }),
]),
});
export const SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore)\.[0-9a-f-]{36}\.zip$/);
export const SaveBackupSchema = z.object({
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore']), size: z.number().int().nonnegative(),
});
export type SaveTransfer = z.output<typeof SaveTransferSchema>;
export type SaveBackup = z.output<typeof SaveBackupSchema>;
export type SaveList = z.output<typeof SaveListSchema>;
export type SaveDetails = z.output<typeof SaveDetailsSchema>;
export type CurrencyEdits = z.output<typeof CurrencyEditsSchema>;
@@ -16,6 +16,7 @@ export const SettingsSchema = z.object({
officialWallpapers: z.boolean().default(true),
windowClose: WindowCloseSchema.default('quit'),
afterGameStarts: AfterGameStartsSchema.default('minimize'),
autoSaveBackups: z.boolean().default(true),
developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null),
@@ -30,6 +31,7 @@ export const SettingsPatchSchema = z.object({
officialWallpapers: z.boolean().optional(),
windowClose: WindowCloseSchema.optional(),
afterGameStarts: AfterGameStartsSchema.optional(),
autoSaveBackups: z.boolean().optional(),
developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(),
+10
View File
@@ -78,6 +78,16 @@ export class AccountStore {
return account;
}
remove(userId: string): boolean {
const accounts = this.#file.accounts.filter((account) => account.userId !== userId);
if (accounts.length === this.#file.accounts.length) return false;
const file = { ...this.#file, accounts };
writeFileAtomic(this.#path, JSON.stringify(file, null, 2));
this.#file = file;
if (this.#lastSignedInUserId === userId) this.#lastSignedInUserId = undefined;
return true;
}
/**
* The account that most recently signed in during this service run (for defaulting the initial
* read-only account dropdown in the built-in browser; never used as a fallback on mutations).
+1
View File
@@ -7,4 +7,5 @@ export { AccountStore, type RegistrationResult } from './accounts/account-store.
export { REGISTRATION_PATH } from './accounts/registration-service.ts';
export { HEALTH_PATH } from './transport/http-listener.ts';
export { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
@@ -0,0 +1,64 @@
import { decodeBlk, encodeBlk, findBlock } from '@wto/blk';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { externalItemSources } from '../game-data/datasets/external-item-sources.ts';
import { itemCatalogue } from '../game-data/datasets/item-catalogue.ts';
import { unitNames } from '../game-data/datasets/unit-names.ts';
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { allCrews } from '../profile/profile-crews.ts';
import { ACTIVE_LISTS } from '../profile/profile-items.ts';
import { recordName } from '../profile/profile-modifications.ts';
import { loadTuning } from '../tuning/tuning.ts';
import type { SaveLocation } from './save-editor.ts';
/** Validate a transferred profile and retain only the destination's vehicle and item identifiers. */
export function prepareTransferredProfile(location: SaveLocation, bytes: Uint8Array, filter: boolean): Uint8Array {
const profile = decodeBlk(bytes);
if (!filter) return bytes;
const packs = new GameFiles(location.gameFolder);
const datasets = new DatasetCache(location.dataFolder, packs, () => {});
const catalogue = datasets.load(vehicleCatalogue);
const vehicles = new Set(catalogue.map(({ name }) => name));
const classic = datasets.load(itemCatalogue);
const itemIds = new Set(classic.map(({ name }) => name));
const tuning = loadTuning(location.dataFolder, () => {});
const inventory = new InventoryCatalogue(catalogue, datasets.load(unitNames), datasets.load(externalItemSources), classic, tuning);
const modifications = new Set<string>();
const weapons = new Set<string>();
for (const equipment of datasets.load(vehicleEquipment)) {
for (const mod of equipment.modifications) modifications.add(recordName(equipment.vehicle, mod.name));
for (const weapon of equipment.weapons) weapons.add(recordName(equipment.vehicle, weapon.name));
weapons.add(recordName(equipment.vehicle, 'custom_presets'));
}
const blockKeys = [
['hangar', vehicles], ['unitResearch', vehicles], ['weaponPresets', vehicles],
['modifications', modifications], ['modsResearch', modifications], ['weapons', weapons],
] as const;
for (const [key, allowed] of blockKeys) {
const collection = findBlock(profile, key);
if (collection) collection.blocks = collection.blocks.filter((entry) => allowed.has(entry.name));
}
for (const crew of allCrews(profile)) {
const aircraft = findBlock(crew, 'aircrafts');
if (aircraft) {
aircraft.params = aircraft.params.filter(({ name, value }) =>
(name !== 'current' && name !== 'trained') || value.type !== 'string' ||
value.value === '' || vehicles.has(value.value));
}
}
const items = findBlock(profile, 'items');
if (items) {
items.blocks = items.blocks.filter((entry) => itemIds.has(stringField(entry, 'id')));
const uids = new Set(items.blocks.map(({ name }) => name));
for (const key of ACTIVE_LISTS) {
const list = findBlock(profile, key);
if (list) list.params = list.params.filter(({ value }) => value.type !== 'string' || uids.has(value.value));
}
}
const coupons = findBlock(profile, 'extInventory');
if (coupons) coupons.blocks = coupons.blocks.filter((entry) => inventory.hasItemDef(intField(entry, 'itemDefId')));
return encodeBlk(profile);
}