feat(saves): localize battle and preset names, merge overview form and guard cache writes
This commit is contained in:
1 parent
e6e75d92c6
commit
7cb1011f0d
11 files changed
+276
-59
No files matched your search
@@ -162,5 +162,12 @@ function readEntry(path: string): CacheEntry | undefined {
|
||||
}
|
||||
|
||||
function writeEntry(path: string, entry: CacheEntry): void {
|
||||
writeFileAtomic(path, JSON.stringify(entry));
|
||||
try {
|
||||
writeFileAtomic(path, JSON.stringify(entry));
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
// Another worker updating the same cache file on Windows can hold a brief lock; reading stays valid.
|
||||
if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.t
|
||||
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
|
||||
import { loadTuning } from '../../tuning/tuning.ts';
|
||||
import type { SaveLocation } from '../save-editor.ts';
|
||||
import { loadSaveLabels, localizeVehicleName } from '../save-labels.ts';
|
||||
import { readBackupBlk } from './backup-blk.ts';
|
||||
|
||||
const TYPES = {
|
||||
@@ -152,12 +153,17 @@ function prepare(location: SaveLocation, paths: readonly string[]) {
|
||||
|
||||
const presetVehicles = [...presetReferenced].filter((name) => known.has(name)).sort();
|
||||
const omitted = [...presetReferenced].filter((name) => !known.has(name)).sort();
|
||||
const labels = loadSaveLabels(location.dataFolder, location.gameFolder);
|
||||
const vehicleNames = Object.fromEntries(
|
||||
[...presetReferenced].map((name) => [name, localizeVehicleName(name, labels)]),
|
||||
);
|
||||
return {
|
||||
files, presets, presetVehicles, known, gameFiles, datasets,
|
||||
preview: {
|
||||
files: files.map(({ name, version }) => ({ name, version })),
|
||||
presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })),
|
||||
vehicles: presetVehicles,
|
||||
vehicleNames,
|
||||
omitted,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@ import { serverTimeNow } from '../profile/server-time.ts';
|
||||
import { setUpProfiles } from '../profiles-setup.ts';
|
||||
import { loadTuning } from '../tuning/tuning.ts';
|
||||
import { readSaveAvatar } from './save-avatars.ts';
|
||||
import { loadSaveLabels, localizeMissionName, localizeVehicleName, type SaveLabels } from './save-labels.ts';
|
||||
|
||||
export interface SaveLocation {
|
||||
readonly gameFolder: string;
|
||||
@@ -57,19 +58,24 @@ export function readSaveSnapshot(dataFolder: string, userId: string): BlkBlock |
|
||||
}
|
||||
}
|
||||
|
||||
function battleEntries(profile: BlkBlock) {
|
||||
function battleEntries(profile: BlkBlock, labels?: SaveLabels) {
|
||||
return (findBlock(profile, 'userlogs')?.blocks ?? [])
|
||||
.filter((entry) => intField(entry, 'type') === EULT_SESSION_RESULT)
|
||||
.map((entry) => {
|
||||
const body = findBlock(entry, 'body');
|
||||
const win = body && findParam(body, 'win')?.value;
|
||||
const mission = stringField(body, 'locName') || stringField(body, 'mission');
|
||||
const mode = stringField(body, 'eventId');
|
||||
const vehicles = (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [];
|
||||
return {
|
||||
id: entry.name,
|
||||
time: intField(entry, 'time'),
|
||||
won: win?.type === 'bool' ? win.value : null,
|
||||
mission: stringField(body, 'locName') || stringField(body, 'mission'),
|
||||
mode: stringField(body, 'eventId'),
|
||||
vehicles: (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [],
|
||||
mission,
|
||||
missionName: labels ? localizeMissionName(mission || mode, labels) : { en: mission || mode, zh: mission || mode },
|
||||
mode,
|
||||
vehicles,
|
||||
vehicleNames: vehicles.map((unitId) => (labels ? localizeVehicleName(unitId, labels) : { en: unitId, zh: unitId })),
|
||||
silverLions: intField(body, 'wpEarned'),
|
||||
researchPoints: intField(body, 'xpEarned'),
|
||||
};
|
||||
@@ -104,9 +110,10 @@ export function readSaveDetails(dataFolder: string, userId: string, gameFolder?:
|
||||
.filter(({ points }) => points > 0)
|
||||
: [];
|
||||
const thresholds = rankThresholds(dataFolder, gameFolder);
|
||||
const labels = loadSaveLabels(dataFolder, gameFolder);
|
||||
return {
|
||||
save: summary(account, profile, thresholds),
|
||||
battles: profile ? battleEntries(profile) : [],
|
||||
battles: profile ? battleEntries(profile, labels) : [],
|
||||
owned,
|
||||
research,
|
||||
maxLevel: thresholds.length || null,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
|
||||
import type { Dataset } from '../game-data/datasets/dataset.ts';
|
||||
import { parseLocalizedCsvMap, type LocalizedCsvText } from '../game-data/datasets/lang-csv.ts';
|
||||
import { GameFiles } from '../game-data/game-files.ts';
|
||||
|
||||
const LANGUAGE_PACK = 'lang.vromfs.bin';
|
||||
const UNIT_FILE = 'lang/units.csv';
|
||||
const MISSION_FILES = ['lang/missions_versus.csv', 'lang/missions_locations.csv', 'lang/missions_single.csv'] as const;
|
||||
const UNIT_SHOP_SUFFIX = '_shop';
|
||||
/** Gaijin uses control-picture and private-use code points for in-game nation flag glyphs. */
|
||||
const GAME_FONT_GLYPHS = /[\u2400-\u243f\ue000-\uf8ff]/g;
|
||||
|
||||
export interface SaveLabels {
|
||||
readonly units: Readonly<Record<string, LocalizedCsvText>>;
|
||||
readonly missions: Readonly<Record<string, LocalizedCsvText>>;
|
||||
}
|
||||
|
||||
const EMPTY_LABELS: SaveLabels = { units: {}, missions: {} };
|
||||
|
||||
const saveLabelsDataset: Dataset<SaveLabels> = {
|
||||
id: 'save-labels',
|
||||
version: 1,
|
||||
extract: (source) => {
|
||||
const available = new Set(source.listFiles(LANGUAGE_PACK));
|
||||
const units: Record<string, LocalizedCsvText> = {};
|
||||
if (available.has(UNIT_FILE)) {
|
||||
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, UNIT_FILE))) {
|
||||
if (!key.endsWith(UNIT_SHOP_SUFFIX)) continue;
|
||||
const unitId = key.slice(0, -UNIT_SHOP_SUFFIX.length);
|
||||
if (!unitId) continue;
|
||||
units[unitId] = stripGlyphs(text, unitId);
|
||||
}
|
||||
}
|
||||
|
||||
const missions: Record<string, LocalizedCsvText> = {};
|
||||
for (const file of MISSION_FILES) {
|
||||
if (!available.has(file)) continue;
|
||||
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, file))) {
|
||||
if (!(key in missions)) missions[key] = stripGlyphs(text, key);
|
||||
}
|
||||
}
|
||||
|
||||
return { units, missions };
|
||||
},
|
||||
};
|
||||
|
||||
export function loadSaveLabels(dataFolder: string, gameFolder: string | undefined): SaveLabels {
|
||||
if (!gameFolder) return EMPTY_LABELS;
|
||||
try {
|
||||
return new DatasetCache(dataFolder, new GameFiles(gameFolder), () => {}).load(saveLabelsDataset);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return EMPTY_LABELS;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function localizeVehicleName(unitId: string, labels: SaveLabels): LocalizedCsvText {
|
||||
return labels.units[unitId] ?? { en: unitId, zh: unitId };
|
||||
}
|
||||
|
||||
export function localizeMissionName(raw: string, labels: SaveLabels): LocalizedCsvText {
|
||||
if (!raw) return { en: '', zh: '' };
|
||||
const exact = lookupMission(raw, labels);
|
||||
if (exact) return exact;
|
||||
|
||||
const parts = raw.split(';').map((part) => part.trim()).filter(Boolean);
|
||||
if (parts.length <= 1) return { en: raw, zh: raw };
|
||||
|
||||
const resolved = parts.map((part) => lookupMission(part, labels) ?? { en: part, zh: part });
|
||||
return {
|
||||
en: joinMissionParts(resolved.map(({ en }) => en), false),
|
||||
zh: joinMissionParts(resolved.map(({ zh }) => zh), true),
|
||||
};
|
||||
}
|
||||
|
||||
function lookupMission(key: string, labels: SaveLabels): LocalizedCsvText | undefined {
|
||||
return labels.missions[key]
|
||||
?? (key.startsWith('missions/') ? labels.missions[key.slice('missions/'.length)] : labels.missions[`missions/${key}`]);
|
||||
}
|
||||
|
||||
function joinMissionParts(parts: readonly string[], cjk: boolean): string {
|
||||
let result = '';
|
||||
for (const part of parts) {
|
||||
if (!part) continue;
|
||||
if (!result) {
|
||||
result = part;
|
||||
} else if (cjk && (result.endsWith('】') || result.endsWith(']') || part.startsWith('【'))) {
|
||||
result += part;
|
||||
} else {
|
||||
result += ` ${part}`;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function stripGlyphs(text: LocalizedCsvText, fallback: string): LocalizedCsvText {
|
||||
const en = text.en.replace(GAME_FONT_GLYPHS, '').trim() || fallback;
|
||||
const zh = text.zh.replace(GAME_FONT_GLYPHS, '').trim() || en;
|
||||
return { en, zh };
|
||||
}
|
||||
@@ -2,12 +2,17 @@
|
||||
* Write a file so that a crash leaves either the old or the new content, never a mix:
|
||||
* write a temporary file next to it, flush it to disk, then rename it over the target.
|
||||
*/
|
||||
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
const TRANSIENT_RENAME_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
||||
const MAX_RENAME_ATTEMPTS = 6;
|
||||
const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
export function writeFileAtomic(path: string, content: Uint8Array | string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const temporary = `${path}.${process.pid}.tmp`;
|
||||
const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
||||
const fd = openSync(temporary, 'w');
|
||||
try {
|
||||
writeSync(fd, typeof content === 'string' ? Buffer.from(content, 'utf8') : content);
|
||||
@@ -15,5 +20,23 @@ export function writeFileAtomic(path: string, content: Uint8Array | string): voi
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
renameSync(temporary, path);
|
||||
try {
|
||||
renameWithRetry(temporary, path);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* ignore cleanup errors */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function renameWithRetry(source: string, target: string): void {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
renameSync(source, target);
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (attempt >= MAX_RENAME_ATTEMPTS || !code || !TRANSIENT_RENAME_ERRORS.has(code)) throw error;
|
||||
Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 25);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user