Import official game backups into local saves
This commit is contained in:
1 parent
20a5b3ebf1
commit
19990fc9de
15 files changed
+661
-16
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>;
|
||||
|
||||
|
||||
@@ -7,5 +7,6 @@ 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 { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
|
||||
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
|
||||
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
||||
@@ -0,0 +1,194 @@
|
||||
import { decodeBlk, emptyBlock, type BlkBlock, type BlkValue } from '@wto/blk';
|
||||
|
||||
/**
|
||||
* Parse the self-contained BLK documents exported by the game. The official Dagor text format
|
||||
* and the existing binary encoder use the same typed values and repeated names.
|
||||
*/
|
||||
export function readBackupBlk(bytes: Uint8Array): BlkBlock {
|
||||
try {
|
||||
return decodeBlk(bytes);
|
||||
} catch {
|
||||
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
return new TextBlock(text).read();
|
||||
}
|
||||
}
|
||||
|
||||
class TextBlock {
|
||||
readonly #text: string;
|
||||
#at = 0;
|
||||
|
||||
constructor(text: string) {
|
||||
this.#text = text;
|
||||
}
|
||||
|
||||
read(): BlkBlock {
|
||||
return this.#block('', 0);
|
||||
}
|
||||
|
||||
#block(name: string, depth: number): BlkBlock {
|
||||
if (depth > 128) this.#fail('Block nesting is too deep');
|
||||
const result = emptyBlock(name);
|
||||
for (;;) {
|
||||
this.#space();
|
||||
if (depth > 0 && this.#take('}')) return result;
|
||||
if (this.#at === this.#text.length) {
|
||||
if (depth > 0) this.#fail('Unclosed block');
|
||||
return result;
|
||||
}
|
||||
const key = this.#word();
|
||||
if (this.#take('{')) {
|
||||
result.blocks.push(this.#block(key, depth + 1));
|
||||
} else {
|
||||
this.#expect(':');
|
||||
const type = this.#word();
|
||||
const array = this.#take('[');
|
||||
if (array) this.#expect(']');
|
||||
this.#expect('=');
|
||||
if (array) {
|
||||
this.#expect('[');
|
||||
if (this.#take(']')) continue;
|
||||
do {
|
||||
result.params.push({ name: key, value: this.#value(type) });
|
||||
} while (this.#take(','));
|
||||
this.#expect(']');
|
||||
} else {
|
||||
result.params.push({ name: key, value: this.#value(type) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#value(type: string): BlkValue {
|
||||
switch (type) {
|
||||
case 't': return { type: 'string', value: this.#word() };
|
||||
case 'i': return { type: 'int', value: this.#int() };
|
||||
case 'i64': return { type: 'int64', value: this.#integer(64) };
|
||||
case 'r': return { type: 'real', value: this.#real() };
|
||||
case 'b': {
|
||||
const literal = this.#word().toLowerCase();
|
||||
if (['true', 'yes', 'on', '1'].includes(literal)) return { type: 'bool', value: true };
|
||||
if (['false', 'no', 'off', '0'].includes(literal)) return { type: 'bool', value: false };
|
||||
return this.#fail('Invalid Boolean');
|
||||
}
|
||||
case 'p2': return { type: 'point2', value: [this.#real(), this.#realAfterComma()] };
|
||||
case 'p3': return { type: 'point3', value: this.#row() };
|
||||
case 'p4': return { type: 'point4', value: [...this.#row(), this.#realAfterComma()] };
|
||||
case 'ip2': return { type: 'ipoint2', value: [this.#int(), this.#intAfterComma()] };
|
||||
case 'ip3': return { type: 'ipoint3', value: [this.#int(), this.#intAfterComma(), this.#intAfterComma()] };
|
||||
case 'ip4': return { type: 'ipoint4', value: [this.#int(), this.#intAfterComma(), this.#intAfterComma(), this.#intAfterComma()] };
|
||||
case 'c': {
|
||||
const [r, g, b] = [this.#int(), this.#intAfterComma(), this.#intAfterComma()];
|
||||
const a = this.#take(',') ? this.#int() : 255;
|
||||
if ([r, g, b, a].some((value) => value < 0 || value > 255)) this.#fail('Invalid color channel');
|
||||
return { type: 'color', value: ((a << 24) | (r << 16) | (g << 8) | b) >>> 0 };
|
||||
}
|
||||
case 'm': {
|
||||
const value: number[] = [];
|
||||
this.#expect('[');
|
||||
for (let row = 0; row < 4; row += 1) {
|
||||
this.#expect('[');
|
||||
value.push(...this.#row());
|
||||
this.#expect(']');
|
||||
if (row < 3) this.#take(',');
|
||||
}
|
||||
this.#expect(']');
|
||||
return { type: 'matrix', value };
|
||||
}
|
||||
default: return this.#fail('Unknown BLK type');
|
||||
}
|
||||
}
|
||||
|
||||
#row(): [number, number, number] {
|
||||
return [this.#real(), this.#realAfterComma(), this.#realAfterComma()];
|
||||
}
|
||||
|
||||
#realAfterComma(): number {
|
||||
this.#expect(',');
|
||||
return this.#real();
|
||||
}
|
||||
|
||||
#intAfterComma(): number {
|
||||
this.#expect(',');
|
||||
return this.#int();
|
||||
}
|
||||
|
||||
#int(): number {
|
||||
return Number(this.#integer(32));
|
||||
}
|
||||
|
||||
#integer(bits: number): bigint {
|
||||
const token = this.#word();
|
||||
if (!/^[+-]?(?:\d+|0x[\da-f]+)$/i.test(token)) this.#fail('Invalid integer');
|
||||
const negative = token.startsWith('-');
|
||||
const magnitude = BigInt(token.replace(/^[+-]/, ''));
|
||||
const value = negative ? -magnitude : magnitude;
|
||||
const limit = 1n << BigInt(bits - 1);
|
||||
if (value < -limit || value >= limit) this.#fail('Integer outside its BLK type');
|
||||
return value;
|
||||
}
|
||||
|
||||
#real(): number {
|
||||
const token = this.#word();
|
||||
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(token)) this.#fail('Invalid real number');
|
||||
const value = Number(token);
|
||||
if (!Number.isFinite(Math.fround(value))) this.#fail('Real number out of range');
|
||||
return value;
|
||||
}
|
||||
|
||||
#word(): string {
|
||||
this.#space();
|
||||
const quote = this.#text[this.#at];
|
||||
if (quote === '"' || quote === "'") {
|
||||
this.#at += 1;
|
||||
let output = '';
|
||||
while (this.#at < this.#text.length) {
|
||||
const char = this.#text[this.#at++]!;
|
||||
if (char === quote) return output;
|
||||
if (char !== '~') {
|
||||
output += char;
|
||||
continue;
|
||||
}
|
||||
const next = this.#text[this.#at++];
|
||||
if (next === undefined) this.#fail('Incomplete string escape');
|
||||
output += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
|
||||
}
|
||||
return this.#fail('Unclosed string');
|
||||
}
|
||||
const start = this.#at;
|
||||
while (this.#at < this.#text.length && !/[\s:={};,\[\]]/.test(this.#text[this.#at]!) &&
|
||||
!this.#text.startsWith('//', this.#at) && !this.#text.startsWith('/*', this.#at)) this.#at += 1;
|
||||
if (this.#at === start) this.#fail('Expected a name or value');
|
||||
return this.#text.slice(start, this.#at);
|
||||
}
|
||||
|
||||
#take(char: string): boolean {
|
||||
this.#space();
|
||||
if (this.#text[this.#at] !== char) return false;
|
||||
this.#at += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
#expect(char: string): void {
|
||||
if (!this.#take(char)) this.#fail('Expected ' + char);
|
||||
}
|
||||
|
||||
#space(): void {
|
||||
for (;;) {
|
||||
const char = this.#text[this.#at] ?? '';
|
||||
if (/[\s;]/.test(char)) this.#at += 1;
|
||||
else if (this.#text.startsWith('//', this.#at)) {
|
||||
const end = this.#text.indexOf('\n', this.#at + 2);
|
||||
this.#at = end === -1 ? this.#text.length : end + 1;
|
||||
} else if (this.#text.startsWith('/*', this.#at)) {
|
||||
const end = this.#text.indexOf('*/', this.#at + 2);
|
||||
if (end === -1) this.#fail('Unclosed comment');
|
||||
this.#at = end + 2;
|
||||
} else return;
|
||||
}
|
||||
}
|
||||
|
||||
#fail(message: string): never {
|
||||
const line = this.#text.slice(0, this.#at).split('\n').length;
|
||||
throw new Error(`${message} (line ${line})`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { lstatSync, readFileSync } from 'node:fs';
|
||||
import { basename } from 'node:path';
|
||||
import { encodeBlk, findBlock, type BlkBlock } from '@wto/blk';
|
||||
import { AccountStore } from '../../accounts/account-store.ts';
|
||||
import { ClanStore } from '../../clans/clan-store.ts';
|
||||
import { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
|
||||
import { DatasetCache } from '../../game-data/datasets/dataset-cache.ts';
|
||||
import { crewSlotPrices } from '../../game-data/datasets/rank-settings.ts';
|
||||
import { vehicleCatalogue } from '../../game-data/datasets/vehicle-catalogue.ts';
|
||||
import { GameFiles } from '../../game-data/game-files.ts';
|
||||
import { intField } from '../../profile/blk-fields.ts';
|
||||
import { addCrew, allCrews, crewOf, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
|
||||
import { addOwnedVehicle } from '../../profile/profile-hangar.ts';
|
||||
import { ownsModification, writeModificationRecord } from '../../profile/profile-modifications.ts';
|
||||
import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.ts';
|
||||
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
|
||||
import { loadTuning } from '../../tuning/tuning.ts';
|
||||
import type { SaveLocation } from '../save-editor.ts';
|
||||
import { readBackupBlk } from './backup-blk.ts';
|
||||
|
||||
const TYPES = {
|
||||
'global.blk': 'GBT_GENERAL_SETTINGS',
|
||||
'machine.blk': 'GBT_GENERAL_MACHINE_SETTINGS',
|
||||
'storage.blk': 'GBT_GENERAL_STORAGE',
|
||||
} as const;
|
||||
type BackupName = keyof typeof TYPES;
|
||||
|
||||
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
|
||||
|
||||
export interface OfficialImportOptions {
|
||||
readonly importSettings: boolean;
|
||||
readonly unlockVehicles: boolean;
|
||||
readonly includeUsedVehicles: boolean;
|
||||
readonly equipment: 'full' | 'basic' | 'stock';
|
||||
}
|
||||
|
||||
interface OfficialFile {
|
||||
readonly name: BackupName;
|
||||
readonly version: number;
|
||||
readonly container: BlkBlock;
|
||||
readonly content: BlkBlock;
|
||||
}
|
||||
|
||||
interface Preset {
|
||||
readonly country: string;
|
||||
readonly title: string;
|
||||
readonly selected: boolean;
|
||||
readonly units: ReadonlyArray<{ readonly slot: number; readonly vehicle: string }>;
|
||||
}
|
||||
|
||||
export function previewOfficialBackup(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
|
||||
return prepare(location, paths, includeUsed).preview;
|
||||
}
|
||||
|
||||
export function importOfficialBackup(location: SaveLocation, userId: string, paths: readonly string[], options: OfficialImportOptions) {
|
||||
const dataFolder = location.dataFolder;
|
||||
const accounts = new AccountStore(dataFolder);
|
||||
if (!accounts.byUserId(userId)) throw new Error('Unknown account for official backup.');
|
||||
const { files, presets, vehicles, gameFiles, datasets, preview } = prepare(location, paths, options.includeUsedVehicles);
|
||||
if (options.unlockVehicles && vehicles.length > 0) {
|
||||
const tuning = loadTuning(dataFolder, () => {});
|
||||
const clans = new ClanStore(dataFolder, tuning.clans);
|
||||
const services = setUpProfiles(dataFolder, gameFiles, datasets, tuning, { accounts, clans });
|
||||
const availableSlots = datasets.load(crewSlotPrices).length;
|
||||
services.profiles.update(userId, (profile) => applyVehicles(profile, services, vehicles, presets, availableSlots, options.equipment));
|
||||
}
|
||||
|
||||
if (options.importSettings) {
|
||||
const store = new CloudSettingsStore(dataFolder);
|
||||
const existing = store.buildMetaBlk(userId);
|
||||
for (const file of files) {
|
||||
const blkType = TYPES[file.name];
|
||||
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version')) + 1;
|
||||
if (version > 0x7fffffff) throw new Error('Imported settings version exceeds the supported range.');
|
||||
const contentHash = createHash('md5').update(encodeBlk({ ...file.content, name: '' })).digest('hex');
|
||||
if (!store.saveUpload(userId, { blkType, version, contentHash, container: file.container })) {
|
||||
throw new Error('Could not store the imported settings.');
|
||||
}
|
||||
}
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
|
||||
function prepare(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
|
||||
const files = paths.map(readFile);
|
||||
if (files.length === 0 || new Set(files.map(({ name }) => name)).size !== files.length) {
|
||||
throw new Error('Select at most one backup for each settings category.');
|
||||
}
|
||||
const gameFiles = new GameFiles(location.gameFolder);
|
||||
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
|
||||
const catalogue = datasets.load(vehicleCatalogue);
|
||||
const known = new Set(catalogue.map(({ name }) => name));
|
||||
const global = files.find(({ name }) => name === 'global.blk');
|
||||
const presets: Preset[] = global ? readPresets(global.content) : [];
|
||||
const referenced = new Set(presets.flatMap((entry) => entry.units.map(({ vehicle }) => vehicle)));
|
||||
if (includeUsed && global) considerUsed(global.content, known, referenced);
|
||||
const vehicles = [...referenced].filter((name) => known.has(name)).sort();
|
||||
const omitted = [...referenced].filter((name) => !known.has(name)).sort();
|
||||
return {
|
||||
files, presets, vehicles, gameFiles, datasets,
|
||||
preview: {
|
||||
files: files.map(({ name, version }) => ({ name, version })),
|
||||
presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })),
|
||||
vehicles, omitted,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function readFile(path: string): OfficialFile {
|
||||
const name = basename(path).toLowerCase();
|
||||
if (!Object.hasOwn(TYPES, name)) throw new Error('Unexpected official backup file: ' + name);
|
||||
const file = lstatSync(path);
|
||||
if (!file.isFile() || file.size > 32 * 1024 * 1024) throw new Error('Invalid backup file: ' + name);
|
||||
const container = readBackupBlk(readFileSync(path));
|
||||
const content = findBlock(container, 'content');
|
||||
const version = intField(container, 'version', -1);
|
||||
if (!content || !Number.isInteger(version) || version < 0) throw new Error('Expected a versioned settings container: ' + name);
|
||||
return { name: name as BackupName, version, container, content };
|
||||
}
|
||||
|
||||
function readPresets(content: BlkBlock): Preset[] {
|
||||
const root = namedBlock(content, 'slotbar_presets');
|
||||
return (root?.blocks ?? []).flatMap((country) => {
|
||||
const selected = intField(country, 'selected', 0);
|
||||
return country.params.filter(({ name }) => name === 'preset').flatMap((entry, index) => {
|
||||
if (entry.value.type !== 'string') return [];
|
||||
const parts = entry.value.value.split('|');
|
||||
if (parts.length !== 6) return [];
|
||||
const [, crewIds, vehicles, title, , slots] = parts as [string, string, string, string, string, string];
|
||||
const ids = (slots || crewIds).split(',');
|
||||
const units = vehicles.split(',').flatMap((vehicle, position) => {
|
||||
const token = ids[position];
|
||||
const slot = token && /^\d+$/.test(token) ? Number(token) : position;
|
||||
return vehicle && Number.isSafeInteger(slot) && slot >= 0 ? [{ slot, vehicle }] : [];
|
||||
});
|
||||
return [{ country: country.name, title, selected: index === selected, units }];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
|
||||
if (block.name === name) return block;
|
||||
for (const child of block.blocks) {
|
||||
const found = namedBlock(child, name);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
|
||||
function considerUsed(block: BlkBlock, known: ReadonlySet<string>, vehicles: Set<string>): void {
|
||||
if (known.has(block.name)) vehicles.add(block.name);
|
||||
for (const child of block.blocks) considerUsed(child, known, vehicles);
|
||||
}
|
||||
|
||||
function applyVehicles(
|
||||
profile: BlkBlock,
|
||||
{ research, equipment }: ProfileServices,
|
||||
vehicles: readonly string[],
|
||||
presets: readonly Preset[],
|
||||
slotLimit: number,
|
||||
tier: OfficialImportOptions['equipment'],
|
||||
): void {
|
||||
const granted = new Set<string>();
|
||||
const next = [...vehicles];
|
||||
while (next.length) {
|
||||
const name = next.pop()!;
|
||||
if (granted.has(name)) continue;
|
||||
const vehicle = research.techTree.vehicle(name);
|
||||
if (!vehicle) continue;
|
||||
granted.add(name);
|
||||
addOwnedVehicle(profile, name);
|
||||
if ((vehicle.kind === 'research' || vehicle.kind === 'purchase') && vehicle.requires) next.push(vehicle.requires);
|
||||
next.push(...vehicle.parts);
|
||||
}
|
||||
|
||||
if (tier !== 'stock') {
|
||||
for (const name of granted) {
|
||||
const facts = equipment.vehicle(name);
|
||||
if (!facts) continue;
|
||||
for (const mod of facts.modifications) {
|
||||
if (ownsModification(profile, name, mod.name) || (tier === 'basic' && !SURVIVAL.test(mod.name))) continue;
|
||||
writeModificationRecord(profile, name, mod.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: Math.max(1, mod.maxCount),
|
||||
});
|
||||
}
|
||||
if (tier === 'full') {
|
||||
for (const weapon of facts.weapons) {
|
||||
if (weaponRecord(profile, name, weapon.name)) continue;
|
||||
writeWeaponRecord(profile, name, weapon.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, count: Math.max(1, weapon.maxCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const preset of presets) {
|
||||
if (!research.techTree.hasCountry(preset.country)) continue;
|
||||
const crews = allCrews(profile).filter((crew) => crew.params.some((param) =>
|
||||
param.name === 'country' && param.value.type === 'string' && param.value.value === preset.country));
|
||||
for (const { slot, vehicle } of preset.units) {
|
||||
if (!granted.has(vehicle) || research.techTree.vehicle(vehicle)?.country !== preset.country ||
|
||||
slot >= Math.max(slotLimit, crews.length)) continue;
|
||||
while (crews.length <= slot) crews.push(crewOf(profile, addCrew(profile, preset.country))!);
|
||||
const crew = crews[slot]!;
|
||||
if (preset.selected) putVehicleInCrew(crew, vehicle);
|
||||
else trainCrewFor(crew, vehicle);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user