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:
N0VAN0M4LY committed 2026-11-29 17:41:46 +08:00
1 parent 1d3af395c2
commit d20b7f4249
13 files changed
+127 -19

No files matched your search

+2 -1
View File
@@ -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}>
+5 -1
View File
@@ -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(),