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); } } }