feat(saves): import official game backups

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 16:03:31 +08:00
1 parent 2e3cc0aaec
commit 597df6b4f5
15 files changed
+661 -16

No files matched your search

+7 -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, exportSave, getSaveDetails, getSaveList, listSaveBackups, pickSaveArchive, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { createSave, exportSave, getSaveDetails, getSaveList, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, 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/. */
@@ -118,6 +118,12 @@ export function registerIpcHandlers(): void {
handle('saves:takeBackup', ({ copyId, userId }) => takeSaveBackup(copyId, userId));
handle('saves:restoreBackup', ({ copyId, userId, name }) => restoreSaveBackup(copyId, userId, name));
handle('saves:pickOfficialBackups', (_input, sender) => pickOfficialBackups(BrowserWindow.fromWebContents(sender)));
handle('saves:previewOfficial', ({ copyId, userId, paths, includeUsedVehicles }) =>
previewSelectedBackups(copyId, userId, paths, includeUsedVehicles));
handle('saves:importOfficial', ({ copyId, userId, paths, options }) =>
importSelectedBackups(copyId, userId, paths, options));
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
@@ -1,12 +1,12 @@
import { join } from 'node:path';
import { dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions } from '@wto/patcher';
import { isAbsolute, join } from 'node:path';
import { app, dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { CurrencyEdits, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, 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 { canonicalCopyPath, copyPathContains, 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';
@@ -152,6 +152,52 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
});
}
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return result.canceled ? [] : result.filePaths;
}
export async function previewSelectedBackups(
copyId: string, userId: string, paths: readonly string[], includeUsedVehicles: boolean,
): Promise<OfficialPreview> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected, includeUsedVehicles }) as OfficialPreview;
}
export async function importSelectedBackups(
copyId: string, userId: string, paths: readonly string[], options: OfficialImportOptions,
): Promise<OfficialPreview> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
const before = await captureSave(copy, userId);
await saveBackup(copy, userId, 'import');
try {
return await run({ operation: 'importOfficial', ...location(copy), userId, paths: selected, options }) as OfficialPreview;
} catch (error) {
await restoreDirectory(copy, userId, before);
throw error;
}
});
}
async function verifyBackupLocations(copy: InstallRecord, paths: readonly string[]): Promise<string[]> {
const documents = await canonicalCopyPath(join(app.getPath('documents'), 'My Games', 'WarThunder'));
const stock = copy.sourcePath && await canonicalCopyPath(copy.sourcePath);
return Promise.all(paths.map(async (path) => {
if (!isAbsolute(path)) throw new AppError('save_official_location');
const selected = await canonicalCopyPath(path);
if (isInSteamLibrary(selected) || copyPathContains(documents, selected) || (stock && copyPathContains(stock, selected))) {
throw new AppError('save_official_location');
}
return selected;
}));
}
async function validateProfile(archive: SaveArchive, copy: InstallRecord): Promise<void> {
const profile = archive.files['profile.blk'];
if (!profile) return;
@@ -1,5 +1,5 @@
import type { AppErrorCode } from '@shared/errors.ts';
import type { CurrencyEdits, SaveDetails, SaveList } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveDetails, SaveList } from '@shared/schemas/saves.ts';
interface Location {
readonly gameFolder: string;
@@ -10,9 +10,11 @@ export type SaveTask = Location & (
| { readonly operation: 'list' }
| { readonly operation: 'details'; readonly userId: string }
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean }
| { readonly operation: 'importOfficial'; readonly paths: readonly string[]; readonly userId: string; readonly options: OfficialImportOptions }
| { 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 } | Uint8Array | null;
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | { 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, prepareTransferredProfile, readSaveDetails } from '@wto/server';
import { AccountStore, editSaveCurrencies, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails } from '@wto/server';
import type { SaveTask, SaveReply } from './save-protocol.ts';
function execute(task: SaveTask): SaveReply {
@@ -13,6 +13,10 @@ 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 'previewOfficial':
return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) };
case 'importOfficial':
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options) };
case 'remove':
return new AccountStore(task.dataFolder).remove(task.userId)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
@@ -37,7 +41,8 @@ process.parentPort.once('message', (event: MessageEvent) => {
reply = execute(event.data as SaveTask);
} catch (error) {
console.error('[saves] the save operation failed:', error);
reply = { ok: false, error: 'save_operation_failed' };
const { operation } = event.data as SaveTask;
reply = { ok: false, error: operation === 'previewOfficial' || operation === 'importOfficial' ? 'save_official_invalid' : 'save_operation_failed' };
}
process.parentPort.postMessage(reply);
});
@@ -258,8 +258,27 @@
"overview": "Overview",
"battles": "Battle history",
"vehicles": "Vehicles and research",
"official": "Import official backup",
"backup": "Backup and restore"
},
"official": {
"files": "Backup files",
"fileHint": "Select copies of global.blk, machine.blk or storage.blk.",
"choose": "Choose files…",
"content": "Import contents",
"settings": "Game settings",
"unlock": "Unlock vehicles from presets",
"equipment": "Modifications",
"full": "All equipment",
"basic": "Essential equipment",
"stock": "Stock configuration",
"includeUsed": "Include other vehicles found in the backup",
"preview": "Preview",
"import": "Import",
"summary": "{{files}} file(s) · {{presets}} preset(s) · {{vehicles}} available vehicle(s)",
"omitted": "Unavailable vehicles to skip · {{names}}",
"done": "Backup imported. The previous save is available in Backup and restore."
},
"archive": {
"fromCopy": "Copy from another copy",
"import": "Import save file…",
@@ -278,7 +297,8 @@
"type": {
"manual": "Manual backup",
"launch": "Before launch",
"restore": "Before restore"
"restore": "Before restore",
"import": "Before import"
}
},
"create": "Create save",
@@ -420,6 +440,8 @@
"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_official_invalid": "The selected files are not supported official backup files.",
"save_official_location": "Choose backup files copied outside the official game's folders.",
"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.",
@@ -258,8 +258,27 @@
"overview": "概览",
"battles": "战绩",
"vehicles": "载具与研发",
"official": "导入正版备份",
"backup": "备份与还原"
},
"official": {
"files": "备份文件",
"fileHint": "请选择复制备份的 global.blk、machine.blk 或 storage.blk。",
"choose": "选择文件…",
"content": "导入内容",
"settings": "游戏设置",
"unlock": "解锁预设中的载具",
"equipment": "改装件",
"full": "完全体",
"basic": "基础生存配件",
"stock": "白板状态",
"includeUsed": "包含备份中的其他已用载具",
"preview": "预览",
"import": "导入",
"summary": "{{files}} 个文件 · {{presets}} 套预设 · {{vehicles}} 辆可用载具",
"omitted": "将跳过的不可用载具 · {{names}}",
"done": "备份已导入。原存档可在「备份与还原」中恢复。"
},
"archive": {
"fromCopy": "从其他副本复制",
"import": "导入存档文件…",
@@ -278,7 +297,8 @@
"type": {
"manual": "手动备份",
"launch": "启动前自动备份",
"restore": "还原前自动备份"
"restore": "还原前自动备份",
"import": "导入前自动备份"
}
},
"create": "新建存档",
@@ -420,6 +440,8 @@
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"save_official_invalid": "所选文件不是受支持的正版备份。",
"save_official_location": "请选择复制到正版目录以外的备份文件。",
"save_archive_invalid": "所选文件不是受支持的 WTOffline 存档归档。",
"save_not_found": "找不到所选存档。",
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
@@ -0,0 +1,105 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { OfficialImportOptions, OfficialPreview } from '@shared/schemas/saves.ts';
import { Row } from '../../components/Row.tsx';
import { ipcInvoke } from '../../ipc.ts';
const DEFAULTS: OfficialImportOptions = {
importSettings: true, unlockVehicles: true, includeUsedVehicles: false, equipment: 'full',
};
interface Props {
readonly copyId: string;
readonly userId: string;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
export function OfficialSaveImport({ copyId, userId, readOnly, onError }: Props) {
const { t } = useTranslation();
const [paths, setPaths] = useState<string[]>([]);
const [options, setOptions] = useState(DEFAULTS);
const [preview, setPreview] = useState<OfficialPreview | null>(null);
const [busy, setBusy] = useState(false);
const [imported, setImported] = useState(false);
const request = { copyId, userId, paths };
const choose = (): void => {
ipcInvoke('saves:pickOfficialBackups').then((selection) => {
if (selection.length === 0) return;
setPaths(selection);
setPreview(null);
setImported(false);
}).catch(onError);
};
const load = (): void => {
setBusy(true);
setImported(false);
ipcInvoke('saves:previewOfficial', { ...request, includeUsedVehicles: options.includeUsedVehicles })
.then(setPreview).catch(onError).finally(() => setBusy(false));
};
const apply = (): void => {
setBusy(true);
ipcInvoke('saves:importOfficial', { ...request, options }).then((value) => {
setPreview(value);
setImported(true);
}).catch(onError).finally(() => setBusy(false));
};
return (
<>
<Row label={t('saves.official.files')} hint={t('saves.official.fileHint')}>
<button type="button" className="button" onClick={choose} disabled={busy}>{t('saves.official.choose')}</button>
{paths.length > 0 && <span className="folder-path" title={paths.join('\n')}>{paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}</span>}
</Row>
<Row label={t('saves.official.content')}>
<label className="check check-inline">
<input type="checkbox" checked={options.importSettings} disabled={busy} onChange={(event) => {
setOptions({ ...options, importSettings: event.target.checked });
}} />
{t('saves.official.settings')}
</label>
<label className="check check-inline">
<input type="checkbox" checked={options.unlockVehicles} disabled={busy} onChange={(event) => {
setOptions({ ...options, unlockVehicles: event.target.checked });
}} />
{t('saves.official.unlock')}
</label>
</Row>
<Row label={t('saves.official.equipment')}>
<select className="select" aria-label={t('saves.official.equipment')} value={options.equipment} disabled={busy || !options.unlockVehicles}
onChange={(event) => setOptions({ ...options, equipment: event.target.value as OfficialImportOptions['equipment'] })}>
<option value="full">{t('saves.official.full')}</option>
<option value="basic">{t('saves.official.basic')}</option>
<option value="stock">{t('saves.official.stock')}</option>
</select>
<label className="check check-inline">
<input type="checkbox" checked={options.includeUsedVehicles} disabled={busy || !options.unlockVehicles} onChange={(event) => {
setOptions({ ...options, includeUsedVehicles: event.target.checked });
setPreview(null);
setImported(false);
}} />
{t('saves.official.includeUsed')}
</label>
</Row>
<div className="copy-list-actions">
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={load}>{t('saves.official.preview')}</button>
<button type="button" className="button button-primary"
disabled={busy || readOnly || !preview || imported || (!options.importSettings && !options.unlockVehicles)} onClick={apply}>
{t('saves.official.import')}
</button>
</div>
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
{preview && (
<div className="maintenance-confirm">
<p>{t('saves.official.summary', { files: preview.files.length, presets: preview.presets.length, vehicles: preview.vehicles.length })}</p>
{preview.presets.map((preset, index) => <p key={index}>{preset.title} · {preset.vehicles.join(', ')}</p>)}
{preview.omitted.length > 0 && <p>{t('saves.official.omitted', { names: preview.omitted.join(', ') })}</p>}
</div>
)}
{imported && <p className="small" role="status">{t('saves.official.done')}</p>}
</>
);
}
@@ -6,6 +6,7 @@ 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 { OfficialSaveImport } from './OfficialSaveImport.tsx';
import { SaveBackups } from './SaveBackups.tsx';
interface SavesPageProps {
@@ -236,6 +237,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
</Row>
))
)}
{section === 'official' && <OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
{section === 'vehicles' && (
<>
@@ -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', 'backup'] as const;
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
+2
View File
@@ -19,6 +19,8 @@ export const APP_ERROR_CODES = [
'copy_not_found',
'save_not_found',
'save_archive_invalid',
'save_official_invalid',
'save_official_location',
'save_read_only',
'save_operation_failed',
'save_login_invalid',
+13 -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, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
/**
@@ -176,6 +176,18 @@ export const ipcContract = {
input: SaveKeysSchema.extend({ name: SaveBackupNameSchema }),
output: SaveDetailsSchema,
},
'saves:pickOfficialBackups': {
input: z.void(),
output: z.array(z.string()),
},
'saves:previewOfficial': {
input: SaveOfficialRequestSchema.extend({ includeUsedVehicles: z.boolean() }),
output: OfficialPreviewSchema,
},
'saves:importOfficial': {
input: SaveOfficialRequestSchema.extend({ options: OfficialImportOptionsSchema }),
output: OfficialPreviewSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
+18 -2
View File
@@ -46,11 +46,27 @@ export const SaveTransferSchema = SaveRegistrationSchema.extend({
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 SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore|import)\.[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(),
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import']), size: z.number().int().nonnegative(),
});
export const SaveOfficialRequestSchema = SaveKeysSchema.extend({
paths: z.array(z.string().min(1)).min(1).max(3),
});
export const OfficialImportOptionsSchema = z.object({
importSettings: z.boolean(), unlockVehicles: z.boolean(), includeUsedVehicles: z.boolean(),
equipment: z.enum(['full', 'basic', 'stock']),
});
export const OfficialPreviewSchema = z.object({
files: z.array(z.object({ name: z.string(), version: z.number().int() })),
presets: z.array(z.object({ country: z.string(), title: z.string(), vehicles: z.array(z.string()) })),
vehicles: z.array(z.string()),
omitted: z.array(z.string()),
});
export type OfficialPreview = z.output<typeof OfficialPreviewSchema>;
export type OfficialImportOptions = z.output<typeof OfficialImportOptionsSchema>;
export type SaveTransfer = z.output<typeof SaveTransferSchema>;
export type SaveBackup = z.output<typeof SaveBackupSchema>;