From c957cecee41447c27a8a954f2664615f4e2f6d70 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:55:23 +0800 Subject: [PATCH] Support save archives and copy transfers --- apps/launcher/src/main/ipc/handlers.ts | 10 +- .../main/services/launch/launch-controller.ts | 8 + .../src/main/services/saves/manage-saves.ts | 107 +++++++++- .../src/main/services/saves/save-archive.ts | 194 ++++++++++++++++++ .../src/main/workers/save-protocol.ts | 4 +- apps/launcher/src/main/workers/save-worker.ts | 7 +- apps/launcher/src/renderer/src/App.tsx | 2 +- .../src/renderer/src/i18n/locales/en.json | 25 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 25 ++- .../renderer/src/pages/saves/SaveBackups.tsx | 76 +++++++ .../renderer/src/pages/saves/SavesPage.tsx | 103 ++++++++-- .../src/renderer/src/shell/navigation.ts | 2 +- apps/launcher/src/shared/errors.ts | 1 + apps/launcher/src/shared/ipc/contract.ts | 30 ++- apps/launcher/src/shared/schemas/saves.ts | 14 ++ apps/launcher/src/shared/schemas/settings.ts | 2 + apps/server/src/accounts/account-store.ts | 10 + apps/server/src/index.ts | 1 + apps/server/src/saves/transferred-profile.ts | 64 ++++++ 19 files changed, 660 insertions(+), 25 deletions(-) create mode 100644 apps/launcher/src/main/services/saves/save-archive.ts create mode 100644 apps/launcher/src/renderer/src/pages/saves/SaveBackups.tsx create mode 100644 apps/server/src/saves/transferred-profile.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index b3b4d7b..4fa1cb8 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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', () => { diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index 1f4aa2e..e71497d 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -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 { 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({ diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 859c136..379a986 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -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 { + 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 { + 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 { + const copy = await requireCopy(copyId); + return backupList(copy, userId); +} + +export async function takeSaveBackup(copyId: string, userId: string): Promise { + 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 { + 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 { + 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(operation: () => Promise): Promise { if (writing || launchInProgress() || maintenanceInProgress()) throw new AppError('save_read_only'); writing = true; @@ -69,6 +168,10 @@ async function write(operation: () => Promise): Promise { 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; } diff --git a/apps/launcher/src/main/services/saves/save-archive.ts b/apps/launcher/src/main/services/saves/save-archive.ts new file mode 100644 index 0000000..7173fb8 --- /dev/null +++ b/apps/launcher/src/main/services/saves/save-archive.ts @@ -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; +} + +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 { + 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 { + 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 { + 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 { + 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 { + 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(copy: InstallRecord, userId: string, operation: (folder: string, work: string) => Promise): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + return readArchive(join(await backupFolder(copy, userId), SaveBackupNameSchema.parse(name))); +} diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts index 63db988..f686429 100644 --- a/apps/launcher/src/main/workers/save-protocol.ts +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -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 }; diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts index 46a3119..8e742da 100644 --- a/apps/launcher/src/main/workers/save-worker.ts +++ b/apps/launcher/src/main/workers/save-worker.ts @@ -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) { diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index e95f69a..225fff6 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -134,7 +134,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { return { side: t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />, main: record - ? + ? :

{t('saves.noCopy')}

, bar: home, }; diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index b443b6e..787aebf 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -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.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 9ab6870..f903358 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -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": "存档操作失败。请查看启动器日志。", diff --git a/apps/launcher/src/renderer/src/pages/saves/SaveBackups.tsx b/apps/launcher/src/renderer/src/pages/saves/SaveBackups.tsx new file mode 100644 index 0000000..abfe6f3 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/saves/SaveBackups.tsx @@ -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([]); + const [automatic, setAutomatic] = useState(true); + const [busy, setBusy] = useState(false); + const [restore, setRestore] = useState(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 ( + <> + + { + ipcInvoke('settings:update', { autoSaveBackups: event.target.checked }) + .then((settings) => setAutomatic(settings.autoSaveBackups)).catch(onError); + }} /> + + {readOnly &&

{t('saves.readOnly')}

} + + {backups.length === 0 &&

{t('saves.archive.noBackups')}

} + {backups.map((backup) => ( + + {formatBytes(backup.size)} + + + ))} + {restore && ( +
+

{t('saves.archive.confirmRestore')}

+
+ + +
+
+ )} + + ); +} diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index c4f86e0..3258cc4 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -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(null); const [details, setDetails] = useState(null); const [creating, setCreating] = useState(false); + const [source, setSource] = useState(null); + const [selectingSource, setSelectingSource] = useState(false); + const [other, setOther] = useState<{ copyId: string; saves: SaveList['saves'] } | null>(null); + const [deleting, setDeleting] = useState(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): 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 ( {readOnly &&

{t('saves.readOnly')}

} - +
+ + + +
+ {selectingSource && ( +
+ + + + {other?.saves.map((save) => ( + + ))} + {other && other.saves.length === 0 &&

{t('saves.empty')}

} +
+ )} {creating && (
@@ -100,7 +146,7 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps) {message &&

{message}

}
- +
)} @@ -119,14 +165,40 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps)
{t('saves.battles')}
{format.format(save.battleCount)}
{t('saves.lastBattle')}
{date(save.lastBattle)}
- {save.userId !== list.current && ( - - )} +
+ {save.userId !== list.current && ( + + )} + + + +
))} + {deleting && ( +
+

{t('saves.archive.confirmDelete', { name: deleting.nick })}

+
+ + +
+
+ )}
); } @@ -164,6 +236,7 @@ export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps) )) )} + {section === 'backup' && } {section === 'vehicles' && ( <> {details.owned.length ? details.owned.join(', ') : '—'} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index 27043e2..1be9db2 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -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; diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 0f9a1a5..e0b83ae 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -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', diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 96e2ede..b3dbd94 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -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, diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index 606f61f..2bf19a2 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -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; +export type SaveBackup = z.output; + export type SaveList = z.output; export type SaveDetails = z.output; export type CurrencyEdits = z.output; diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index edc4e21..2297e2f 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -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(), diff --git a/apps/server/src/accounts/account-store.ts b/apps/server/src/accounts/account-store.ts index ecc02d5..5631fd6 100644 --- a/apps/server/src/accounts/account-store.ts +++ b/apps/server/src/accounts/account-store.ts @@ -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). diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 52bd867..39b966c 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -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'; diff --git a/apps/server/src/saves/transferred-profile.ts b/apps/server/src/saves/transferred-profile.ts new file mode 100644 index 0000000..e6ad947 --- /dev/null +++ b/apps/server/src/saves/transferred-profile.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(); + const weapons = new Set(); + 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); +}