Persist cloud settings with each local save
This commit is contained in:
1 parent
2e2c4a5234
commit
929e4b1e78
9 files changed
+474
-7
No files matched your search
@@ -1,6 +1,7 @@
|
||||
/** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */
|
||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import type { ClanStore } from '../../clans/clan-store.ts';
|
||||
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
|
||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||
import type { ResearchRules } from '../../research/research-rules.ts';
|
||||
import type { CharActionHandler } from '../char-action.ts';
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
setClanBestRewardsAction,
|
||||
setResearchClanUnitAction,
|
||||
} from './clan-actions.ts';
|
||||
import { bulkSetGblkAction, getGeneralBlkAction, getMetaBlkAction, setGeneralBlkAction } from './cloud-settings-actions.ts';
|
||||
import { bulkTrainCrews, trainCrew } from './crew-actions.ts';
|
||||
import { buyUnlockAction } from './unlock-actions.ts';
|
||||
import { buyAllModificationsAction, buyModificationAction, buySparesAction, buyWeaponsAction, enableModificationsAction } from './modification-actions.ts';
|
||||
@@ -58,13 +60,14 @@ export interface ActionDependencies {
|
||||
readonly accounts: AccountStore;
|
||||
readonly research: ResearchRules;
|
||||
readonly clans?: ClanStore;
|
||||
readonly cloudSettings?: CloudSettingsStore;
|
||||
readonly notifyInventoryChanged?: () => void;
|
||||
}
|
||||
|
||||
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
|
||||
const notifyInventory = deps.notifyInventoryChanged ?? (() => {});
|
||||
const entries: Array<[string, CharActionHandler]> = [
|
||||
['cln_get_initial_meta', initialMeta()],
|
||||
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
|
||||
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts, deps.clans)],
|
||||
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts, deps.clans)],
|
||||
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
|
||||
@@ -140,5 +143,15 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharA
|
||||
);
|
||||
}
|
||||
|
||||
if (deps.cloudSettings) {
|
||||
const cloudSettings = deps.cloudSettings;
|
||||
entries.push(
|
||||
['cln_get_meta_blk', getMetaBlkAction(deps.accounts, cloudSettings)],
|
||||
['cln_get_general_blk', getGeneralBlkAction(deps.accounts, cloudSettings)],
|
||||
['cln_set_general_blk', setGeneralBlkAction(deps.accounts, cloudSettings)],
|
||||
['cln_bulk_set_gblk', bulkSetGblkAction(deps.accounts, cloudSettings)],
|
||||
);
|
||||
}
|
||||
|
||||
return new Map<string, CharActionHandler>(entries);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Char actions for `online_storage` / `generalBlk` cloud settings sync (implementation notes;
|
||||
* aces.exe 2.61.0.37: `cln_get_meta_blk` 0x4662b3f, `cln_get_general_blk` 0x46677df,
|
||||
* `cln_set_general_blk` 0x4666c51, `cln_bulk_set_gblk` 0x4663cfd).
|
||||
*/
|
||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import {
|
||||
buildContainerBlk,
|
||||
computeContentHash,
|
||||
normalizeContainerBlk,
|
||||
parsePbbdBulkUploads,
|
||||
unpackCloudBlk,
|
||||
} from '../../cloud-settings/cloud-settings-codec.ts';
|
||||
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
|
||||
import { emptyBlock } from '@wto/blk';
|
||||
import type { CharActionHandler } from '../char-action.ts';
|
||||
import { withAccount } from './account-context.ts';
|
||||
import { intParam, stringParam } from './payload-params.ts';
|
||||
|
||||
/** `cln_get_meta_blk`: returns schema, compression negotiation, and saved block versions/hashes. */
|
||||
export function getMetaBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
|
||||
return (context) => withAccount(context, accounts, (account) => ({
|
||||
kind: 'data',
|
||||
blk: cloudSettings.buildMetaBlk(account.userId),
|
||||
}));
|
||||
}
|
||||
|
||||
/** `cln_get_general_blk`: returns `ContainerBlk` (`version:i`, `content { ... }`) for `blkType`. */
|
||||
export function getGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
|
||||
return (context) => withAccount(context, accounts, (account) => {
|
||||
const payload = context.payload;
|
||||
const blkType = context.headerParam('blkType') ?? (payload ? stringParam(payload, 'blkType') : undefined);
|
||||
if (!blkType) return { kind: 'error', code: 'BAD_PARAM' };
|
||||
const stored = cloudSettings.loadContainer(account.userId, blkType) ?? buildContainerBlk(1, emptyBlock('content'));
|
||||
return { kind: 'data', blk: stored };
|
||||
});
|
||||
}
|
||||
|
||||
/** `cln_set_general_blk`: stores a single `ContainerBlk` uploaded by the client and answers `!OK`. */
|
||||
export function setGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
|
||||
return (context) => withAccount(context, accounts, (account) => {
|
||||
const payload = context.payload;
|
||||
const blkType = context.headerParam('type')
|
||||
?? context.headerParam('blkType')
|
||||
?? (payload ? stringParam(payload, 'type') : undefined)
|
||||
?? (payload ? stringParam(payload, 'blkType') : undefined);
|
||||
if (!blkType) return { kind: 'error', code: 'BAD_PARAM' };
|
||||
|
||||
const headerVersion = parsePositiveInt(context.headerParam('version'))
|
||||
?? (payload ? intParam(payload, 'version') : undefined)
|
||||
?? 1;
|
||||
const compr = context.headerParam('compr');
|
||||
const rawBody = context.rawBody ?? new Uint8Array(0);
|
||||
const decoded = unpackCloudBlk(rawBody, compr) ?? payload;
|
||||
if (!decoded) return { kind: 'error', code: 'BAD_PARAM' };
|
||||
|
||||
const normalized = normalizeContainerBlk(decoded, headerVersion);
|
||||
const contentHash = context.headerParam('contentHash')
|
||||
?? (payload ? stringParam(payload, 'contentHash') : undefined)
|
||||
?? computeContentHash(normalized.content);
|
||||
|
||||
const ok = cloudSettings.saveUpload(account.userId, {
|
||||
blkType,
|
||||
version: normalized.version,
|
||||
contentHash,
|
||||
container: normalized.container,
|
||||
});
|
||||
return ok ? { kind: 'done' } : { kind: 'error', code: 'BAD_PARAM' };
|
||||
});
|
||||
}
|
||||
|
||||
/** `cln_bulk_set_gblk`: unpacks a `PBBD` batch stream (`store_gblk` / `bigquery` / `logout`) and answers `!OK`. */
|
||||
export function bulkSetGblkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
|
||||
return (context) => withAccount(context, accounts, (account) => {
|
||||
const rawBody = context.rawBody ?? new Uint8Array(0);
|
||||
if (rawBody.byteLength > 0) {
|
||||
const uploads = parsePbbdBulkUploads(rawBody);
|
||||
if (uploads.length > 0) {
|
||||
cloudSettings.saveBulkUploads(account.userId, uploads);
|
||||
}
|
||||
}
|
||||
return { kind: 'done' };
|
||||
});
|
||||
}
|
||||
|
||||
function parsePositiveInt(raw: string | undefined): number | undefined {
|
||||
if (!raw || !/^\d+$/.test(raw.trim())) return undefined;
|
||||
const parsed = Number.parseInt(raw.trim(), 10);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
* Char actions of the online initialisation after sign-in, up to the profile
|
||||
*.
|
||||
*/
|
||||
import { emptyBlock } from '@wto/blk';
|
||||
import { emptyBlock, setParam } from '@wto/blk';
|
||||
import type { AccountStore } from '../../accounts/account-store.ts';
|
||||
import type { ClanStore } from '../../clans/clan-store.ts';
|
||||
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
|
||||
import { clientProfile } from '../../profile/client-profile.ts';
|
||||
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
|
||||
import type { CharActionHandler } from '../char-action.ts';
|
||||
@@ -14,12 +15,19 @@ import { withAccount } from './account-context.ts';
|
||||
* cln_get_initial_meta: server-side metadata the client reads in GameSaveData's initial-meta
|
||||
* handling (aces.exe 0xeb5f60). binaryDataMetainfo lists server-side binary files the client
|
||||
* must fetch and compare by hash; the local service has none, so the list is empty and no
|
||||
* downloads follow.
|
||||
* downloads follow. generalBlkMeta carries the cloud-settings schema and saved versions/hashes
|
||||
*.
|
||||
*/
|
||||
export function initialMeta(): CharActionHandler {
|
||||
return () => {
|
||||
export function initialMeta(accounts?: AccountStore, cloudSettings?: CloudSettingsStore): CharActionHandler {
|
||||
return (context) => {
|
||||
const meta = emptyBlock();
|
||||
meta.blocks.push(emptyBlock('binaryDataMetainfo'), emptyBlock('generalBlkMeta'));
|
||||
setParam(meta, 'machineId', { type: 'string', value: 'wto_local_machine' });
|
||||
setParam(meta, 'bestCompression', { type: 'string', value: 'zstd' });
|
||||
const account = context.userId !== undefined ? accounts?.byUserId(context.userId) : undefined;
|
||||
const generalBlkMeta = cloudSettings
|
||||
? cloudSettings.buildMetaBlk(account?.userId, 'generalBlkMeta')
|
||||
: emptyBlock('generalBlkMeta');
|
||||
meta.blocks.push(emptyBlock('binaryDataMetainfo'), generalBlkMeta);
|
||||
return { kind: 'data', blk: meta };
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface CharActionContext {
|
||||
readonly payload: BlkBlock | undefined;
|
||||
/** Raw UTF-8 request body text, for EATT_JSON_REQUEST custom actions. */
|
||||
readonly rawText: string;
|
||||
/** Raw request body bytes, for compressed or PBBD-framed cloud-settings uploads. */
|
||||
readonly rawBody?: Uint8Array;
|
||||
/**
|
||||
* A request parameter sent as an HTTP header: char_request_blk_from_server (scripts
|
||||
* charRequestBlk) sends the top-level parameters of its BLK that way and no body (lab round
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* text) and the traffic log records which form it was.
|
||||
*/
|
||||
import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
|
||||
import { describePbbdForLog, isPbbdStream } from '../cloud-settings/cloud-settings-codec.ts';
|
||||
import { markUncompressed, unpackMarked } from './compression-marker.ts';
|
||||
|
||||
export function encodeDataAnswer(blk: BlkBlock): Uint8Array {
|
||||
@@ -28,6 +29,9 @@ const BINARY_BLK_LABELS = new Set([1, 2, 3, 6]);
|
||||
export function decodeRequestPayload(body: Uint8Array): DecodedPayload {
|
||||
if (body.length === 0) return { form: 'empty', text: '' };
|
||||
try {
|
||||
if (isPbbdStream(body)) {
|
||||
return { form: 'PBBD stream', text: describePbbdForLog(body) };
|
||||
}
|
||||
const marked = unpackMarked(body);
|
||||
if (marked) {
|
||||
if (!marked.data) return { form: `marked ${marked.method}, not unpacked`, text: '' };
|
||||
|
||||
@@ -41,6 +41,7 @@ export class CharService implements Service {
|
||||
userId: header(request, 'uidhint'),
|
||||
payload: payload.blk,
|
||||
rawText: payload.text,
|
||||
rawBody: request.body,
|
||||
headerParam: (name) => header(request, name.toLowerCase()),
|
||||
})
|
||||
: { kind: 'data', blk: emptyBlock() };
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Wire codecs for War Thunder's cloud settings subsystem (`online_storage` / `generalBlk`,
|
||||
* implementation notes; aces.exe 2.61.0.37 at 0x4662a70..0x466b2ec and 0x41537d0..0x4154020).
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
|
||||
import {
|
||||
decodeBlk,
|
||||
emptyBlock,
|
||||
encodeBlk,
|
||||
findBlock,
|
||||
findParam,
|
||||
setParam,
|
||||
type BlkBlock,
|
||||
} from '@wto/blk';
|
||||
import { unpackMarked } from '../char/compression-marker.ts';
|
||||
|
||||
/**
|
||||
* The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and
|
||||
* `PlayerProfile::storeGeneralBlk` (0xf5b080).
|
||||
*/
|
||||
export const GENERAL_BLK_TYPES = [
|
||||
'GBT_GENERAL_STORAGE',
|
||||
'GBT_GENERAL_SETTINGS',
|
||||
'GBT_GENERAL_MACHINE_SETTINGS',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd`
|
||||
* first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard
|
||||
* frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly.
|
||||
*/
|
||||
export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip';
|
||||
|
||||
export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250)
|
||||
|
||||
export interface ParsedGblkUpload {
|
||||
readonly blkType: string;
|
||||
readonly version: number;
|
||||
readonly contentHash: string;
|
||||
readonly container: BlkBlock;
|
||||
}
|
||||
|
||||
export function isPbbdStream(bytes: Uint8Array): boolean {
|
||||
if (bytes.byteLength < 8) return false;
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unpack a single `cln_set_general_blk` request body (0x4666ee7 -> 0x3371f30 -> 0x3371cc0).
|
||||
* Unlike CharServer answers, `0x3371cc0` omits the 1-byte marker and names the compressor in
|
||||
* the HTTP `compr` header (`zstd`: pure Zstd frame; `zlib`: 4-byte BE size + zlib stream;
|
||||
* `gzip`: standard gzip; omitted/`none`: raw binary BLK).
|
||||
*/
|
||||
export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined {
|
||||
if (bytes.byteLength === 0) return undefined;
|
||||
const raw = decompressCloudBytes(bytes, comprHeader);
|
||||
if (!raw || raw.byteLength === 0) return undefined;
|
||||
try {
|
||||
return decodeBlk(raw);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `cln_bulk_set_gblk` `PBBD` stream (0x4663080..0x4663f1c, 0x41537d0..0x4154020).
|
||||
* Header is 8 bytes: `"PBBD"` + `uint16_le(1)` + `uint16_le(chunkCount)`.
|
||||
* Each chunk is `uint32_le(payloadLen)` + `uint8(marker)` + `payload`.
|
||||
* Each `desc:t="store_gblk"` descriptor chunk is immediately followed by its `ContainerBlk` chunk.
|
||||
*/
|
||||
export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray<ParsedGblkUpload> {
|
||||
if (!isPbbdStream(bytes)) return [];
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const chunkCount = view.getUint16(6, true);
|
||||
const chunks: Array<BlkBlock | undefined> = [];
|
||||
let offset = 8;
|
||||
|
||||
for (let i = 0; i < chunkCount; i++) {
|
||||
if (offset + 5 > bytes.byteLength) break;
|
||||
const payloadLen = view.getUint32(offset, true);
|
||||
const marker = bytes[offset + 4]!;
|
||||
offset += 5;
|
||||
if (offset + payloadLen > bytes.byteLength) break;
|
||||
const slice = bytes.subarray(offset, offset + payloadLen);
|
||||
offset += payloadLen;
|
||||
chunks.push(decodeMarkedChunk(marker, slice));
|
||||
}
|
||||
|
||||
const uploads: ParsedGblkUpload[] = [];
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const meta = chunks[i];
|
||||
if (!meta) continue;
|
||||
const desc = stringOf(meta, 'desc');
|
||||
if (desc === 'store_gblk') {
|
||||
const containerCandidate = chunks[i + 1];
|
||||
i += 1;
|
||||
const blkType = stringOf(meta, 'blkType');
|
||||
if (!blkType || !containerCandidate) continue;
|
||||
const fallbackVersion = intOf(meta, 'version') ?? 1;
|
||||
const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion);
|
||||
const contentHash = stringOf(meta, 'contentHash') || computeContentHash(extracted.content);
|
||||
uploads.push({
|
||||
blkType,
|
||||
version: extracted.version,
|
||||
contentHash,
|
||||
container: extracted.container,
|
||||
});
|
||||
} else if (desc === 'bigquery' || desc === 'logout') {
|
||||
// Both `bigquery` (0x4663916) and `logout` (0x4663b66) append one companion payload chunk.
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return uploads;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an uploaded `ContainerBlk` (`version:i` + `content { ... }`, 0x4664b55 / 0x466a810)
|
||||
* so stored `.blk` files always carry an authoritative positive `version:i` and a `content` block.
|
||||
*/
|
||||
export function normalizeContainerBlk(
|
||||
incoming: BlkBlock,
|
||||
fallbackVersion: number,
|
||||
): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } {
|
||||
const existingContent = findBlock(incoming, 'content');
|
||||
const rawVersion = intOf(incoming, 'version') ?? fallbackVersion;
|
||||
const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion);
|
||||
|
||||
const content = existingContent
|
||||
? cloneAsContent(existingContent)
|
||||
: cloneAsContent(incoming);
|
||||
|
||||
const container = buildContainerBlk(version, content);
|
||||
return { version, content, container };
|
||||
}
|
||||
|
||||
export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock {
|
||||
const container = emptyBlock();
|
||||
setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) });
|
||||
container.blocks.push(cloneAsContent(content));
|
||||
return container;
|
||||
}
|
||||
|
||||
/** MD5 hex of the serialized `content` DataBlock (`ContainerBlk::calcHash` at 0x466af40 -> 0x4661840). */
|
||||
export function computeContentHash(content: BlkBlock): string {
|
||||
const rootCopy = emptyBlock();
|
||||
rootCopy.params.push(...content.params);
|
||||
rootCopy.blocks.push(...content.blocks);
|
||||
return createHash('md5').update(encodeBlk(rootCopy)).digest('hex');
|
||||
}
|
||||
|
||||
export function describePbbdForLog(bytes: Uint8Array): string {
|
||||
const uploads = parsePbbdBulkUploads(bytes);
|
||||
if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)';
|
||||
return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', ');
|
||||
}
|
||||
|
||||
function cloneAsContent(source: BlkBlock): BlkBlock {
|
||||
return {
|
||||
name: 'content',
|
||||
params: [...source.params],
|
||||
blocks: [...source.blocks],
|
||||
};
|
||||
}
|
||||
|
||||
function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined {
|
||||
const method = comprHeader?.trim().toLowerCase();
|
||||
try {
|
||||
if (method === 'zstd') return zstdDecompressSync(bytes);
|
||||
if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined;
|
||||
if (method === 'gzip') return gunzipSync(bytes);
|
||||
if (!method || method === 'none') {
|
||||
const marked = unpackMarked(bytes);
|
||||
return marked?.data ?? bytes;
|
||||
}
|
||||
const marked = unpackMarked(bytes);
|
||||
return marked?.data;
|
||||
} catch {
|
||||
const marked = unpackMarked(bytes);
|
||||
return marked?.data;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined {
|
||||
if (payload.byteLength === 0) return emptyBlock();
|
||||
try {
|
||||
let raw: Uint8Array | undefined;
|
||||
if (marker === 0x69) {
|
||||
raw = payload; // 'i' uncompressed
|
||||
} else if (marker === 0x5a) {
|
||||
raw = zstdDecompressSync(payload); // 'Z' zstd (0-byte header)
|
||||
} else if (marker === 0x7a) {
|
||||
raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined; // 'z' 4B BE size + zlib
|
||||
} else if (marker === 0x1f) {
|
||||
raw = gunzipSync(payload); // gzip
|
||||
}
|
||||
return raw ? decodeBlk(raw) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function stringOf(block: BlkBlock, name: string): string | undefined {
|
||||
const param = findParam(block, name);
|
||||
return param?.value.type === 'string' ? param.value.value : undefined;
|
||||
}
|
||||
|
||||
function intOf(block: BlkBlock, name: string): number | undefined {
|
||||
const param = findParam(block, name);
|
||||
return param?.value.type === 'int' ? param.value.value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Per-player cloud settings persistence inside `<data>/saves/<userId>/cloud-settings/`
|
||||
*. Keeping cloud settings inside each player's save directory means
|
||||
* copying `saves/<userId>/` to another machine or fresh client folder carries all game
|
||||
* options, keybinds, HUD settings, presets, and map preferences along automatically.
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||
import {
|
||||
GENERAL_BLK_TYPES,
|
||||
SUPPORTED_CLOUD_COMPRESSIONS,
|
||||
type ParsedGblkUpload,
|
||||
} from './cloud-settings-codec.ts';
|
||||
|
||||
interface StoredBlockMeta {
|
||||
version: number;
|
||||
contentHash: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface CloudSettingsMetaFile {
|
||||
formatVersion: 1;
|
||||
blocks: Record<string, StoredBlockMeta>;
|
||||
}
|
||||
|
||||
export class CloudSettingsStore {
|
||||
readonly #savesRoot: string;
|
||||
|
||||
constructor(dataFolder: string) {
|
||||
this.#savesRoot = join(dataFolder, 'saves');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `generalBlkMeta` / `cln_get_meta_blk` DataBlock (aces.exe 0x4665cf4..0x4666900).
|
||||
* Every registered `blkType` is marked `perMachine:b=no` in `__schema` so settings travel
|
||||
* with the player's save across machines without hardware-ID partitioning.
|
||||
*/
|
||||
buildMetaBlk(userId?: string, blockName?: string): BlkBlock {
|
||||
const meta = blockName ? emptyBlock(blockName) : emptyBlock();
|
||||
setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` });
|
||||
setParam(meta, 'compressionSupported', { type: 'string', value: SUPPORTED_CLOUD_COMPRESSIONS });
|
||||
|
||||
const schema = ensureBlock(meta, '__schema');
|
||||
const saved = userId && isValidUserId(userId) ? this.#loadMeta(userId).blocks : {};
|
||||
const allTypes = new Set<string>([...GENERAL_BLK_TYPES, ...Object.keys(saved)]);
|
||||
|
||||
for (const blkType of allTypes) {
|
||||
const schemaEntry = ensureBlock(schema, blkType);
|
||||
setParam(schemaEntry, 'perMachine', { type: 'bool', value: false });
|
||||
|
||||
const entry = saved[blkType];
|
||||
if (entry && entry.version > 0) {
|
||||
const typeBlock = ensureBlock(meta, blkType);
|
||||
setParam(typeBlock, 'version', { type: 'int', value: entry.version });
|
||||
setParam(typeBlock, 'contentHash', { type: 'string', value: entry.contentHash });
|
||||
}
|
||||
}
|
||||
|
||||
return meta;
|
||||
}
|
||||
|
||||
/** Load a stored `ContainerBlk` (`version:i` + `content { ... }`) for `cln_get_general_blk`. */
|
||||
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
|
||||
if (!isValidUserId(userId) || !isValidBlkType(blkType)) return undefined;
|
||||
const blkPath = this.#blkPath(userId, blkType);
|
||||
if (!existsSync(blkPath)) return undefined;
|
||||
try {
|
||||
return decodeBlk(readFileSync(blkPath));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist a single uploaded `ContainerBlk` and update `meta.json` atomically. */
|
||||
saveUpload(userId: string, upload: ParsedGblkUpload): boolean {
|
||||
if (!isValidUserId(userId) || !isValidBlkType(upload.blkType)) return false;
|
||||
const meta = this.#loadMeta(userId);
|
||||
const nextVersion = Math.max(1, Math.trunc(upload.version));
|
||||
setParam(upload.container, 'version', { type: 'int', value: nextVersion });
|
||||
|
||||
writeFileAtomic(this.#blkPath(userId, upload.blkType), encodeBlk(upload.container));
|
||||
meta.blocks[upload.blkType] = {
|
||||
version: nextVersion,
|
||||
contentHash: upload.contentHash,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
writeFileAtomic(this.#metaPath(userId), JSON.stringify(meta, null, 2));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Persist a batch of uploads from `cln_bulk_set_gblk`. */
|
||||
saveBulkUploads(userId: string, uploads: ReadonlyArray<ParsedGblkUpload>): number {
|
||||
let savedCount = 0;
|
||||
for (const upload of uploads) {
|
||||
if (this.saveUpload(userId, upload)) savedCount += 1;
|
||||
}
|
||||
return savedCount;
|
||||
}
|
||||
|
||||
#loadMeta(userId: string): CloudSettingsMetaFile {
|
||||
const metaPath = this.#metaPath(userId);
|
||||
if (!existsSync(metaPath)) return { formatVersion: 1, blocks: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(metaPath, 'utf8')) as Partial<CloudSettingsMetaFile>;
|
||||
return {
|
||||
formatVersion: 1,
|
||||
blocks: parsed.blocks && typeof parsed.blocks === 'object' ? { ...parsed.blocks } : {},
|
||||
};
|
||||
} catch {
|
||||
return { formatVersion: 1, blocks: {} };
|
||||
}
|
||||
}
|
||||
|
||||
#folderOf(userId: string): string {
|
||||
return join(this.#savesRoot, userId, 'cloud-settings');
|
||||
}
|
||||
|
||||
#metaPath(userId: string): string {
|
||||
return join(this.#folderOf(userId), 'meta.json');
|
||||
}
|
||||
|
||||
#blkPath(userId: string, blkType: string): string {
|
||||
return join(this.#folderOf(userId), `${blkType}.blk`);
|
||||
}
|
||||
}
|
||||
|
||||
function isValidUserId(userId: string): boolean {
|
||||
return /^\d+$/.test(userId);
|
||||
}
|
||||
|
||||
function isValidBlkType(blkType: string): boolean {
|
||||
return /^[A-Za-z0-9_.-]{1,80}$/.test(blkType);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { AccountStore } from './accounts/account-store.ts';
|
||||
import { actionTable } from './char/actions/action-table.ts';
|
||||
import { CharService } from './char/char-service.ts';
|
||||
import { ClanStore } from './clans/clan-store.ts';
|
||||
import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
|
||||
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
|
||||
import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
|
||||
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
|
||||
@@ -54,6 +55,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
// One store for all services: accounts registered at sign-in must be visible everywhere.
|
||||
const accounts = new AccountStore(options.dataFolder);
|
||||
const clans = new ClanStore(options.dataFolder);
|
||||
const cloudSettings = new CloudSettingsStore(options.dataFolder);
|
||||
let matching: MatchingService | undefined;
|
||||
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
|
||||
|
||||
@@ -62,7 +64,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
new MarketplaceService(accounts, profiles, research.inventory, notifyInventoryChanged),
|
||||
new InventoryService(accounts, profiles, research.inventory),
|
||||
new LoginService(accounts),
|
||||
new CharService(actionTable({ profiles, accounts, research, clans, notifyInventoryChanged })),
|
||||
new CharService(actionTable({ profiles, accounts, research, clans, cloudSettings, notifyInventoryChanged })),
|
||||
new DownloadableContentService(),
|
||||
]);
|
||||
const log = new TrafficLog(options.dataFolder);
|
||||
|
||||
Reference in new issue
Block a user