From 073a907617893740747f37893d3ee37c5f7f3a2c Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:42:28 +0800 Subject: [PATCH] feat(saves): add local save selection and editing --- apps/launcher/electron.vite.config.ts | 1 + apps/launcher/src/main/ipc/handlers.ts | 10 +- .../src/main/services/saves/manage-saves.ts | 105 +++++++++++ .../src/main/workers/save-protocol.ts | 16 ++ apps/launcher/src/main/workers/save-worker.ts | 38 ++++ apps/launcher/src/renderer/src/App.tsx | 11 +- .../src/renderer/src/i18n/locales/en.json | 42 +++++ .../src/renderer/src/i18n/locales/zh-CN.json | 42 +++++ .../renderer/src/pages/saves/SavesPage.tsx | 175 ++++++++++++++++++ .../src/renderer/src/shell/navigation.ts | 11 +- .../src/renderer/src/styles/pages.css | 4 + apps/launcher/src/shared/errors.ts | 7 + apps/launcher/src/shared/ipc/channels.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 21 +++ apps/launcher/src/shared/schemas/install.ts | 1 + apps/launcher/src/shared/schemas/saves.ts | 46 +++++ apps/server/src/index.ts | 1 + apps/server/src/saves/save-editor.ts | 105 +++++++++++ 18 files changed, 634 insertions(+), 4 deletions(-) create mode 100644 apps/launcher/src/main/services/saves/manage-saves.ts create mode 100644 apps/launcher/src/main/workers/save-protocol.ts create mode 100644 apps/launcher/src/main/workers/save-worker.ts create mode 100644 apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx create mode 100644 apps/launcher/src/shared/schemas/saves.ts create mode 100644 apps/server/src/saves/save-editor.ts diff --git a/apps/launcher/electron.vite.config.ts b/apps/launcher/electron.vite.config.ts index 1ea6046..6ab858d 100644 --- a/apps/launcher/electron.vite.config.ts +++ b/apps/launcher/electron.vite.config.ts @@ -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'), }, }, diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 2139e2d..b3b4d7b 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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(); }); diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts new file mode 100644 index 0000000..859c136 --- /dev/null +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -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 { + 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 { + 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 { + const copy = await requireCopy(copyId); + return await run({ operation: 'details', ...location(copy), userId }) as SaveDetails; +} + +export async function selectSave(copyId: string, userId: string): Promise { + await getSaveDetails(copyId, userId); + await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId })); + return getSaveList(copyId); +} + +export async function createSave({ copyId, login, password, nick }: SaveRegistration): Promise { + 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 { + return write(async () => { + const copy = await requireCopy(copyId); + await run({ operation: 'edit', ...location(copy), userId, values }); + return getSaveDetails(copyId, userId); + }); +} + +async function write(operation: () => Promise): Promise { + 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 { + 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 { + 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((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(); + } +} diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts new file mode 100644 index 0000000..63db988 --- /dev/null +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -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 }; diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts new file mode 100644 index 0000000..46a3119 --- /dev/null +++ b/apps/launcher/src/main/workers/save-worker.ts @@ -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); +}); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 23f23bf..e95f69a 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -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: t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />, + main: record + ? + :

{t('saves.noCopy')}

, + bar: home, + }; case 'copies': { const side = t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; if (route.copies === 'list') { diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 9e081a8..b443b6e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -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.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 19b89d5..9ab6870 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -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": "副本位置或数据目录与已有副本重叠。", diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx new file mode 100644 index 0000000..c4f86e0 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -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(null); + const [details, setDetails] = useState(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): 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): 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 ( + + {readOnly &&

{t('saves.readOnly')}

} + + {creating && ( +
+ + + + + {message &&

{message}

} +
+ + +
+
+ )} + {list?.saves.length === 0 &&

{t('saves.empty')}

} +
+ {list?.saves.map((save) => ( +
+
+ {save.nick} + {save.userId === list.current && {t('copies.list.current')}} +
+
+
{t('saves.login')}
{save.login}
+
{t('saves.silverLions')}
{save.currencies ? format.format(save.currencies.silverLions) : '—'}
+
{t('saves.vehicles')}
{format.format(save.vehicleCount)}
+
{t('saves.battles')}
{format.format(save.battleCount)}
+
{t('saves.lastBattle')}
{date(save.lastBattle)}
+
+ {save.userId !== list.current && ( + + )} +
+ ))} +
+
+ ); + } + + if (!details) return

{t(userId ? 'saves.loading' : 'saves.empty')}

; + const { save } = details; + return ( + + {section === 'overview' && ( + <> + {readOnly &&

{t('saves.readOnly')}

} + {save.login} + {format.format(save.premiumDays)} + {format.format(save.vehicleCount)} + {format.format(save.battleCount)} +
+ {CURRENCIES.map((name) => ( + + {save.currencies ? format.format(name === 'gjnCents' ? save.currencies[name] / 100 : save.currencies[name]) : '—'} + + + ))} + + {message &&

{message}

} +
+ + )} + {section === 'battles' && ( + details.battles.length === 0 ?

{t('saves.noBattles')}

: details.battles.map((battle) => ( + + {battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')} + {t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })} + {battle.vehicles.join(', ')} + + )) + )} + {section === 'vehicles' && ( + <> + {details.owned.length ? details.owned.join(', ') : '—'} + {details.research.length ? details.research.map(({ name, points }) => `${name} · ${format.format(points)}`).join(', ') : '—'} + + )} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index f6b11f8..27043e2 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -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': diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index f37315c..3ebad07 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -303,6 +303,10 @@ margin-top: 10px; } +.saves-list { + margin-top: 12px; +} + /* ===== About ===== */ .about-head { display: flex; diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 6852d1d..0f9a1a5 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -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', diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index 434cf95..1b82e4f 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -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. */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 4eb0c16..96e2ede 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -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, diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index 9001df7..04bd212 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -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(), }); diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts new file mode 100644 index 0000000..606f61f --- /dev/null +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -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; +export type SaveDetails = z.output; +export type CurrencyEdits = z.output; +export type SaveRegistration = z.output; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 86a903f..52bd867 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -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'; diff --git a/apps/server/src/saves/save-editor.ts b/apps/server/src/saves/save-editor.ts new file mode 100644 index 0000000..0ab26c7 --- /dev/null +++ b/apps/server/src/saves/save-editor.ts @@ -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; +}