fix(saves): remap online settings accounts, crew ids and exclude talismans
Re-key imported global.blk account settings to the local user id, map online global crew ids onto local crew slots, rewrite slotbar presets to local crew ids, clear offline local cache after bumping cloud versions, avoid cascading tech-tree unlocks from optional per-unit settings, and exclude talismans (premExpMul) from full equipment unlocks.
This commit is contained in:
1 parent
dacc61d404
commit
8c19811714
2 files changed
+367
-52
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { lstatSync, readFileSync } from 'node:fs';
|
||||
import { basename } from 'node:path';
|
||||
import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { basename, join } 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';
|
||||
@@ -10,7 +10,7 @@ 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 { addCrew, allCrews, crewOf, emptyCrewSlot, 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';
|
||||
@@ -27,6 +27,8 @@ const TYPES = {
|
||||
type BackupName = keyof typeof TYPES;
|
||||
|
||||
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
|
||||
const TALISMAN = 'premExpMul';
|
||||
const CREW_BLOCK_NAME = /^c(\d+)$/;
|
||||
|
||||
export interface OfficialImportOptions {
|
||||
readonly importSettings: boolean;
|
||||
@@ -42,41 +44,83 @@ interface OfficialFile {
|
||||
readonly content: BlkBlock;
|
||||
}
|
||||
|
||||
interface Preset {
|
||||
interface PresetUnit {
|
||||
readonly onlineCrewId: number;
|
||||
readonly vehicle: string;
|
||||
}
|
||||
|
||||
interface ParsedPreset {
|
||||
readonly country: string;
|
||||
readonly title: string;
|
||||
readonly gameModeId: string;
|
||||
readonly selected: boolean;
|
||||
readonly units: ReadonlyArray<{ readonly slot: number; readonly vehicle: string }>;
|
||||
readonly selectedOnlineCrewId: number;
|
||||
readonly onlineCrewOrder: readonly number[];
|
||||
readonly units: readonly PresetUnit[];
|
||||
}
|
||||
|
||||
interface CountryCrewMapping {
|
||||
readonly onlineToOffline: ReadonlyMap<number, number>;
|
||||
readonly offlineCrewIds: readonly number[];
|
||||
}
|
||||
|
||||
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) {
|
||||
export function importOfficialBackup(
|
||||
location: SaveLocation,
|
||||
userId: string,
|
||||
paths: readonly string[],
|
||||
options: OfficialImportOptions,
|
||||
offlineClientCacheFolder?: string,
|
||||
) {
|
||||
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) {
|
||||
if (!accounts.byUserId(userId)) throw new Error('Unknown account for online data import.');
|
||||
const { files, presets, presetVehicles, extraUsedVehicles, known, gameFiles, datasets, preview } = prepare(
|
||||
location, paths, options.includeUsedVehicles,
|
||||
);
|
||||
|
||||
const crewMappings = new Map<string, CountryCrewMapping>();
|
||||
const needsProfile = (options.unlockVehicles && (presetVehicles.length > 0 || extraUsedVehicles.length > 0))
|
||||
|| (options.importSettings && presets.length > 0);
|
||||
|
||||
if (needsProfile) {
|
||||
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.unlockVehicles && (presetVehicles.length > 0 || extraUsedVehicles.length > 0)) {
|
||||
services.profiles.update(userId, (profile) => {
|
||||
applyVehicles(profile, services, presetVehicles, extraUsedVehicles, presets, availableSlots, options.equipment, crewMappings);
|
||||
});
|
||||
} else {
|
||||
const profile = services.profiles.profileOf(userId);
|
||||
buildExistingCrewMappings(profile, services, presets, crewMappings);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.importSettings) {
|
||||
const global = files.find(({ name }) => name === 'global.blk');
|
||||
if (global) {
|
||||
remapGlobalAccountSettings(global.content, userId, crewMappings, known);
|
||||
}
|
||||
|
||||
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;
|
||||
const localCachedVersion = offlineClientCacheFolder ? readCachedLocalVersion(offlineClientCacheFolder, file.name) : 0;
|
||||
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version'), localCachedVersion) + 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.');
|
||||
}
|
||||
if (offlineClientCacheFolder) {
|
||||
clearCachedLocalFile(offlineClientCacheFolder, file.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return preview;
|
||||
@@ -85,20 +129,24 @@ export function importOfficialBackup(location: SaveLocation, userId: string, pat
|
||||
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.');
|
||||
throw new Error('Select at most one file 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();
|
||||
const presets: ParsedPreset[] = global ? readPresets(global.content) : [];
|
||||
const presetReferenced = new Set(presets.flatMap((entry) => entry.units.map(({ vehicle }) => vehicle)));
|
||||
const extraReferenced = new Set<string>();
|
||||
if (includeUsed && global) considerUsedUnits(global.content, known, presetReferenced, extraReferenced);
|
||||
|
||||
const presetVehicles = [...presetReferenced].filter((name) => known.has(name)).sort();
|
||||
const extraUsedVehicles = [...extraReferenced].filter((name) => known.has(name)).sort();
|
||||
const vehicles = [...new Set([...presetVehicles, ...extraUsedVehicles])].sort();
|
||||
const omitted = [...presetReferenced].filter((name) => !known.has(name)).sort();
|
||||
return {
|
||||
files, presets, vehicles, gameFiles, datasets,
|
||||
files, presets, presetVehicles, extraUsedVehicles, known, gameFiles, datasets,
|
||||
preview: {
|
||||
files: files.map(({ name, version }) => ({ name, version })),
|
||||
presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })),
|
||||
@@ -109,9 +157,9 @@ function prepare(location: SaveLocation, paths: readonly string[], includeUsed:
|
||||
|
||||
function readFile(path: string): OfficialFile {
|
||||
const name = basename(path).toLowerCase();
|
||||
if (!Object.hasOwn(TYPES, name)) throw new Error('Unexpected official backup file: ' + name);
|
||||
if (!Object.hasOwn(TYPES, name)) throw new Error('Unexpected online settings file: ' + name);
|
||||
const file = lstatSync(path);
|
||||
if (!file.isFile() || file.size > 32 * 1024 * 1024) throw new Error('Invalid backup file: ' + name);
|
||||
if (!file.isFile() || file.size > 32 * 1024 * 1024) throw new Error('Invalid settings file: ' + name);
|
||||
const container = readBackupBlk(readFileSync(path));
|
||||
const content = findBlock(container, 'content');
|
||||
const version = intField(container, 'version', -1);
|
||||
@@ -119,26 +167,73 @@ function readFile(path: string): OfficialFile {
|
||||
return { name: name as BackupName, version, container, content };
|
||||
}
|
||||
|
||||
function readPresets(content: BlkBlock): Preset[] {
|
||||
const root = namedBlock(content, 'slotbar_presets');
|
||||
function findAccountsBlock(content: BlkBlock): BlkBlock | undefined {
|
||||
const settings = findBlock(content, 'settings');
|
||||
const customSettings = settings ? findBlock(settings, 'customSettings') : undefined;
|
||||
return (customSettings ? findBlock(customSettings, 'accounts') : undefined) ?? namedBlock(content, 'accounts');
|
||||
}
|
||||
|
||||
function pickSourceAccountBlock(accounts: BlkBlock): BlkBlock | undefined {
|
||||
const withPresets = accounts.blocks.filter((entry) => findBlock(entry, 'slotbar_presets') !== undefined);
|
||||
return withPresets.find((entry) => entry.name.endsWith('.production'))
|
||||
?? withPresets[0]
|
||||
?? accounts.blocks.find((entry) => entry.name.endsWith('.production'))
|
||||
?? accounts.blocks[0];
|
||||
}
|
||||
|
||||
function readPresets(content: BlkBlock): ParsedPreset[] {
|
||||
const accounts = findAccountsBlock(content);
|
||||
const sourceAccount = accounts ? pickSourceAccountBlock(accounts) : undefined;
|
||||
const root = (sourceAccount ? findBlock(sourceAccount, 'slotbar_presets') : undefined)
|
||||
?? 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 }];
|
||||
const parsed = parsePresetString(country.name, entry.value.value, index === selected);
|
||||
return parsed ? [parsed] : [];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function parsePresetString(country: string, raw: string, selected: boolean): ParsedPreset | null {
|
||||
const parts = raw.split('|');
|
||||
if (parts.length < 3) return null;
|
||||
const selectedCrewText = parts[0] ?? '';
|
||||
const crewIdsText = parts[1] ?? '';
|
||||
const vehiclesText = parts[2] ?? '';
|
||||
const title = parts[3] ?? '';
|
||||
const gameModeId = parts[4] ?? '';
|
||||
const crewInSlotsText = parts[5] ?? '';
|
||||
|
||||
const selectedOnlineCrewId = /^\d+$/.test(selectedCrewText) ? Number(selectedCrewText) : -1;
|
||||
const crewIdTokens = crewIdsText ? crewIdsText.split(',') : [];
|
||||
const vehicleTokens = vehiclesText ? vehiclesText.split(',') : [];
|
||||
const slotCrewIds = crewInSlotsText
|
||||
? crewInSlotsText.split(',').filter((token) => /^\d+$/.test(token)).map(Number)
|
||||
: [];
|
||||
|
||||
const units: PresetUnit[] = [];
|
||||
const pairCount = Math.min(crewIdTokens.length, vehicleTokens.length);
|
||||
for (let i = 0; i < pairCount; i += 1) {
|
||||
const vehicle = vehicleTokens[i]?.trim() ?? '';
|
||||
const token = crewIdTokens[i]?.trim() ?? '';
|
||||
if (!vehicle || !/^\d+$/.test(token)) continue;
|
||||
units.push({ onlineCrewId: Number(token), vehicle });
|
||||
}
|
||||
|
||||
const onlineCrewOrder: number[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const id of [...slotCrewIds, ...units.map(({ onlineCrewId }) => onlineCrewId)]) {
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
onlineCrewOrder.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
return { country, title, gameModeId, selected, selectedOnlineCrewId, onlineCrewOrder, units };
|
||||
}
|
||||
|
||||
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
|
||||
if (block.name === name) return block;
|
||||
for (const child of block.blocks) {
|
||||
@@ -147,21 +242,88 @@ function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
/**
|
||||
* Only read per-unit battle settings from `content/settings/unitsSettings` rather than scanning
|
||||
* the whole file, so protection analysis, skin lists and crosshair tables are never mistaken
|
||||
* for owned vehicles.
|
||||
*/
|
||||
function considerUsedUnits(
|
||||
content: BlkBlock,
|
||||
known: ReadonlySet<string>,
|
||||
presetVehicles: ReadonlySet<string>,
|
||||
extraVehicles: Set<string>,
|
||||
): void {
|
||||
const settings = findBlock(content, 'settings');
|
||||
const unitsSettings = settings ? findBlock(settings, 'unitsSettings') : undefined;
|
||||
if (!unitsSettings) return;
|
||||
for (const unitBlock of unitsSettings.blocks) {
|
||||
if (!known.has(unitBlock.name) || presetVehicles.has(unitBlock.name)) continue;
|
||||
const hasConfiguredLoadout = unitBlock.params.some((param) =>
|
||||
(param.name === 'USEROPT_BULLET_COUNT0' && param.value.type === 'int' && param.value.value > 0)
|
||||
|| (param.name === 'USEROPT_WEAPONS' && param.value.type === 'string' && param.value.value.length > 0),
|
||||
);
|
||||
if (hasConfiguredLoadout) extraVehicles.add(unitBlock.name);
|
||||
}
|
||||
}
|
||||
|
||||
function crewIdOfBlock(crew: BlkBlock): number {
|
||||
return Number(CREW_BLOCK_NAME.exec(crew.name)?.[1] ?? -1);
|
||||
}
|
||||
|
||||
function countryCrewsOf(profile: BlkBlock, country: string): BlkBlock[] {
|
||||
return allCrews(profile).filter((crew) =>
|
||||
crew.params.some((param) => param.name === 'country' && param.value.type === 'string' && param.value.value === country),
|
||||
);
|
||||
}
|
||||
|
||||
function orderedOnlineCrewIdsForCountry(presets: readonly ParsedPreset[], country: string): number[] {
|
||||
const ordered: number[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const preset of presets) {
|
||||
if (preset.country !== country) continue;
|
||||
for (const id of preset.onlineCrewOrder) {
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
ordered.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function buildExistingCrewMappings(
|
||||
profile: BlkBlock,
|
||||
{ research }: ProfileServices,
|
||||
presets: readonly ParsedPreset[],
|
||||
mappings: Map<string, CountryCrewMapping>,
|
||||
): void {
|
||||
const countries = new Set(presets.map(({ country }) => country));
|
||||
for (const country of countries) {
|
||||
if (!research.techTree.hasCountry(country)) continue;
|
||||
const crews = countryCrewsOf(profile, country);
|
||||
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
|
||||
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
|
||||
const onlineToOffline = new Map<number, number>();
|
||||
for (let slot = 0; slot < Math.min(onlineOrder.length, offlineCrewIds.length); slot += 1) {
|
||||
onlineToOffline.set(onlineOrder[slot]!, offlineCrewIds[slot]!);
|
||||
}
|
||||
mappings.set(country, { onlineToOffline, offlineCrewIds });
|
||||
}
|
||||
}
|
||||
|
||||
function applyVehicles(
|
||||
profile: BlkBlock,
|
||||
{ research, equipment }: ProfileServices,
|
||||
vehicles: readonly string[],
|
||||
presets: readonly Preset[],
|
||||
presetVehicles: readonly string[],
|
||||
extraUsedVehicles: readonly string[],
|
||||
presets: readonly ParsedPreset[],
|
||||
slotLimit: number,
|
||||
tier: OfficialImportOptions['equipment'],
|
||||
mappings: Map<string, CountryCrewMapping>,
|
||||
): void {
|
||||
const granted = new Set<string>();
|
||||
const next = [...vehicles];
|
||||
// Trace tech-tree prerequisites only for vehicles that actually appear in slotbar presets.
|
||||
const next = [...presetVehicles];
|
||||
while (next.length) {
|
||||
const name = next.pop()!;
|
||||
if (granted.has(name)) continue;
|
||||
@@ -173,14 +335,34 @@ function applyVehicles(
|
||||
next.push(...vehicle.parts);
|
||||
}
|
||||
|
||||
// Optional extra vehicles from unitsSettings are granted individually without unlocking whole lines.
|
||||
for (const name of extraUsedVehicles) {
|
||||
if (granted.has(name)) continue;
|
||||
const vehicle = research.techTree.vehicle(name);
|
||||
if (!vehicle) continue;
|
||||
granted.add(name);
|
||||
addOwnedVehicle(profile, name);
|
||||
for (const part of vehicle.parts) {
|
||||
if (!granted.has(part)) {
|
||||
granted.add(part);
|
||||
addOwnedVehicle(profile, part);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tier !== 'stock') {
|
||||
for (const name of granted) {
|
||||
const facts = equipment.vehicle(name);
|
||||
if (!facts) continue;
|
||||
const enabledGroups = new Set<string>();
|
||||
for (const mod of facts.modifications) {
|
||||
if (ownsModification(profile, name, mod.name) || (tier === 'basic' && !SURVIVAL.test(mod.name))) continue;
|
||||
// Never grant talismans or GE-only premium modifications when unlocking vehicle equipment.
|
||||
if (mod.name === TALISMAN || mod.goldenEagles > 0 || ownsModification(profile, name, mod.name)) continue;
|
||||
if (tier === 'basic' && !SURVIVAL.test(mod.name)) continue;
|
||||
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
|
||||
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
|
||||
writeModificationRecord(profile, name, mod.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: Math.max(1, mod.maxCount),
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
|
||||
});
|
||||
}
|
||||
if (tier === 'full') {
|
||||
@@ -194,17 +376,147 @@ function applyVehicles(
|
||||
}
|
||||
}
|
||||
|
||||
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 countries = new Set(presets.map(({ country }) => country));
|
||||
for (const country of countries) {
|
||||
if (!research.techTree.hasCountry(country)) continue;
|
||||
const crews = countryCrewsOf(profile, country);
|
||||
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
|
||||
const targetSlots = Math.min(Math.max(crews.length, onlineOrder.length), Math.max(slotLimit, crews.length));
|
||||
while (crews.length < targetSlots) {
|
||||
crews.push(crewOf(profile, addCrew(profile, country))!);
|
||||
}
|
||||
|
||||
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
|
||||
const onlineToOffline = new Map<number, number>();
|
||||
const onlineToCrew = new Map<number, BlkBlock>();
|
||||
for (let slot = 0; slot < Math.min(onlineOrder.length, crews.length); slot += 1) {
|
||||
const onlineId = onlineOrder[slot]!;
|
||||
const crew = crews[slot]!;
|
||||
if (preset.selected) putVehicleInCrew(crew, vehicle);
|
||||
else trainCrewFor(crew, vehicle);
|
||||
const offlineId = crewIdOfBlock(crew);
|
||||
if (offlineId >= 0) {
|
||||
onlineToOffline.set(onlineId, offlineId);
|
||||
onlineToCrew.set(onlineId, crew);
|
||||
}
|
||||
}
|
||||
mappings.set(country, { onlineToOffline, offlineCrewIds });
|
||||
|
||||
const countryPresets = presets.filter((entry) => entry.country === country);
|
||||
const selectedPreset = countryPresets.find((entry) => entry.selected) ?? countryPresets[0];
|
||||
const selectedAssignments = (selectedPreset?.units ?? []).flatMap(({ onlineCrewId, vehicle }) => {
|
||||
const crew = onlineToCrew.get(onlineCrewId);
|
||||
return crew && granted.has(vehicle) && research.techTree.vehicle(vehicle)?.country === country
|
||||
? [{ crew, vehicle }]
|
||||
: [];
|
||||
});
|
||||
|
||||
if (selectedAssignments.length > 0) {
|
||||
for (const crew of crews) emptyCrewSlot(crew);
|
||||
for (const { crew, vehicle } of selectedAssignments) putVehicleInCrew(crew, vehicle);
|
||||
}
|
||||
|
||||
for (const preset of countryPresets) {
|
||||
for (const { onlineCrewId, vehicle } of preset.units) {
|
||||
const crew = onlineToCrew.get(onlineCrewId);
|
||||
if (!crew || !granted.has(vehicle) || research.techTree.vehicle(vehicle)?.country !== country) continue;
|
||||
trainCrewFor(crew, vehicle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-key `content/settings/customSettings/accounts/<onlineUid>.production` to the target local
|
||||
* offline account id and rewrite every slotbar preset's crew ids to match the local profile.
|
||||
*/
|
||||
function remapGlobalAccountSettings(
|
||||
content: BlkBlock,
|
||||
userId: string,
|
||||
mappings: ReadonlyMap<string, CountryCrewMapping>,
|
||||
known: ReadonlySet<string>,
|
||||
): void {
|
||||
const accounts = findAccountsBlock(content);
|
||||
if (!accounts) return;
|
||||
const source = pickSourceAccountBlock(accounts);
|
||||
if (!source) return;
|
||||
|
||||
const targetAccount: BlkBlock = {
|
||||
name: `${userId}.production`,
|
||||
params: [...source.params],
|
||||
blocks: [...source.blocks],
|
||||
};
|
||||
accounts.blocks = [targetAccount];
|
||||
|
||||
const slotbarPresets = findBlock(targetAccount, 'slotbar_presets');
|
||||
if (!slotbarPresets) return;
|
||||
|
||||
for (const countryBlock of slotbarPresets.blocks) {
|
||||
const mapping = mappings.get(countryBlock.name);
|
||||
if (!mapping || mapping.offlineCrewIds.length === 0) continue;
|
||||
|
||||
countryBlock.params = countryBlock.params.map((param) => {
|
||||
if (param.name !== 'preset' || param.value.type !== 'string') return param;
|
||||
const rewritten = rewritePresetString(countryBlock.name, param.value.value, mapping, known);
|
||||
return rewritten === null ? param : { name: 'preset', value: { type: 'string', value: rewritten } };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function rewritePresetString(
|
||||
country: string,
|
||||
raw: string,
|
||||
mapping: CountryCrewMapping,
|
||||
known: ReadonlySet<string>,
|
||||
): string | null {
|
||||
const parsed = parsePresetString(country, raw, false);
|
||||
if (!parsed) return null;
|
||||
|
||||
const remappedCrews: number[] = [];
|
||||
const remappedUnits: string[] = [];
|
||||
for (const { onlineCrewId, vehicle } of parsed.units) {
|
||||
if (!known.has(vehicle)) continue;
|
||||
const offlineCrewId = mapping.onlineToOffline.get(onlineCrewId);
|
||||
if (offlineCrewId === undefined) continue;
|
||||
remappedCrews.push(offlineCrewId);
|
||||
remappedUnits.push(vehicle);
|
||||
}
|
||||
|
||||
const mappedSelected = parsed.selectedOnlineCrewId >= 0
|
||||
? mapping.onlineToOffline.get(parsed.selectedOnlineCrewId)
|
||||
: undefined;
|
||||
const selectedCrewId = mappedSelected !== undefined && remappedCrews.includes(mappedSelected)
|
||||
? mappedSelected
|
||||
: (remappedCrews[0] ?? -1);
|
||||
|
||||
return [
|
||||
String(selectedCrewId),
|
||||
remappedCrews.join(','),
|
||||
remappedUnits.join(','),
|
||||
parsed.title,
|
||||
parsed.gameModeId,
|
||||
mapping.offlineCrewIds.join(','),
|
||||
].join('|');
|
||||
}
|
||||
|
||||
function readCachedLocalVersion(cacheFolder: string, fileName: BackupName): number {
|
||||
const path = join(cacheFolder, fileName);
|
||||
if (!existsSync(path)) return 0;
|
||||
try {
|
||||
const stats = lstatSync(path);
|
||||
if (!stats.isFile() || stats.size > 32 * 1024 * 1024) return 0;
|
||||
const block = readBackupBlk(readFileSync(path));
|
||||
const version = intField(block, 'version', 0);
|
||||
return Number.isInteger(version) && version > 0 ? version : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function clearCachedLocalFile(cacheFolder: string, fileName: BackupName): void {
|
||||
const path = join(cacheFolder, fileName);
|
||||
if (!existsSync(path)) return;
|
||||
try {
|
||||
rmSync(path, { force: true });
|
||||
} catch {
|
||||
// Best-effort cleanup; the bumped server version still forces a fresh pull on login.
|
||||
}
|
||||
}
|
||||
@@ -61,10 +61,13 @@ export function editSaveResearch(location: SaveLocation, userId: string, branch:
|
||||
for (const part of unit.parts) addOwnedVehicle(profile, part);
|
||||
}
|
||||
if (operation === 'equipment' && owned.has(unit.name)) {
|
||||
const enabledGroups = new Set<string>();
|
||||
for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) {
|
||||
if (ownsModification(profile, unit.name, mod.name)) continue;
|
||||
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || ownsModification(profile, unit.name, mod.name)) continue;
|
||||
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
|
||||
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
|
||||
writeModificationRecord(profile, unit.name, mod.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: Math.max(1, mod.maxCount),
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user