feat(saves): edit local save nicknames and premium days
Let the launcher update a save's account nickname and replace or clear its remaining premium time. Reuse registration validation and preserve the existing login and password hash.
This commit is contained in:
1 parent
1d3af395c2
commit
d20b7f4249
13 files changed
+127
-19
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 { 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, 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,7 @@ 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:editAccount', ({ copyId, userId, edits }) => changeSaveAccount(copyId, userId, edits));
|
||||
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
|
||||
|
||||
handle('saves:pickArchive', (_input, sender) => pickSaveArchive(BrowserWindow.fromWebContents(sender)));
|
||||
|
||||
@@ -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 { 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, 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,6 +55,23 @@ export async function createSave({ copyId, login, password, nick }: SaveRegistra
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
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'))) {
|
||||
await restoreDirectory(copy, userId, before);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return getSaveDetails(copyId, userId);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setSaveCurrencies(copyId: string, userId: string, values: CurrencyEdits): Promise<SaveDetails> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AppErrorCode } from '@shared/errors.ts';
|
||||
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
|
||||
|
||||
interface Location {
|
||||
readonly gameFolder: string;
|
||||
@@ -9,6 +9,7 @@ interface Location {
|
||||
export type SaveTask = Location & (
|
||||
| { readonly operation: 'list' }
|
||||
| { readonly operation: 'details'; readonly userId: 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 }
|
||||
| { readonly operation: 'importOfficial'; readonly paths: readonly string[]; readonly userId: string; readonly options: OfficialImportOptions }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { AccountStore, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server';
|
||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||
|
||||
function execute(task: SaveTask): SaveReply {
|
||||
@@ -10,6 +10,11 @@ function execute(task: SaveTask): SaveReply {
|
||||
const result = readSaveDetails(task.dataFolder, task.userId);
|
||||
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 'edit':
|
||||
return editSaveCurrencies(task, task.userId, task.values)
|
||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||
|
||||
@@ -354,6 +354,7 @@
|
||||
"battles": "Recorded battles",
|
||||
"lastBattle": "Last battle",
|
||||
"premiumDays": "Premium account days",
|
||||
"saveAccount": "Save account details",
|
||||
"apply": "Save changes",
|
||||
"saved": "Changes saved.",
|
||||
"noBattles": "The save has no recorded battles.",
|
||||
|
||||
@@ -354,6 +354,7 @@
|
||||
"battles": "已记录对局",
|
||||
"lastBattle": "上次对局",
|
||||
"premiumDays": "高级账户剩余天数",
|
||||
"saveAccount": "保存账号信息",
|
||||
"apply": "保存更改",
|
||||
"saved": "更改已保存。",
|
||||
"noBattles": "此存档没有对局记录。",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { CurrencyEdits, SaveDetails, SaveList, SaveTransfer } from '@shared/schemas/saves.ts';
|
||||
import type { AccountEdits, CurrencyEdits, SaveDetails, SaveList, SaveTransfer } from '@shared/schemas/saves.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
@@ -103,6 +103,24 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
const submitAccount = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
if (!details || !userId) return;
|
||||
const data = new FormData(event.currentTarget);
|
||||
const nick = String(data.get('nick') ?? '').trim();
|
||||
const days = String(data.get('premiumDays') ?? '').trim();
|
||||
const edits: AccountEdits = {};
|
||||
if (nick !== details.save.nick) edits.nick = nick;
|
||||
if (days !== '' && Number(days) !== details.save.premiumDays) edits.premiumDays = Number(days);
|
||||
if (Object.keys(edits).length === 0) return;
|
||||
setSaving(true);
|
||||
setMessage('');
|
||||
ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits })
|
||||
.then((updated) => { updateDetails(updated); setMessage(t('saves.saved')); })
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
const title = t(`saves.sections.${section}`);
|
||||
if (section === 'list') {
|
||||
return (
|
||||
@@ -213,7 +231,16 @@ 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>
|
||||
<Row label={t('saves.premiumDays')}>{format.format(save.premiumDays)}</Row>
|
||||
<form key={save.userId + ':' + save.nick + ':' + 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>
|
||||
<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} />
|
||||
</Row>
|
||||
<button type="submit" className="button" disabled={readOnly || saving}>{t('saves.saveAccount')}</button>
|
||||
</form>
|
||||
<Row label={t('saves.vehicles')}>{format.format(save.vehicleCount)}</Row>
|
||||
<Row label={t('saves.battles')}>{format.format(save.battleCount)}</Row>
|
||||
<form key={save.userId} onSubmit={submitEdits}>
|
||||
|
||||
@@ -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 { ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { AccountEditsSchema, 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,10 @@ export const ipcContract = {
|
||||
input: SaveRegistrationSchema,
|
||||
output: SaveListSchema,
|
||||
},
|
||||
'saves:editAccount': {
|
||||
input: SaveKeysSchema.extend({ edits: AccountEditsSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
},
|
||||
'saves:editCurrencies': {
|
||||
input: SaveKeysSchema.extend({ values: CurrencyEditsSchema }),
|
||||
output: SaveDetailsSchema,
|
||||
|
||||
@@ -4,6 +4,9 @@ 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 type AccountEdits = z.output<typeof AccountEditsSchema>;
|
||||
|
||||
export const CurrencyEditsSchema = z.object({
|
||||
silverLions: z.number().int().nonnegative().optional(),
|
||||
goldenEagles: z.number().int().min(0).max(0x7fffffff).optional(),
|
||||
|
||||
@@ -61,12 +61,12 @@ export class AccountStore {
|
||||
|
||||
register(login: string, password: string, nick: string): RegistrationResult {
|
||||
login = login.trim();
|
||||
nick = nick.trim();
|
||||
const displayName = normalizedNickname(nick);
|
||||
if (!login || /[\s\p{Cc}]/u.test(login)) return { kind: 'invalid-login' };
|
||||
if (!password) return { kind: 'invalid-password' };
|
||||
if (!nick || [...nick].length > NICK_MAX_LENGTH || /\p{Cc}/u.test(nick)) return { kind: 'invalid-nick' };
|
||||
if (displayName === undefined) return { kind: 'invalid-nick' };
|
||||
if (this.#find(login)) return { kind: 'already-registered' };
|
||||
return { kind: 'registered', account: this.#create(login, password, nick) };
|
||||
return { kind: 'registered', account: this.#create(login, password, displayName) };
|
||||
}
|
||||
|
||||
#create(login: string, password: string, nick: string): Account {
|
||||
@@ -78,6 +78,19 @@ export class AccountStore {
|
||||
return account;
|
||||
}
|
||||
|
||||
rename(userId: string, nick: string): 'updated' | 'invalid-nick' | 'not-found' {
|
||||
const displayName = normalizedNickname(nick);
|
||||
if (displayName === undefined) return 'invalid-nick';
|
||||
const prior = this.byUserId(userId);
|
||||
if (!prior) return 'not-found';
|
||||
if (prior.nick === displayName) return 'updated';
|
||||
const accounts = this.#file.accounts.map((account) => account.userId === userId ? { ...account, nick: displayName } : account);
|
||||
const file = { ...this.#file, accounts };
|
||||
writeFileAtomic(this.#path, JSON.stringify(file, null, 2));
|
||||
this.#file = file;
|
||||
return 'updated';
|
||||
}
|
||||
|
||||
remove(userId: string): boolean {
|
||||
const accounts = this.#file.accounts.filter((account) => account.userId !== userId);
|
||||
if (accounts.length === this.#file.accounts.length) return false;
|
||||
@@ -115,6 +128,11 @@ export class AccountStore {
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizedNickname(nick: string): string | undefined {
|
||||
const value = nick.trim();
|
||||
return value && [...value].length <= NICK_MAX_LENGTH && !/\p{Cc}/u.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readAccountFile(path: string): AccountFile {
|
||||
const file = JSON.parse(readFileSync(path, 'utf8')) as AccountFile;
|
||||
if (file.formatVersion !== 1) throw new Error(`${path}: unsupported account file version ${String(file.formatVersion)}`);
|
||||
|
||||
@@ -7,7 +7,7 @@ export { AccountStore, type RegistrationResult } from './accounts/account-store.
|
||||
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 { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
|
||||
export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.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';
|
||||
|
||||
@@ -45,6 +45,15 @@ export function extendPremiumAccount(profile: BlkBlock, days: number, nowFiletim
|
||||
setParam(entry, 'expiredTime', { type: 'int64', value: base + BigInt(days) * TICKS_PER_DAY });
|
||||
}
|
||||
|
||||
export function setPremiumDays(profile: BlkBlock, days: number, nowFiletime: bigint): void {
|
||||
if (!Number.isSafeInteger(days) || days < 0) throw new RangeError('Premium days must be a whole non-negative number.');
|
||||
const expires = nowFiletime + BigInt(days) * TICKS_PER_DAY;
|
||||
if (expires >= (1n << 63n)) throw new RangeError('Premium expiration exceeds the saved format.');
|
||||
const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), PREMIUM_ACCOUNT_ENTITLEMENT);
|
||||
setParam(entry, 'count', { type: 'int', value: days > 0 ? Math.max(1, intField(entry, 'count')) : 0 });
|
||||
setParam(entry, 'expiredTime', { type: 'int64', value: expires });
|
||||
}
|
||||
|
||||
/** Remaining whole days (rounded up) of Premium Account, or 0 when inactive. */
|
||||
export function remainingPremiumDays(profile: BlkBlock, nowFiletime: bigint): number {
|
||||
const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? EMPTY_BLK, PREMIUM_ACCOUNT_ENTITLEMENT);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { decodeBlk, findBlock, findParam, type BlkBlock } from '@wto/blk';
|
||||
import { AccountStore, type Account } from '../accounts/account-store.ts';
|
||||
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 { GameFiles } from '../game-data/game-files.ts';
|
||||
import { intField, stringField } from '../profile/blk-fields.ts';
|
||||
import { balanceOf, setGjnCents, setGoldenEagles, setSilverLions } from '../profile/profile-currency.ts';
|
||||
import { remainingPremiumDays } from '../profile/profile-entitlements.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 { EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||
@@ -87,15 +87,27 @@ export function readSaveDetails(dataFolder: string, userId: string) {
|
||||
return { save: summary(account, profile), battles: profile ? battleEntries(profile) : [], owned, research };
|
||||
}
|
||||
|
||||
export interface AccountEdits {
|
||||
readonly nick?: string | undefined;
|
||||
readonly premiumDays?: number | undefined;
|
||||
}
|
||||
|
||||
export function editSaveAccount(location: SaveLocation, userId: string, edits: AccountEdits): 'updated' | 'invalid-nick' | '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()));
|
||||
}
|
||||
return nick === undefined ? 'updated' : accounts.rename(userId, nick);
|
||||
}
|
||||
|
||||
export function editSaveCurrencies(location: SaveLocation, userId: string, values: CurrencyEdits): boolean {
|
||||
const accounts = new AccountStore(location.dataFolder);
|
||||
if (!accounts.byUserId(userId)) return false;
|
||||
const tuning = loadTuning(location.dataFolder, () => {});
|
||||
const gameFiles = new GameFiles(location.gameFolder);
|
||||
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
|
||||
const clans = new ClanStore(location.dataFolder, tuning.clans);
|
||||
const { profiles } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans });
|
||||
profiles.update(userId, (profile) => {
|
||||
updateProfile(location, accounts, userId, (profile) => {
|
||||
if (values.silverLions !== undefined) setSilverLions(profile, values.silverLions);
|
||||
if (values.goldenEagles !== undefined) setGoldenEagles(profile, values.goldenEagles);
|
||||
if (values.gjnCents !== undefined) setGjnCents(profile, values.gjnCents);
|
||||
@@ -103,3 +115,12 @@ export function editSaveCurrencies(location: SaveLocation, userId: string, value
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function updateProfile(location: SaveLocation, accounts: AccountStore, userId: string, change: (profile: BlkBlock) => void): void {
|
||||
const tuning = loadTuning(location.dataFolder, () => {});
|
||||
const gameFiles = new GameFiles(location.gameFolder);
|
||||
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
|
||||
const clans = new ClanStore(location.dataFolder, tuning.clans);
|
||||
const { profiles } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans });
|
||||
profiles.update(userId, change);
|
||||
}
|
||||
Reference in new issue
Block a user