feat(saves): add local save selection and editing

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:42:28 +08:00
1 parent 2b1da24263
commit 073a907617
18 files changed
+634 -4

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ export default defineConfig({
input: {
index: resolve('src/main/index.ts'),
'build-worker': resolve('src/main/workers/build-worker.ts'),
'save-worker': resolve('src/main/workers/save-worker.ts'),
'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'),
},
},
+9 -1
View File
@@ -13,6 +13,7 @@ import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentC
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { createSave, getSaveDetails, getSaveList, saveWriteInProgress, selectSave, setSaveCurrencies } 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/. */
@@ -96,16 +97,23 @@ export function registerIpcHandlers(): void {
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintain', async (request) => {
if (saveWriteInProgress()) throw new AppError('maintenance_busy');
const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress));
broadcast('event:copies-changed', updated);
return updated;
});
handle('copies:cancelMaintenance', () => cancelMaintenance());
handle('saves:list', ({ copyId }) => getSaveList(copyId));
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId));
handle('saves:create', (request) => createSave(request));
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
if (maintenanceInProgress() || saveWriteInProgress()) throw new AppError('maintenance_busy');
return startLaunch((state) => broadcast('event:launch-state', state));
});
handle('launch:stop', async () => { await stopLaunch(); });
@@ -0,0 +1,105 @@
import { join } from 'node:path';
import { utilityProcess } from 'electron';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { CurrencyEdits, SaveDetails, SaveList, SaveRegistration } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { forwardProcessOutput } from '../launch/process-output.ts';
let writing = false;
export function saveWriteInProgress(): boolean {
return writing;
}
async function requireCopy(id: string): Promise<InstallRecord> {
const copy = (await listCopies()).copies.find((record) => record.id === id);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
function location(copy: InstallRecord) {
return { gameFolder: copy.copyPath, dataFolder: copy.dataPath };
}
export async function getSaveList(copyId: string): Promise<SaveList> {
const copy = await requireCopy(copyId);
const saves = await run({ operation: 'list', ...location(copy) }) as SaveList['saves'];
const current = saves.find(({ userId }) => userId === copy.currentSaveId)?.userId ?? saves[0]?.userId ?? null;
return { saves, current };
}
export async function getSaveDetails(copyId: string, userId: string): Promise<SaveDetails> {
const copy = await requireCopy(copyId);
return await run({ operation: 'details', ...location(copy), userId }) as SaveDetails;
}
export async function selectSave(copyId: string, userId: string): Promise<SaveList> {
await getSaveDetails(copyId, userId);
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
return getSaveList(copyId);
}
export async function createSave({ copyId, login, password, nick }: SaveRegistration): Promise<SaveList> {
return write(async () => {
const copy = await requireCopy(copyId);
const { userId } = await run({ operation: 'create', ...location(copy), login, password, nick }) as { userId: string };
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
return getSaveList(copyId);
});
}
export async function setSaveCurrencies(copyId: string, userId: string, values: CurrencyEdits): Promise<SaveDetails> {
return write(async () => {
const copy = await requireCopy(copyId);
await run({ operation: 'edit', ...location(copy), userId, values });
return getSaveDetails(copyId, userId);
});
}
async function write<T>(operation: () => Promise<T>): Promise<T> {
if (writing || launchInProgress() || maintenanceInProgress()) throw new AppError('save_read_only');
writing = true;
try {
if (await gameProcessRunning(AbortSignal.timeout(4000)) || await labServerRunning()) {
throw new AppError('save_read_only');
}
return await operation();
} finally {
writing = false;
}
}
async function labServerRunning(): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab) return false;
try {
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) });
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
} catch {
return false;
}
}
async function run(task: SaveTask): Promise<SaveResult> {
const child = utilityProcess.fork(join(import.meta.dirname, 'save-worker.js'), [], { serviceName: 'WTOffline save management', stdio: 'pipe' });
forwardProcessOutput(child.stdout, 'saves', 'info');
forwardProcessOutput(child.stderr, 'saves', 'error');
try {
return await new Promise<SaveResult>((resolve, reject) => {
child.once('exit', () => reject(new AppError('save_operation_failed')));
child.once('message', (reply: SaveReply) => {
if (reply.ok) resolve(reply.result);
else reject(new AppError(reply.error));
});
child.postMessage(task);
});
} finally {
child.removeAllListeners('exit');
child.kill();
}
}
@@ -0,0 +1,16 @@
import type { AppErrorCode } from '@shared/errors.ts';
import type { CurrencyEdits, SaveDetails, SaveList } from '@shared/schemas/saves.ts';
interface Location {
readonly gameFolder: string;
readonly dataFolder: string;
}
export type SaveTask = Location & (
| { readonly operation: 'list' }
| { readonly operation: 'details'; readonly userId: string }
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
);
export type SaveResult = SaveList['saves'] | SaveDetails | { userId: string } | null;
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
@@ -0,0 +1,38 @@
import type { MessageEvent } from 'electron';
import { AccountStore, editSaveCurrencies, listSaveSummaries, readSaveDetails } 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) };
case 'details': {
const result = readSaveDetails(task.dataFolder, task.userId);
return result ? { ok: true, result } : { 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' };
case 'create': {
const result = new AccountStore(task.dataFolder).register(task.login, task.password, task.nick);
switch (result.kind) {
case 'registered': return { ok: true, result: { userId: result.account.userId } };
case 'invalid-login': return { ok: false, error: 'save_login_invalid' };
case 'invalid-password': return { ok: false, error: 'save_password_invalid' };
case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' };
case 'already-registered': return { ok: false, error: 'save_login_exists' };
}
}
}
}
process.parentPort.once('message', (event: MessageEvent) => {
let reply: SaveReply;
try {
reply = execute(event.data as SaveTask);
} catch (error) {
console.error('[saves] the save operation failed:', error);
reply = { ok: false, error: 'save_operation_failed' };
}
process.parentPort.postMessage(reply);
});
+10 -1
View File
@@ -20,6 +20,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
import { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx';
import { GeneralSettings } from './pages/settings/GeneralSettings.tsx';
@@ -28,7 +29,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SETTINGS_SECTIONS, START_ROUTE, type Destination, type Route } from './shell/navigation.ts';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -129,6 +130,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
bar: home,
};
}
case 'saves':
return {
side: <SubNav sections={SAVE_SECTIONS} active={route.saves} label={(section) => t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />,
main: record
? <SavesPage key={record.id} copy={record} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
@@ -5,6 +5,7 @@
},
"nav": {
"home": "Home",
"saves": "Saves",
"copies": "Copies",
"settings": "Settings",
"about": "About"
@@ -251,6 +252,40 @@
"N": "Settings, controls and mods",
"O": "Multiplayer social features"
},
"saves": {
"sections": {
"list": "All saves",
"overview": "Overview",
"battles": "Battle history",
"vehicles": "Vehicles and research"
},
"create": "Create save",
"login": "Login",
"nick": "Nickname",
"password": "Password",
"confirmPassword": "Confirm password",
"passwordMismatch": "The passwords do not match.",
"readOnly": "The local server or game is running. Saves are read-only.",
"noCopy": "Select a game copy to manage its saves.",
"empty": "There are no local saves for this copy.",
"loading": "Loading save",
"silverLions": "Silver Lions",
"goldenEagles": "Golden Eagles",
"gjnCents": "GJN",
"freeRp": "Free research points",
"vehicles": "Vehicles",
"battles": "Recorded battles",
"lastBattle": "Last battle",
"premiumDays": "Premium account days",
"apply": "Save changes",
"saved": "Changes saved.",
"noBattles": "The save has no recorded battles.",
"win": "Victory",
"loss": "Defeat",
"battleRewards": "{{sl}} Silver Lions · {{rp}} research points",
"owned": "Owned vehicles",
"research": "Research progress"
},
"settings": {
"sections": {
"general": "General",
@@ -363,6 +398,13 @@
"internal_error": "An internal launcher error occurred.",
"logs_folder_open_failed": "The launcher log folder could not be opened.",
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
"save_not_found": "The selected save could not be found.",
"save_read_only": "Saves are read-only while the game or local server is running.",
"save_operation_failed": "The save operation failed. See the launcher log.",
"save_login_invalid": "Enter a login without spaces.",
"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.",
"copy_not_found": "The selected copy is no longer available.",
"copies_write_failed": "The copy registry could not be saved.",
"copy_location_in_use": "The copy or data location overlaps an existing copy.",
@@ -5,6 +5,7 @@
},
"nav": {
"home": "首页",
"saves": "存档",
"copies": "副本",
"settings": "设置",
"about": "关于"
@@ -251,6 +252,40 @@
"N": "设置、操控与模组",
"O": "多人社交"
},
"saves": {
"sections": {
"list": "全部存档",
"overview": "概览",
"battles": "战绩",
"vehicles": "载具与研发"
},
"create": "新建存档",
"login": "登录账号",
"nick": "昵称",
"password": "密码",
"confirmPassword": "确认密码",
"passwordMismatch": "两次输入的密码不一致。",
"readOnly": "游戏或本地服务器正在运行,存档为只读。",
"noCopy": "选择游戏副本后即可管理该副本的存档。",
"empty": "此副本没有本地存档。",
"loading": "正在读取存档",
"silverLions": "银狮",
"goldenEagles": "金鹰",
"gjnCents": "GJN",
"freeRp": "通用研发点",
"vehicles": "载具",
"battles": "已记录对局",
"lastBattle": "上次对局",
"premiumDays": "高级账户剩余天数",
"apply": "保存更改",
"saved": "更改已保存。",
"noBattles": "此存档没有对局记录。",
"win": "胜利",
"loss": "失败",
"battleRewards": "{{sl}} 银狮 · {{rp}} 研发点",
"owned": "已拥有载具",
"research": "研发进度"
},
"settings": {
"sections": {
"general": "常规",
@@ -363,6 +398,13 @@
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"save_not_found": "找不到所选存档。",
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
"save_operation_failed": "存档操作失败。请查看启动器日志。",
"save_login_invalid": "登录账号不能包含空格。",
"save_login_exists": "该登录账号已注册。",
"save_password_invalid": "请输入密码。",
"save_nick_invalid": "请输入最多 16 个字符的昵称。",
"copy_not_found": "所选副本已不可用。",
"copies_write_failed": "无法保存副本记录。",
"copy_location_in_use": "副本位置或数据目录与已有副本重叠。",
@@ -0,0 +1,175 @@
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 } from '@shared/schemas/saves.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { SaveSection } from '../../shell/navigation.ts';
interface SavesPageProps {
readonly copy: InstallRecord;
readonly section: SaveSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
const CURRENCIES = ['silverLions', 'goldenEagles', 'gjnCents', 'freeRp'] as const;
export function SavesPage({ copy, section, readOnly, onError }: SavesPageProps) {
const { t, i18n } = useTranslation();
const [list, setList] = useState<SaveList | null>(null);
const [details, setDetails] = useState<SaveDetails | null>(null);
const [creating, setCreating] = useState(false);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState('');
const userId = list?.current ?? null;
useEffect(() => {
let mounted = true;
ipcInvoke('saves:list', { copyId: copy.id }).then((value) => {
if (mounted) setList(value);
}).catch(onError);
return () => { mounted = false; };
}, [copy.id, onError]);
useEffect(() => {
if (section === 'list' || !userId) return;
let mounted = true;
setDetails(null);
ipcInvoke('saves:details', { copyId: copy.id, userId }).then((value) => {
if (mounted) setDetails(value);
}).catch(onError);
return () => { mounted = false; };
}, [copy.id, userId, section, onError]);
const date = (time: number | null): string => time ? new Date(time * 1000).toLocaleString(i18n.language) : '—';
const format = new Intl.NumberFormat(i18n.language);
const submitNew = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const password = String(data.get('password') ?? '');
if (password !== data.get('confirm')) {
setMessage(t('saves.passwordMismatch'));
return;
}
setSaving(true);
setMessage('');
ipcInvoke('saves:create', { copyId: copy.id, login: String(data.get('login') ?? ''), password, nick: String(data.get('nick') ?? '') })
.then((next) => { setList(next); setCreating(false); })
.catch(onError)
.finally(() => setSaving(false));
};
const submitEdits = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
if (!userId) return;
const data = new FormData(event.currentTarget);
const values: CurrencyEdits = {};
for (const name of CURRENCIES) {
const value = String(data.get(name) ?? '').trim();
if (value) values[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value);
}
if (Object.keys(values).length === 0) return;
setSaving(true);
setMessage('');
ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values })
.then((updated) => {
setDetails(updated);
setList((current) => current && { ...current, saves: current.saves.map((save) => save.userId === userId ? updated.save : save) });
setMessage(t('saves.saved'));
})
.catch(onError)
.finally(() => setSaving(false));
};
const title = t(`saves.sections.${section}`);
if (section === 'list') {
return (
<Sheet title={title} aside={copy.name}>
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
<button type="button" className="button button-primary" disabled={readOnly || creating} onClick={() => {
setMessage('');
setCreating(true);
}}>{t('saves.create')}</button>
{creating && (
<form className="maintenance-confirm" onSubmit={submitNew}>
<Row label={t('saves.login')}><input className="input" aria-label={t('saves.login')} autoComplete="username" name="login" required /></Row>
<Row label={t('saves.nick')}><input className="input" aria-label={t('saves.nick')} name="nick" required /></Row>
<Row label={t('saves.password')}><input className="input" aria-label={t('saves.password')} type="password" autoComplete="new-password" name="password" required /></Row>
<Row label={t('saves.confirmPassword')}><input className="input" aria-label={t('saves.confirmPassword')} type="password" autoComplete="new-password" name="confirm" required /></Row>
{message && <p className="error-text" role="alert">{message}</p>}
<div className="copy-list-actions">
<button type="button" className="button" disabled={saving} onClick={() => setCreating(false)}>{t('wizard.cancel')}</button>
<button type="submit" className="button button-primary" disabled={saving || readOnly}>{t('saves.create')}</button>
</div>
</form>
)}
{list?.saves.length === 0 && <p className="lead">{t('saves.empty')}</p>}
<div className="copy-list saves-list">
{list?.saves.map((save) => (
<article key={save.userId} className={save.userId === list.current ? 'copy-list-card copy-list-current' : 'copy-list-card'}>
<div className="copy-list-heading">
<strong>{save.nick}</strong>
{save.userId === list.current && <span className="ok">{t('copies.list.current')}</span>}
</div>
<dl className="kv">
<dt>{t('saves.login')}</dt><dd>{save.login}</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>
<dt>{t('saves.lastBattle')}</dt><dd>{date(save.lastBattle)}</dd>
</dl>
{save.userId !== list.current && (
<button type="button" className="button" onClick={() => {
ipcInvoke('saves:setCurrent', { copyId: copy.id, userId: save.userId }).then(setList).catch(onError);
}}>{t('copies.list.select')}</button>
)}
</article>
))}
</div>
</Sheet>
);
}
if (!details) return <Sheet title={title} aside={copy.name}><p className="lead">{t(userId ? 'saves.loading' : 'saves.empty')}</p></Sheet>;
const { save } = details;
return (
<Sheet title={title} aside={save.nick}>
{section === 'overview' && (
<>
{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>
<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}>
{CURRENCIES.map((name) => (
<Row key={name} label={t(`saves.${name}`)}>
<span>{save.currencies ? format.format(name === 'gjnCents' ? save.currencies[name] / 100 : save.currencies[name]) : '—'}</span>
<input className="input" type="number" step={name === 'gjnCents' ? '0.01' : '1'} min="0" name={name}
aria-label={t(`saves.${name}`)} disabled={readOnly || saving} />
</Row>
))}
<button type="submit" className="button button-primary" disabled={readOnly || saving}>{t('saves.apply')}</button>
{message && <p className="small" role="status">{message}</p>}
</form>
</>
)}
{section === 'battles' && (
details.battles.length === 0 ? <p className="lead">{t('saves.noBattles')}</p> : details.battles.map((battle) => (
<Row key={battle.id} label={battle.mission || battle.mode} hint={date(battle.time)}>
<span>{battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')}</span>
<span>{t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })}</span>
<span>{battle.vehicles.join(', ')}</span>
</Row>
))
)}
{section === 'vehicles' && (
<>
<Row label={t('saves.owned')}>{details.owned.length ? details.owned.join(', ') : '—'}</Row>
<Row label={t('saves.research')}>{details.research.length ? details.research.map(({ name, points }) => `${name} · ${format.format(points)}`).join(', ') : '—'}</Row>
</>
)}
</Sheet>
);
}
@@ -3,9 +3,12 @@
* Pages for later features (saves, tuning) join this list when they are built.
*/
export const PAGES = ['home', 'copies', 'settings', 'about'] as const;
export const PAGES = ['home', 'saves', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -15,19 +18,23 @@ export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];
export interface Route {
readonly page: PageId;
readonly copies: CopySection;
readonly saves: SaveSection;
readonly settings: SettingsSection;
}
export const START_ROUTE: Route = { page: 'home', copies: 'list', settings: 'general' };
export const START_ROUTE: Route = { page: 'home', saves: 'list', copies: 'list', settings: 'general' };
/** Where a link points: a page, and for pages with sections, which one. */
export type Destination =
| { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection };
export function navigate(route: Route, to: Destination): Route {
switch (to.page) {
case 'saves':
return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings':
@@ -303,6 +303,10 @@
margin-top: 10px;
}
.saves-list {
margin-top: 12px;
}
/* ===== About ===== */
.about-head {
display: flex;
+7
View File
@@ -17,6 +17,13 @@ export const APP_ERROR_CODES = [
'logs_folder_open_failed',
'diagnostics_export_failed',
'copy_not_found',
'save_not_found',
'save_read_only',
'save_operation_failed',
'save_login_invalid',
'save_login_exists',
'save_password_invalid',
'save_nick_invalid',
'copies_write_failed',
'maintenance_busy',
'maintenance_location',
+2
View File
@@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [
'install:',
/** Listing and managing installed copies. */
'copies:',
/** Local account and save management. */
'saves:',
/** Starting and stopping the active copy. */
'launch:',
/** The launcher's own settings. */
+21
View File
@@ -15,6 +15,7 @@ import {
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { CurrencyEditsSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema } from '../schemas/saves.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
/**
@@ -127,6 +128,26 @@ export const ipcContract = {
input: z.void(),
output: z.void(),
},
'saves:list': {
input: z.object({ copyId: CopyIdSchema }),
output: SaveListSchema,
},
'saves:details': {
input: SaveKeysSchema,
output: SaveDetailsSchema,
},
'saves:setCurrent': {
input: SaveKeysSchema,
output: SaveListSchema,
},
'saves:create': {
input: SaveRegistrationSchema,
output: SaveListSchema,
},
'saves:editCurrencies': {
input: SaveKeysSchema.extend({ values: CurrencyEditsSchema }),
output: SaveDetailsSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
@@ -134,6 +134,7 @@ export const InstallRecordSchema = z.object({
unavailablePatches: z.array(UnavailablePatchSchema),
installedAt: z.string(),
lastCheckedAt: z.string().optional(),
currentSaveId: z.string().regex(/^\d+$/).optional(),
/** Relative paths read from the installation source during the last copy or update. */
sourceFiles: z.array(z.string().min(1)).optional(),
});
+46
View File
@@ -0,0 +1,46 @@
import { z } from 'zod';
import { CopyIdSchema } from './install.ts';
export const LocalUserIdSchema = z.string().regex(/^\d+$/);
export const SaveKeysSchema = z.object({ copyId: CopyIdSchema, userId: LocalUserIdSchema });
export const CurrencyEditsSchema = z.object({
silverLions: z.number().int().nonnegative().optional(),
goldenEagles: z.number().int().min(0).max(0x7fffffff).optional(),
gjnCents: z.number().int().nonnegative().optional(),
freeRp: z.number().int().nonnegative().optional(),
});
const SaveSummarySchema = z.object({
userId: LocalUserIdSchema,
login: z.string(),
nick: z.string(),
created: z.string(),
currencies: z.object({
silverLions: z.number(),
goldenEagles: z.number(),
gjnCents: z.number(),
freeRp: z.number(),
}).nullable(),
vehicleCount: z.number().int().nonnegative(),
battleCount: z.number().int().nonnegative(),
lastBattle: z.number().nullable(),
premiumDays: z.number(),
});
export const SaveListSchema = z.object({ saves: z.array(SaveSummarySchema), current: LocalUserIdSchema.nullable() });
export const SaveDetailsSchema = z.object({
save: SaveSummarySchema,
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(),
})),
owned: z.array(z.string()),
research: z.array(z.object({ name: z.string(), points: z.number() })),
});
export const SaveRegistrationSchema = z.object({
copyId: CopyIdSchema, login: z.string(), password: z.string(), nick: z.string(),
});
export type SaveList = z.output<typeof SaveListSchema>;
export type SaveDetails = z.output<typeof SaveDetailsSchema>;
export type CurrencyEdits = z.output<typeof CurrencyEditsSchema>;
export type SaveRegistration = z.output<typeof SaveRegistrationSchema>;
+1
View File
@@ -6,4 +6,5 @@ export { LOOPBACK, startServer, type ServerOptions, type RunningServer } from '.
export { AccountStore, type RegistrationResult } from './accounts/account-store.ts';
export { REGISTRATION_PATH } from './accounts/registration-service.ts';
export { HEALTH_PATH } from './transport/http-listener.ts';
export { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
+105
View File
@@ -0,0 +1,105 @@
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 { 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 { 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';
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';
export interface SaveLocation {
readonly gameFolder: string;
readonly dataFolder: string;
}
export interface CurrencyEdits {
readonly silverLions?: number | undefined;
readonly goldenEagles?: number | undefined;
readonly gjnCents?: number | undefined;
readonly freeRp?: number | undefined;
}
function summary(account: Account, profile: BlkBlock | undefined) {
const battles = profile ? battleEntries(profile) : [];
const { userId, login, nick, created } = account;
return {
userId, login, nick, created,
currencies: profile ? { ...balanceOf(profile), freeRp: freeResearchPoints(profile) } : null,
vehicleCount: profile ? ownedVehicles(profile).size : 0,
battleCount: battles.length,
lastBattle: battles[0]?.time ?? null,
premiumDays: profile ? remainingPremiumDays(profile, serverTimeNow()) : 0,
};
}
function snapshot(dataFolder: string, userId: string): BlkBlock | undefined {
if (!/^\d+$/.test(userId)) throw new Error('Invalid local account id.');
try {
return decodeBlk(readFileSync(join(dataFolder, 'saves', userId, 'profile.blk')));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
throw error;
}
}
function battleEntries(profile: BlkBlock) {
return (findBlock(profile, 'userlogs')?.blocks ?? [])
.filter((entry) => intField(entry, 'type') === EULT_SESSION_RESULT)
.map((entry) => {
const body = findBlock(entry, 'body');
const win = body && findParam(body, 'win')?.value;
return {
id: entry.name,
time: intField(entry, 'time'),
won: win?.type === 'bool' ? win.value : null,
mission: stringField(body, 'locName') || stringField(body, 'mission'),
mode: stringField(body, 'eventId'),
vehicles: (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [],
silverLions: intField(body, 'wpEarned'),
researchPoints: intField(body, 'xpEarned'),
};
})
.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, snapshot(dataFolder, account.userId)));
}
export function readSaveDetails(dataFolder: string, userId: string) {
const account = new AccountStore(dataFolder).byUserId(userId);
if (!account) return null;
const profile = snapshot(dataFolder, userId);
const owned = profile ? [...ownedVehicles(profile)].sort() : [];
const research = profile
? (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 };
}
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) => {
if (values.silverLions !== undefined) setSilverLions(profile, values.silverLions);
if (values.goldenEagles !== undefined) setGoldenEagles(profile, values.goldenEagles);
if (values.gjnCents !== undefined) setGjnCents(profile, values.gjnCents);
if (values.freeRp !== undefined) setFreeResearchPoints(profile, values.freeRp);
});
return true;
}