diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 4fa1cb8..5ad403b 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, 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', () => { diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 379a986..2f90861 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { const profile = archive.files['profile.blk']; if (!profile) return; diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts index f686429..341bbd2 100644 --- a/apps/launcher/src/main/workers/save-protocol.ts +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -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 }; diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts index 8e742da..78f7f35 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, 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); }); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 787aebf..7a556b2 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -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.", 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 f903358..e057880 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -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": "游戏或本地服务器运行期间存档为只读。", diff --git a/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx new file mode 100644 index 0000000..af88008 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx @@ -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([]); + const [options, setOptions] = useState(DEFAULTS); + const [preview, setPreview] = useState(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 ( + <> + + + {paths.length > 0 && {paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}} + + + + + + + + + +
+ + +
+ {readOnly &&

{t('saves.readOnly')}

} + {preview && ( +
+

{t('saves.official.summary', { files: preview.files.length, presets: preview.presets.length, vehicles: preview.vehicles.length })}

+ {preview.presets.map((preset, index) =>

{preset.title} · {preset.vehicles.join(', ')}

)} + {preview.omitted.length > 0 &&

{t('saves.official.omitted', { names: preview.omitted.join(', ') })}

} +
+ )} + {imported &&

{t('saves.official.done')}

} + + ); +} diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index 3258cc4..79a821a 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -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 )) )} + {section === 'official' && } {section === 'backup' && } {section === 'vehicles' && ( <> diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index 1be9db2..348d1ba 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', '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; diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index e0b83ae..7764264 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -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', diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index b3dbd94..c2596d6 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, 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, diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index 2bf19a2..c778de8 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -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; +export type OfficialImportOptions = z.output; + export type SaveTransfer = z.output; export type SaveBackup = z.output; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 39b966c..56fff21 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -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'; diff --git a/apps/server/src/saves/import/backup-blk.ts b/apps/server/src/saves/import/backup-blk.ts new file mode 100644 index 0000000..5af21ab --- /dev/null +++ b/apps/server/src/saves/import/backup-blk.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})`); + } +} diff --git a/apps/server/src/saves/import/official-backup.ts b/apps/server/src/saves/import/official-backup.ts new file mode 100644 index 0000000..e9ce6d4 --- /dev/null +++ b/apps/server/src/saves/import/official-backup.ts @@ -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, vehicles: Set): 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(); + 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); + } + } +}