feat(saves): edit account levels and avatars
Read rank thresholds and available avatar artwork from the selected copy. Persist avatar selections in the player profile and preserve free research points when a level changes.
This commit is contained in:
1 parent
d043a8f0f8
commit
5d1d7001b8
22 files changed
+337
-63
No files matched your search
@@ -15,7 +15,7 @@ import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
|
||||
import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, 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/. */
|
||||
@@ -110,6 +110,8 @@ export function registerIpcHandlers(): void {
|
||||
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
||||
handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId));
|
||||
handle('saves:create', (request) => createSave(request));
|
||||
handle('saves:avatars', ({ copyId }) => getSaveAvatarChoices(copyId));
|
||||
handle('saves:avatarPreview', ({ copyId, avatar }) => getSaveAvatarPreview(copyId, avatar));
|
||||
handle('saves:editAccount', ({ copyId, userId, edits }) => changeSaveAccount(copyId, userId, edits));
|
||||
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
@@ -55,15 +55,27 @@ export async function createSave({ copyId, login, password, nick }: SaveRegistra
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSaveAvatarChoices(copyId: string): Promise<SaveAvatarChoices> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return await run({ operation: 'avatars', ...location(copy) }) as SaveAvatarChoices;
|
||||
}
|
||||
|
||||
export async function getSaveAvatarPreview(copyId: string, avatar: string): Promise<string | null> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return await run({ operation: 'avatarPreview', ...location(copy), avatar }) as string | null;
|
||||
}
|
||||
|
||||
export async function changeSaveAccount(copyId: string, userId: string, edits: AccountEdits): Promise<SaveDetails> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
const before = edits.premiumDays === undefined ? null : await captureSave(copy, userId);
|
||||
const changesProfile = edits.premiumDays !== undefined || edits.avatar !== undefined || edits.level !== undefined;
|
||||
const before = changesProfile ? await captureSave(copy, userId) : null;
|
||||
try {
|
||||
await run({ operation: 'editAccount', ...location(copy), userId, edits });
|
||||
} catch (error) {
|
||||
if (before &&
|
||||
(!(error instanceof AppError) || (error.code !== 'save_nick_invalid' && error.code !== 'save_not_found'))) {
|
||||
const rejectedEdit = error instanceof AppError &&
|
||||
['save_nick_invalid', 'save_avatar_invalid', 'save_level_invalid', 'save_not_found'].includes(error.code);
|
||||
if (before && !rejectedEdit) {
|
||||
await restoreDirectory(copy, userId, before);
|
||||
}
|
||||
throw error;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AppErrorCode } from '@shared/errors.ts';
|
||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
|
||||
interface Location {
|
||||
readonly gameFolder: string;
|
||||
@@ -9,6 +9,8 @@ interface Location {
|
||||
export type SaveTask = Location & (
|
||||
| { readonly operation: 'list' }
|
||||
| { readonly operation: 'details'; readonly userId: string }
|
||||
| { readonly operation: 'avatars' }
|
||||
| { readonly operation: 'avatarPreview'; readonly avatar: string }
|
||||
| { readonly operation: 'editAccount'; readonly userId: string; readonly edits: AccountEdits }
|
||||
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
|
||||
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean }
|
||||
@@ -19,5 +21,5 @@ export type SaveTask = Location & (
|
||||
| { 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 | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | null;
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
|
||||
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
||||
@@ -1,20 +1,27 @@
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||
|
||||
function execute(task: SaveTask): SaveReply {
|
||||
switch (task.operation) {
|
||||
case 'list':
|
||||
return { ok: true, result: listSaveSummaries(task.dataFolder) };
|
||||
return { ok: true, result: listSaveSummaries(task.dataFolder, task.gameFolder) };
|
||||
case 'details': {
|
||||
const result = readSaveDetails(task.dataFolder, task.userId);
|
||||
const result = readSaveDetails(task.dataFolder, task.userId, task.gameFolder);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'editAccount': {
|
||||
const status = editSaveAccount(task, task.userId, task.edits);
|
||||
if (status === 'updated') return { ok: true, result: null };
|
||||
return { ok: false, error: status === 'invalid-nick' ? 'save_nick_invalid' : 'save_not_found' };
|
||||
}
|
||||
case 'avatars':
|
||||
return { ok: true, result: listSaveAvatars(task) };
|
||||
case 'avatarPreview':
|
||||
return { ok: true, result: readSaveAvatar(task, task.avatar) };
|
||||
case 'editAccount':
|
||||
switch (editSaveAccount(task, task.userId, task.edits)) {
|
||||
case 'updated': return { ok: true, result: null };
|
||||
case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' };
|
||||
case 'invalid-avatar': return { ok: false, error: 'save_avatar_invalid' };
|
||||
case 'invalid-level': return { ok: false, error: 'save_level_invalid' };
|
||||
case 'not-found': return { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'edit':
|
||||
return editSaveCurrencies(task, task.userId, task.values)
|
||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||
|
||||
@@ -354,6 +354,9 @@
|
||||
"battles": "Recorded battles",
|
||||
"lastBattle": "Last battle",
|
||||
"premiumDays": "Premium account days",
|
||||
"avatar": "Avatar",
|
||||
"avatarUnavailable": "Avatar unavailable",
|
||||
"level": "Account level",
|
||||
"saveAccount": "Save account details",
|
||||
"apply": "Save changes",
|
||||
"saved": "Changes saved.",
|
||||
@@ -565,6 +568,8 @@
|
||||
"save_login_exists": "An account with this login already exists.",
|
||||
"save_password_invalid": "Enter a password.",
|
||||
"save_nick_invalid": "Enter a nickname with up to 16 characters.",
|
||||
"save_avatar_invalid": "Select an avatar available in this game copy.",
|
||||
"save_level_invalid": "Enter a level supported by this game copy.",
|
||||
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
|
||||
"copy_not_found": "The selected copy is no longer available.",
|
||||
"copies_write_failed": "The copy registry could not be saved.",
|
||||
|
||||
@@ -354,6 +354,9 @@
|
||||
"battles": "已记录对局",
|
||||
"lastBattle": "上次对局",
|
||||
"premiumDays": "高级账户剩余天数",
|
||||
"avatar": "头像",
|
||||
"avatarUnavailable": "头像不可用",
|
||||
"level": "账号等级",
|
||||
"saveAccount": "保存账号信息",
|
||||
"apply": "保存更改",
|
||||
"saved": "更改已保存。",
|
||||
@@ -565,6 +568,8 @@
|
||||
"save_login_exists": "该登录账号已注册。",
|
||||
"save_password_invalid": "请输入密码。",
|
||||
"save_nick_invalid": "请输入最多 16 个字符的昵称。",
|
||||
"save_avatar_invalid": "请选择此副本中可用的头像。",
|
||||
"save_level_invalid": "请输入此副本支持的账号等级。",
|
||||
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
|
||||
"copy_not_found": "所选副本已不可用。",
|
||||
"copies_write_failed": "无法保存副本记录。",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { SaveAvatarChoices } from '@shared/schemas/saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
|
||||
interface SaveAvatarFieldProps {
|
||||
readonly copyId: string;
|
||||
readonly avatar: string;
|
||||
readonly disabled: boolean;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function SaveAvatarField({ copyId, avatar, disabled, onError }: SaveAvatarFieldProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [choices, setChoices] = useState<SaveAvatarChoices | null>(null);
|
||||
const [selected, setSelected] = useState(avatar);
|
||||
const [preview, setPreview] = useState<{ id: string; data: string } | null>(null);
|
||||
const canPreview = choices?.some(({ id }) => id === selected) ?? false;
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:avatars', { copyId })
|
||||
.then((value) => { if (mounted) setChoices(value); })
|
||||
.catch((error: unknown) => {
|
||||
if (mounted) {
|
||||
setChoices([]);
|
||||
onError(error);
|
||||
}
|
||||
});
|
||||
return () => { mounted = false; };
|
||||
}, [copyId, onError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canPreview) return;
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:avatarPreview', { copyId, avatar: selected })
|
||||
.then((data) => { if (mounted) setPreview(data ? { id: selected, data } : null); })
|
||||
.catch((error: unknown) => { if (mounted) onError(error); });
|
||||
return () => { mounted = false; };
|
||||
}, [canPreview, copyId, selected, onError]);
|
||||
|
||||
const label = t('saves.avatar');
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
return (
|
||||
<Row label={label}>
|
||||
{choices === null
|
||||
? <span>{t('saves.loading')}</span>
|
||||
: choices.length === 0
|
||||
? <span>{t('saves.avatarUnavailable')}</span>
|
||||
: (
|
||||
<div className="copy-list-actions">
|
||||
{canPreview && preview?.id === selected && (
|
||||
<img src={`data:image/avif;base64,${preview.data}`} width={48} height={48} alt="" />
|
||||
)}
|
||||
<select className="select" aria-label={label} name="avatar" value={selected} disabled={disabled}
|
||||
onChange={(event) => setSelected(event.currentTarget.value)}>
|
||||
{!canPreview && <option value={selected} disabled>{t('saves.avatarUnavailable')}</option>}
|
||||
{choices.map(({ id, name }) => <option key={id} value={id}>{name[language]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
import type { SaveSection } from '../../shell/navigation.ts';
|
||||
import { OfficialSaveImport } from './OfficialSaveImport.tsx';
|
||||
import { SaveAvatarField } from './SaveAvatarField.tsx';
|
||||
import { SaveResearch } from './SaveResearch.tsx';
|
||||
import { SaveBackups } from './SaveBackups.tsx';
|
||||
|
||||
@@ -109,8 +110,12 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
const data = new FormData(event.currentTarget);
|
||||
const nick = String(data.get('nick') ?? '').trim();
|
||||
const days = String(data.get('premiumDays') ?? '').trim();
|
||||
const avatar = String(data.get('avatar') ?? '');
|
||||
const level = String(data.get('level') ?? '').trim();
|
||||
const edits: AccountEdits = {};
|
||||
if (nick !== details.save.nick) edits.nick = nick;
|
||||
if (avatar && avatar !== details.save.avatar) edits.avatar = avatar;
|
||||
if (level !== '' && Number(level) !== details.save.level) edits.level = Number(level);
|
||||
if (days !== '' && Number(days) !== details.save.premiumDays) edits.premiumDays = Number(days);
|
||||
if (Object.keys(edits).length === 0) return;
|
||||
setSaving(true);
|
||||
@@ -180,6 +185,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
</div>
|
||||
<dl className="kv">
|
||||
<dt>{t('saves.login')}</dt><dd>{save.login}</dd>
|
||||
<dt>{t('saves.level')}</dt><dd>{save.level === null ? '—' : format.format(save.level)}</dd>
|
||||
<dt>{t('saves.silverLions')}</dt><dd>{save.currencies ? format.format(save.currencies.silverLions) : '—'}</dd>
|
||||
<dt>{t('saves.vehicles')}</dt><dd>{format.format(save.vehicleCount)}</dd>
|
||||
<dt>{t('saves.battles')}</dt><dd>{format.format(save.battleCount)}</dd>
|
||||
@@ -231,10 +237,17 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
<>
|
||||
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
|
||||
<Row label={t('saves.login')}>{save.login}</Row>
|
||||
<form key={save.userId + ':' + save.nick + ':' + save.premiumDays} onSubmit={submitAccount}>
|
||||
<form key={JSON.stringify([copy.id, save.userId, save.nick, save.avatar, save.level, save.premiumDays])} onSubmit={submitAccount}>
|
||||
<Row label={t('saves.nick')}>
|
||||
<input className="input" aria-label={t('saves.nick')} name="nick" defaultValue={save.nick} disabled={readOnly || saving} required />
|
||||
</Row>
|
||||
<SaveAvatarField copyId={copy.id} avatar={save.avatar} disabled={readOnly || saving} onError={onError} />
|
||||
<Row label={t('saves.level')}>
|
||||
{details.maxLevel === null ? '—' : (
|
||||
<input className="input" aria-label={t('saves.level')} type="number" min="0" max={details.maxLevel}
|
||||
step="1" name="level" defaultValue={save.level ?? ''} disabled={readOnly || saving} />
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t('saves.premiumDays')}>
|
||||
<input className="input" aria-label={t('saves.premiumDays')} type="number" min="0" step="1"
|
||||
name="premiumDays" defaultValue={save.premiumDays} disabled={readOnly || saving} />
|
||||
|
||||
@@ -28,6 +28,8 @@ export const APP_ERROR_CODES = [
|
||||
'save_login_exists',
|
||||
'save_password_invalid',
|
||||
'save_nick_invalid',
|
||||
'save_avatar_invalid',
|
||||
'save_level_invalid',
|
||||
'copies_write_failed',
|
||||
'maintenance_busy',
|
||||
'maintenance_location',
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
||||
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts';
|
||||
import { AccountEditsSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
|
||||
|
||||
@@ -146,6 +146,14 @@ export const ipcContract = {
|
||||
input: SaveRegistrationSchema,
|
||||
output: SaveListSchema,
|
||||
},
|
||||
'saves:avatars': {
|
||||
input: z.object({ copyId: CopyIdSchema }),
|
||||
output: SaveAvatarChoicesSchema,
|
||||
},
|
||||
'saves:avatarPreview': {
|
||||
input: z.object({ copyId: CopyIdSchema, avatar: SaveAvatarIdSchema }),
|
||||
output: z.base64().nullable(),
|
||||
},
|
||||
'saves:editAccount': {
|
||||
input: SaveKeysSchema.extend({ edits: AccountEditsSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
|
||||
@@ -4,7 +4,19 @@ import { CopyIdSchema } from './install.ts';
|
||||
export const LocalUserIdSchema = z.string().regex(/^\d+$/);
|
||||
|
||||
export const SaveKeysSchema = z.object({ copyId: CopyIdSchema, userId: LocalUserIdSchema });
|
||||
export const AccountEditsSchema = z.object({ nick: z.string().optional(), premiumDays: z.number().int().nonnegative().optional() });
|
||||
export const SaveAvatarIdSchema = z.string().regex(/^cardicon_[a-z0-9_]+$/);
|
||||
export const SaveAvatarChoicesSchema = z.array(z.object({
|
||||
id: SaveAvatarIdSchema,
|
||||
name: z.object({ en: z.string(), zh: z.string() }),
|
||||
}));
|
||||
export type SaveAvatarChoices = z.output<typeof SaveAvatarChoicesSchema>;
|
||||
|
||||
export const AccountEditsSchema = z.object({
|
||||
nick: z.string().optional(),
|
||||
premiumDays: z.number().int().nonnegative().optional(),
|
||||
avatar: SaveAvatarIdSchema.optional(),
|
||||
level: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
export type AccountEdits = z.output<typeof AccountEditsSchema>;
|
||||
|
||||
export const CurrencyEditsSchema = z.object({
|
||||
@@ -18,6 +30,8 @@ const SaveSummarySchema = z.object({
|
||||
login: z.string(),
|
||||
nick: z.string(),
|
||||
created: z.string(),
|
||||
avatar: z.string(),
|
||||
level: z.number().int().nonnegative().nullable(),
|
||||
currencies: z.object({
|
||||
silverLions: z.number(),
|
||||
goldenEagles: z.number(),
|
||||
@@ -32,6 +46,7 @@ const SaveSummarySchema = z.object({
|
||||
export const SaveListSchema = z.object({ saves: z.array(SaveSummarySchema), current: LocalUserIdSchema.nullable() });
|
||||
export const SaveDetailsSchema = z.object({
|
||||
save: SaveSummarySchema,
|
||||
maxLevel: z.number().int().positive().nullable(),
|
||||
battles: z.array(z.object({
|
||||
id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(), mode: z.string(),
|
||||
vehicles: z.array(z.string()), silverLions: z.number(), researchPoints: z.number(),
|
||||
|
||||
@@ -111,19 +111,23 @@ class TrackedSource implements DatasetSource {
|
||||
}
|
||||
|
||||
readBlk(pack: GamePackName, path: string): BlkBlock {
|
||||
const gamePack = this.#gameFiles.pack(pack);
|
||||
const sha1 = gamePack.fileDigest(path);
|
||||
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
|
||||
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
|
||||
return gamePack.readBlk(path);
|
||||
return this.#trackFile(pack, path).readBlk(path);
|
||||
}
|
||||
|
||||
readText(pack: GamePackName, path: string): string {
|
||||
return this.#trackFile(pack, path).readText(path);
|
||||
}
|
||||
|
||||
readBytes(pack: GamePackName, path: string): Uint8Array {
|
||||
return this.#trackFile(pack, path).readBytes(path);
|
||||
}
|
||||
|
||||
#trackFile(pack: GamePackName, path: string) {
|
||||
const gamePack = this.#gameFiles.pack(pack);
|
||||
const sha1 = gamePack.fileDigest(path);
|
||||
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
|
||||
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
|
||||
return gamePack.readText(path);
|
||||
return gamePack;
|
||||
}
|
||||
|
||||
listFiles(pack: GamePackName): readonly string[] {
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { GamePackName } from '../game-files.ts';
|
||||
export interface DatasetSource {
|
||||
readBlk(pack: GamePackName, path: string): BlkBlock;
|
||||
readText(pack: GamePackName, path: string): string;
|
||||
readBytes(pack: GamePackName, path: string): Uint8Array;
|
||||
/** Every file path in a pack, sorted. */
|
||||
listFiles(pack: GamePackName): readonly string[];
|
||||
}
|
||||
|
||||
@@ -16,6 +16,22 @@ import type { Dataset } from './dataset.ts';
|
||||
const RANK = 'config/rank.blk';
|
||||
const SLOT = /^slot(\d+)$/;
|
||||
|
||||
/** Cumulative XP thresholds read in the same order as scripts/ranks.nut. */
|
||||
export const playerRankThresholds: Dataset<readonly number[]> = {
|
||||
id: 'player-rank-thresholds',
|
||||
version: 1,
|
||||
extract: (source) => {
|
||||
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'exp_for_playerRank');
|
||||
const thresholds: number[] = [];
|
||||
for (const { value } of block?.params ?? []) {
|
||||
const threshold = value.type === 'int' || value.type === 'int64' ? Number(value.value) : NaN;
|
||||
if (!Number.isSafeInteger(threshold) || threshold <= (thresholds.at(-1) ?? 0)) return [];
|
||||
thresholds.push(threshold);
|
||||
}
|
||||
return thresholds;
|
||||
},
|
||||
};
|
||||
|
||||
/** country -> parameter name -> vehicles needed, as written. */
|
||||
export type EraRequirements = Readonly<Record<string, Readonly<Record<string, number>>>>;
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ export type GamePackName =
|
||||
| 'aces.vromfs.bin'
|
||||
| 'gui.vromfs.bin'
|
||||
| 'lang.vromfs.bin'
|
||||
| 'ui/atlases.vromfs.bin';
|
||||
| 'ui/atlases.vromfs.bin'
|
||||
| 'ui/images.vromfs.bin';
|
||||
|
||||
/** Size and modification time provide a quick preliminary check of a pack file. */
|
||||
export interface PackStamp {
|
||||
|
||||
@@ -27,7 +27,11 @@ export class GamePack {
|
||||
}
|
||||
|
||||
readText(pathInPack: string): string {
|
||||
return Buffer.from(getFile(this.#archive, pathInPack)).toString('utf8');
|
||||
return Buffer.from(this.readBytes(pathInPack)).toString('utf8');
|
||||
}
|
||||
|
||||
readBytes(pathInPack: string): Uint8Array {
|
||||
return getFile(this.#archive, pathInPack);
|
||||
}
|
||||
|
||||
/** Every file path in the pack, sorted. */
|
||||
|
||||
@@ -8,6 +8,7 @@ export { REGISTRATION_PATH } from './accounts/registration-service.ts';
|
||||
export { HEALTH_PATH } from './transport/http-listener.ts';
|
||||
export { editSaveResearch, readSaveResearch } from './saves/save-research.ts';
|
||||
export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
|
||||
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
|
||||
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
|
||||
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
|
||||
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
|
||||
|
||||
@@ -10,12 +10,15 @@
|
||||
*/
|
||||
import { setParam, type BlkBlock } from '@wto/blk';
|
||||
import type { Account } from '../accounts/account-store.ts';
|
||||
import { appearance } from './profile-appearance.ts';
|
||||
import { clearStoreCart } from './profile-store-cart.ts';
|
||||
import { serverTimeNow } from './server-time.ts';
|
||||
|
||||
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
|
||||
const profile = structuredClone(saved);
|
||||
clearStoreCart(profile);
|
||||
const pilotIcon = appearance(profile).pilotIcon;
|
||||
if (pilotIcon !== undefined) setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon });
|
||||
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
|
||||
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
|
||||
return profile;
|
||||
|
||||
@@ -30,6 +30,10 @@ export function appearance(profile: BlkBlock): Partial<Record<AppearanceField, s
|
||||
const value = block && findParam(block, field)?.value;
|
||||
if (value?.type === 'string') result[field] = value.value;
|
||||
}
|
||||
if (result.pilotIcon === undefined) {
|
||||
const legacy = findParam(profile, 'pilotIcon')?.value;
|
||||
if (legacy?.type === 'string') result.pilotIcon = legacy.value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,57 +1,50 @@
|
||||
/**
|
||||
* Free research points in the profile.
|
||||
*
|
||||
* The client shows shop_get_free_exp (aces.exe 2.61.0.37 0x17a4f40): the total of the
|
||||
* experience counters (0x933190) minus "converted". The counters are top-level i64
|
||||
* parameters read and written by 0x9331b0: experience, experienceOffline, valUnlocks,
|
||||
* presented and valTrophy count into the total; Gaijin's new-account template has
|
||||
* experience:i64=0. Free research points are earned into "experience" and spending them
|
||||
* raises "converted".
|
||||
* The client uses the total of the saved experience counters for its account rank.
|
||||
* Free research points are that total minus the signed `converted` counter. Both
|
||||
* values were observed in the 2.61.0.43 client's rank and free RP getters.
|
||||
* Battle rewards increase `experience`, and spending free RP increases `converted`.
|
||||
*/
|
||||
import { findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { setParam, type BlkBlock } from '@wto/blk';
|
||||
import { int64Field } from './blk-fields.ts';
|
||||
|
||||
const EARNED = 'experience';
|
||||
const OTHER_EARNED = ['experienceOffline', 'valUnlocks', 'presented', 'valTrophy'] as const;
|
||||
const SPENT = 'converted';
|
||||
|
||||
export function freeResearchPoints(profile: BlkBlock): number {
|
||||
return earnedTotal(profile) - counter(profile, SPENT);
|
||||
return Number(playerExperience(profile) - int64Field(profile, SPENT));
|
||||
}
|
||||
|
||||
/** Spend free research points the player has (callers check freeResearchPoints first). */
|
||||
export function spendFreeResearchPoints(profile: BlkBlock, amount: number): void {
|
||||
setCounter(profile, SPENT, counter(profile, SPENT) + amount);
|
||||
setCounter(profile, SPENT, int64Field(profile, SPENT) + BigInt(amount));
|
||||
}
|
||||
|
||||
/** Credit convertible (free) research points earned in battle (`experience:i64`). */
|
||||
export function addFreeResearchPoints(profile: BlkBlock, amount: number): void {
|
||||
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
|
||||
if (amount > 0) setCounter(profile, EARNED, counter(profile, EARNED) + amount);
|
||||
if (amount > 0) setCounter(profile, EARNED, int64Field(profile, EARNED) + BigInt(amount));
|
||||
}
|
||||
|
||||
/** Make the free research points this amount (the save editor). */
|
||||
/** Set the free research balance while keeping the experience used for rank. */
|
||||
export function setFreeResearchPoints(profile: BlkBlock, amount: number): void {
|
||||
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
|
||||
const others = earnedTotal(profile) - counter(profile, EARNED);
|
||||
const earned = amount + counter(profile, SPENT) - others;
|
||||
if (earned >= 0) {
|
||||
setCounter(profile, EARNED, earned);
|
||||
} else {
|
||||
setCounter(profile, EARNED, 0);
|
||||
setCounter(profile, SPENT, counter(profile, SPENT) - earned);
|
||||
}
|
||||
setCounter(profile, SPENT, playerExperience(profile) - BigInt(amount));
|
||||
}
|
||||
|
||||
function earnedTotal(profile: BlkBlock): number {
|
||||
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + counter(profile, name), 0);
|
||||
export function playerExperience(profile: BlkBlock): bigint {
|
||||
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + int64Field(profile, name), 0n);
|
||||
}
|
||||
|
||||
function counter(profile: BlkBlock, name: string): number {
|
||||
const value = findParam(profile, name)?.value;
|
||||
if (value?.type === 'int64') return Number(value.value);
|
||||
return value?.type === 'int' ? value.value : 0;
|
||||
/** Set rank experience by applying the same adjustment to earned and converted RP. */
|
||||
export function setPlayerExperience(profile: BlkBlock, amount: bigint): void {
|
||||
const difference = amount - playerExperience(profile);
|
||||
setCounter(profile, EARNED, int64Field(profile, EARNED) + difference);
|
||||
setCounter(profile, SPENT, int64Field(profile, SPENT) + difference);
|
||||
}
|
||||
|
||||
function setCounter(profile: BlkBlock, name: string, amount: number): void {
|
||||
setParam(profile, name, { type: 'int64', value: BigInt(amount) });
|
||||
function setCounter(profile: BlkBlock, name: string, amount: bigint): void {
|
||||
setParam(profile, name, { type: 'int64', value: amount });
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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';
|
||||
import { stringField } from '../profile/blk-fields.ts';
|
||||
import type { SaveLocation } from './save-editor.ts';
|
||||
|
||||
export const DEFAULT_SAVE_AVATAR = 'cardicon_default';
|
||||
|
||||
const IMAGE_PACK = 'ui/images.vromfs.bin';
|
||||
const LANGUAGE_PACK = 'lang.vromfs.bin';
|
||||
const AVATAR_IMAGE = /^images\/avatars\/(cardicon_[a-z0-9_]+)\.avif$/;
|
||||
const LABEL_FILES = ['lang/menu_options.csv', 'lang/unlocks_achievements.csv'];
|
||||
|
||||
interface AvatarImage {
|
||||
readonly name: LocalizedCsvText;
|
||||
readonly image: string;
|
||||
}
|
||||
|
||||
type AvatarImages = Readonly<Record<string, AvatarImage>>;
|
||||
|
||||
const saveAvatarImages: Dataset<AvatarImages> = {
|
||||
id: 'save-avatar-images',
|
||||
version: 1,
|
||||
extract: (source) => {
|
||||
const paths = source.listFiles(IMAGE_PACK);
|
||||
const unlocks = source.readBlk('char.vromfs.bin', 'config/unlocks.blk');
|
||||
const ids = new Set(unlocks.blocks
|
||||
.filter((entry) => stringField(entry, 'type') === 'pilot')
|
||||
.map((entry) => stringField(entry, 'id')));
|
||||
ids.add(DEFAULT_SAVE_AVATAR);
|
||||
|
||||
const labels = new Map<string, LocalizedCsvText>();
|
||||
const languagePaths = source.listFiles(LANGUAGE_PACK);
|
||||
for (const file of LABEL_FILES) {
|
||||
if (!languagePaths.includes(file)) continue;
|
||||
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, file))) {
|
||||
labels.set(key, text);
|
||||
}
|
||||
}
|
||||
|
||||
const result: Record<string, AvatarImage> = {};
|
||||
for (const path of paths) {
|
||||
const id = AVATAR_IMAGE.exec(path)?.[1];
|
||||
if (!id || !ids.has(id)) continue;
|
||||
const fallback = id.slice('cardicon_'.length).replaceAll('_', ' ');
|
||||
const name = labels.get(`pilotIcons/${id}`) ?? labels.get(`${id}/name`) ??
|
||||
labels.get(`${id}/desc`) ?? { en: fallback, zh: fallback };
|
||||
const image = Buffer.from(source.readBytes(IMAGE_PACK, path)).toString('base64');
|
||||
result[id] = { name, image };
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
export function listSaveAvatars(location: SaveLocation) {
|
||||
return Object.entries(loadImages(location)).map(([id, { name }]) => ({ id, name }));
|
||||
}
|
||||
|
||||
export function readSaveAvatar(location: SaveLocation, id: string): string | null {
|
||||
return loadImages(location)[id]?.image ?? null;
|
||||
}
|
||||
|
||||
function loadImages(location: SaveLocation): AvatarImages {
|
||||
const files = new GameFiles(location.gameFolder);
|
||||
try {
|
||||
return new DatasetCache(location.dataFolder, files, () => {}).load(saveAvatarImages);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,20 @@ import { decodeBlk, findBlock, findParam, type BlkBlock } from '@wto/blk';
|
||||
import { AccountStore, normalizedNickname, type Account } from '../accounts/account-store.ts';
|
||||
import { ClanStore } from '../clans/clan-store.ts';
|
||||
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
|
||||
import { playerRankThresholds } from '../game-data/datasets/rank-settings.ts';
|
||||
import { GameFiles } from '../game-data/game-files.ts';
|
||||
import { intField, stringField } from '../profile/blk-fields.ts';
|
||||
import { appearance, setAppearance } from '../profile/profile-appearance.ts';
|
||||
import { balanceOf, setGjnCents, setGoldenEagles, setSilverLions } from '../profile/profile-currency.ts';
|
||||
import { remainingPremiumDays, setPremiumDays } from '../profile/profile-entitlements.ts';
|
||||
import { ownedVehicles } from '../profile/profile-hangar.ts';
|
||||
import { freeResearchPoints, setFreeResearchPoints } from '../profile/profile-research-points.ts';
|
||||
import { freeResearchPoints, playerExperience, setFreeResearchPoints, setPlayerExperience } from '../profile/profile-research-points.ts';
|
||||
import { EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
|
||||
import { serverTimeNow } from '../profile/server-time.ts';
|
||||
import { setUpProfiles } from '../profiles-setup.ts';
|
||||
import { loadTuning } from '../tuning/tuning.ts';
|
||||
import { DEFAULT_SAVE_AVATAR, readSaveAvatar } from './save-avatars.ts';
|
||||
|
||||
export interface SaveLocation {
|
||||
readonly gameFolder: string;
|
||||
@@ -28,11 +31,14 @@ export interface CurrencyEdits {
|
||||
readonly freeRp?: number | undefined;
|
||||
}
|
||||
|
||||
function summary(account: Account, profile: BlkBlock | undefined) {
|
||||
function summary(account: Account, profile: BlkBlock | undefined, thresholds: readonly number[]) {
|
||||
const battles = profile ? battleEntries(profile) : [];
|
||||
const { userId, login, nick, created } = account;
|
||||
const xp = profile ? playerExperience(profile) : 0n;
|
||||
return {
|
||||
userId, login, nick, created,
|
||||
avatar: (profile && appearance(profile).pilotIcon) || DEFAULT_SAVE_AVATAR,
|
||||
level: thresholds.length ? thresholds.filter((threshold) => xp >= BigInt(threshold)).length : null,
|
||||
currencies: profile ? { ...balanceOf(profile), freeRp: freeResearchPoints(profile) } : null,
|
||||
vehicleCount: profile ? ownedVehicles(profile).size : 0,
|
||||
battleCount: battles.length,
|
||||
@@ -71,11 +77,24 @@ function battleEntries(profile: BlkBlock) {
|
||||
.sort((a, b) => b.time - a.time || b.id.localeCompare(a.id));
|
||||
}
|
||||
|
||||
export function listSaveSummaries(dataFolder: string) {
|
||||
return new AccountStore(dataFolder).all().map((account) => summary(account, readSaveSnapshot(dataFolder, account.userId)));
|
||||
function rankThresholds(dataFolder: string, gameFolder: string | undefined): readonly number[] {
|
||||
if (!gameFolder) return [];
|
||||
try {
|
||||
return new DatasetCache(dataFolder, new GameFiles(gameFolder), () => {}).load(playerRankThresholds);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function readSaveDetails(dataFolder: string, userId: string) {
|
||||
export function listSaveSummaries(dataFolder: string, gameFolder?: string) {
|
||||
const accounts = new AccountStore(dataFolder).all();
|
||||
if (!accounts.length) return [];
|
||||
const thresholds = rankThresholds(dataFolder, gameFolder);
|
||||
return accounts.map((account) => summary(account, readSaveSnapshot(dataFolder, account.userId), thresholds));
|
||||
}
|
||||
|
||||
export function readSaveDetails(dataFolder: string, userId: string, gameFolder?: string) {
|
||||
const account = new AccountStore(dataFolder).byUserId(userId);
|
||||
if (!account) return null;
|
||||
const profile = readSaveSnapshot(dataFolder, userId);
|
||||
@@ -84,22 +103,42 @@ export function readSaveDetails(dataFolder: string, userId: string) {
|
||||
? (findBlock(profile, 'unitResearch')?.blocks ?? []).map(({ name }) => ({ name, points: researchPointsOf(profile, name) }))
|
||||
.filter(({ points }) => points > 0)
|
||||
: [];
|
||||
return { save: summary(account, profile), battles: profile ? battleEntries(profile) : [], owned, research };
|
||||
const thresholds = rankThresholds(dataFolder, gameFolder);
|
||||
return {
|
||||
save: summary(account, profile, thresholds),
|
||||
battles: profile ? battleEntries(profile) : [],
|
||||
owned,
|
||||
research,
|
||||
maxLevel: thresholds.length || null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface AccountEdits {
|
||||
readonly nick?: string | undefined;
|
||||
readonly premiumDays?: number | undefined;
|
||||
readonly avatar?: string | undefined;
|
||||
readonly level?: number | undefined;
|
||||
}
|
||||
|
||||
export function editSaveAccount(location: SaveLocation, userId: string, edits: AccountEdits): 'updated' | 'invalid-nick' | 'not-found' {
|
||||
export function editSaveAccount(location: SaveLocation, userId: string, edits: AccountEdits): 'updated' | 'invalid-nick' | 'invalid-avatar' | 'invalid-level' | 'not-found' {
|
||||
const accounts = new AccountStore(location.dataFolder);
|
||||
if (!accounts.byUserId(userId)) return 'not-found';
|
||||
const nick = edits.nick === undefined ? undefined : normalizedNickname(edits.nick);
|
||||
if (edits.nick !== undefined && nick === undefined) return 'invalid-nick';
|
||||
const days = edits.premiumDays;
|
||||
if (days !== undefined) {
|
||||
updateProfile(location, accounts, userId, (profile) => setPremiumDays(profile, days, serverTimeNow()));
|
||||
const { avatar, level, premiumDays } = edits;
|
||||
if (avatar !== undefined && readSaveAvatar(location, avatar) === null) return 'invalid-avatar';
|
||||
let xp: number | undefined;
|
||||
if (level !== undefined) {
|
||||
const thresholds = rankThresholds(location.dataFolder, location.gameFolder);
|
||||
if (!thresholds.length || !Number.isSafeInteger(level) || level < 0 || level > thresholds.length) return 'invalid-level';
|
||||
xp = level === 0 ? 0 : thresholds[level - 1];
|
||||
}
|
||||
if (avatar !== undefined || xp !== undefined || premiumDays !== undefined) {
|
||||
updateProfile(location, accounts, userId, (profile) => {
|
||||
if (avatar !== undefined) setAppearance(profile, 'pilotIcon', avatar);
|
||||
if (xp !== undefined) setPlayerExperience(profile, BigInt(xp));
|
||||
if (premiumDays !== undefined) setPremiumDays(profile, premiumDays, serverTimeNow());
|
||||
});
|
||||
}
|
||||
return nick === undefined ? 'updated' : accounts.rename(userId, nick);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user