feat(saves): add one-click online data discovery and cache cleanup

Add user-initiated read-only discovery of local online client settings, copy selected files into the offline copy's staging directory before preview/import, clear the offline client's local cache for the imported account, and refresh save summaries after import.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 16:51:52 +08:00
1 parent f39d7b05c1
commit db84971823
8 files changed
+261 -25

No files matched your search

+3 -1
View File
@@ -17,7 +17,7 @@ import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -136,6 +136,8 @@ export function registerIpcHandlers(): void {
handle('saves:takeBackup', ({ copyId, userId }) => takeSaveBackup(copyId, userId));
handle('saves:restoreBackup', ({ copyId, userId, name }) => restoreSaveBackup(copyId, userId, name));
handle('saves:discoverOnlineData', () => discoverOnlineData());
handle('saves:copyOnlineData', ({ copyId, userId, accountId }) => copyOnlineData(copyId, userId, accountId));
handle('saves:pickOfficialBackups', (_input, sender) => pickOfficialBackups(BrowserWindow.fromWebContents(sender)));
handle('saves:previewOfficial', ({ copyId, userId, paths, includeUsedVehicles }) =>
previewSelectedBackups(copyId, userId, paths, includeUsedVehicles));
@@ -1,9 +1,10 @@
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
@@ -182,6 +183,92 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
});
}
const ONLINE_DATA_FILES = ['global.blk', 'machine.blk', 'storage.blk'] as const;
const ONLINE_DATA_MAX_BYTES = 32 * 1024 * 1024;
function onlineSavesRoot(): string {
return join(app.getPath('documents'), 'My Games', 'WarThunder', 'Saves');
}
async function offlineClientCacheFolder(userId: string): Promise<string | undefined> {
if (!/^\d+$/.test(userId)) return undefined;
const root = await canonicalCopyPath(join(app.getPath('documents'), 'My Games', 'WTOffline', 'Saves'));
const target = await canonicalCopyPath(join(root, userId, 'production'));
return copyPathContains(root, target) ? target : undefined;
}
/** Read-only discovery of local online client settings under Documents/My Games/WarThunder/Saves. */
export async function discoverOnlineData(): Promise<OnlineDataSource[]> {
const root = onlineSavesRoot();
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
const found: Array<OnlineDataSource & { readonly mtimeMs: number }> = [];
for (const entry of entries) {
if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
const production = join(root, entry.name, 'production');
const files: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
let latestMtime = 0;
for (const fileName of ONLINE_DATA_FILES) {
const stats = await lstat(join(production, fileName)).catch(() => null);
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
files.push(fileName);
if (stats.mtimeMs > latestMtime) latestMtime = stats.mtimeMs;
}
if (files.length > 0) {
found.push({
accountId: entry.name,
folder: production,
files,
updatedAt: new Date(latestMtime).toISOString(),
mtimeMs: latestMtime,
});
}
}
return found
.sort((a, b) => b.mtimeMs - a.mtimeMs || a.accountId.localeCompare(b.accountId))
.map(({ mtimeMs: _ignored, ...item }) => item);
}
/**
* Copy the player's selected online settings files into the offline copy's own staging folder
* without writing to or modifying the online directory.
*/
export async function copyOnlineData(copyId: string, userId: string, accountId: string): Promise<string[]> {
if (!/^\d+$/.test(accountId) || !/^\d+$/.test(userId)) throw new AppError('save_official_invalid');
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const onlineRoot = await canonicalCopyPath(onlineSavesRoot());
const sourceDir = await canonicalCopyPath(join(onlineRoot, accountId, 'production'));
if (!copyPathContains(onlineRoot, sourceDir)) throw new AppError('save_official_location');
const dataRoot = await canonicalCopyPath(copy.dataPath);
const stageDir = await canonicalCopyPath(join(dataRoot, 'imported-online-data', userId, accountId));
if (!copyPathContains(dataRoot, stageDir)) throw new AppError('save_operation_failed');
const existingFiles: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
for (const fileName of ONLINE_DATA_FILES) {
const sourcePath = join(sourceDir, fileName);
const stats = await lstat(sourcePath).catch(() => null);
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
existingFiles.push(fileName);
}
if (existingFiles.length === 0) throw new AppError('save_official_invalid');
await rm(stageDir, { recursive: true, force: true });
await mkdir(stageDir, { recursive: true });
const copied: string[] = [];
for (const fileName of existingFiles) {
const targetPath = join(stageDir, fileName);
await copyFile(join(sourceDir, fileName), targetPath);
copied.push(targetPath);
}
return copied;
}
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
@@ -204,10 +291,18 @@ export async function importSelectedBackups(
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
const cacheFolder = await offlineClientCacheFolder(userId);
const before = await captureSave(copy, userId);
await saveBackup(copy, userId, 'import');
try {
return await run({ operation: 'importOfficial', ...location(copy), userId, paths: selected, options }) as OfficialPreview;
return await run({
operation: 'importOfficial',
...location(copy),
userId,
paths: selected,
options,
...(cacheFolder ? { offlineClientCacheFolder: cacheFolder } : {}),
}) as OfficialPreview;
} catch (error) {
await restoreDirectory(copy, userId, before);
throw error;
@@ -14,7 +14,13 @@ export type SaveTask = Location & (
| { 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 }
| {
readonly operation: 'importOfficial';
readonly paths: readonly string[];
readonly userId: string;
readonly options: OfficialImportOptions;
readonly offlineClientCacheFolder?: string;
}
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
| { readonly operation: 'remove'; readonly userId: string }
@@ -28,7 +28,7 @@ function execute(task: SaveTask): SaveReply {
case 'previewOfficial':
return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) };
case 'importOfficial':
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options) };
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options, task.offlineClientCacheFolder) };
case 'readResearch': {
const result = readSaveResearch(task, task.userId, task.branch);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { OfficialImportOptions, OfficialPreview } from '@shared/schemas/saves.ts';
import type { OfficialImportOptions, OfficialPreview, OnlineDataSource } from '@shared/schemas/saves.ts';
import { Row } from '../../components/Row.tsx';
import { ipcInvoke } from '../../ipc.ts';
@@ -13,81 +13,189 @@ interface Props {
readonly userId: string;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
readonly onImported?: () => void;
}
export function OfficialSaveImport({ copyId, userId, readOnly, onError }: Props) {
const { t } = useTranslation();
export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImported }: Props) {
const { t, i18n } = useTranslation();
const [sources, setSources] = useState<OnlineDataSource[] | null>(null);
const [selectedAccount, setSelectedAccount] = useState<string>('');
const [paths, setPaths] = useState<string[]>([]);
const [options, setOptions] = useState(DEFAULTS);
const [preview, setPreview] = useState<OfficialPreview | null>(null);
const [busy, setBusy] = useState(false);
const [imported, setImported] = useState(false);
const request = { copyId, userId, paths };
const stageAndPreview = async (accountId: string, includeUsed: boolean): Promise<string[]> => {
const copied = await ipcInvoke('saves:copyOnlineData', { copyId, userId, accountId });
setSelectedAccount(accountId);
setPaths(copied);
setImported(false);
const nextPreview = await ipcInvoke('saves:previewOfficial', { copyId, userId, paths: copied, includeUsedVehicles: includeUsed });
setPreview(nextPreview);
return copied;
};
const discover = (importImmediately: boolean): void => {
setBusy(true);
setImported(false);
ipcInvoke('saves:discoverOnlineData')
.then(async (found) => {
setSources(found);
if (found.length === 0) {
setSelectedAccount('');
setPaths([]);
setPreview(null);
return;
}
const first = found[0]!;
const copied = await stageAndPreview(first.accountId, options.includeUsedVehicles);
if (importImmediately && found.length === 1 && !readOnly && (options.importSettings || options.unlockVehicles)) {
const result = await ipcInvoke('saves:importOfficial', { copyId, userId, paths: copied, options });
setPreview(result);
setImported(true);
onImported?.();
}
})
.catch(onError)
.finally(() => setBusy(false));
};
const selectOnlineAccount = (accountId: string): void => {
if (!accountId) return;
setBusy(true);
setImported(false);
stageAndPreview(accountId, options.includeUsedVehicles)
.catch(onError)
.finally(() => setBusy(false));
};
const choose = (): void => {
ipcInvoke('saves:pickOfficialBackups').then((selection) => {
if (selection.length === 0) return;
setSelectedAccount('');
setPaths(selection);
setPreview(null);
setImported(false);
}).catch(onError);
};
const load = (): void => {
const load = (targetPaths = paths, includeUsed = options.includeUsedVehicles): void => {
if (targetPaths.length === 0) return;
setBusy(true);
setImported(false);
ipcInvoke('saves:previewOfficial', { ...request, includeUsedVehicles: options.includeUsedVehicles })
.then(setPreview).catch(onError).finally(() => setBusy(false));
ipcInvoke('saves:previewOfficial', { copyId, userId, paths: targetPaths, includeUsedVehicles: includeUsed })
.then(setPreview)
.catch(onError)
.finally(() => setBusy(false));
};
const apply = (): void => {
if (paths.length === 0) return;
setBusy(true);
ipcInvoke('saves:importOfficial', { ...request, options }).then((value) => {
setPreview(value);
setImported(true);
}).catch(onError).finally(() => setBusy(false));
ipcInvoke('saves:importOfficial', { copyId, userId, paths, options })
.then((value) => {
setPreview(value);
setImported(true);
onImported?.();
})
.catch(onError)
.finally(() => setBusy(false));
};
const formatTime = (iso: string): string => {
const parsed = Date.parse(iso);
return Number.isNaN(parsed) ? iso : new Date(parsed).toLocaleString(i18n.language);
};
const canImportSelection = options.importSettings || options.unlockVehicles;
return (
<>
<Row label={t('saves.official.auto')} hint={t('saves.official.autoHint')}>
<button type="button" className="button button-primary" onClick={() => discover(true)} disabled={busy || readOnly || !canImportSelection}>
{t('saves.official.oneClick')}
</button>
<button type="button" className="button" onClick={() => discover(false)} disabled={busy}>
{t('saves.official.discover')}
</button>
</Row>
{sources !== null && sources.length === 0 && (
<p className="small">{t('saves.official.notFound')}</p>
)}
{sources !== null && sources.length > 0 && (
<Row label={t('saves.official.account')} hint={sources.length > 1 ? t('saves.official.multipleAccounts', { count: sources.length }) : undefined}>
<select
className="select"
aria-label={t('saves.official.account')}
value={selectedAccount}
disabled={busy}
onChange={(event) => selectOnlineAccount(event.target.value)}
>
{sources.map((entry) => (
<option key={entry.accountId} value={entry.accountId}>
{t('saves.official.accountOption', {
id: entry.accountId,
files: entry.files.join(', '),
time: formatTime(entry.updatedAt),
})}
</option>
))}
</select>
</Row>
)}
<Row label={t('saves.official.files')} hint={t('saves.official.fileHint')}>
<button type="button" className="button" onClick={choose} disabled={busy}>{t('saves.official.choose')}</button>
{paths.length > 0 && <span className="folder-path" title={paths.join('\n')}>{paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}</span>}
{paths.length > 0 && (
<span className="folder-path" data-ellipsis-tip={paths.join('\n')}>
{paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}
</span>
)}
</Row>
<Row label={t('saves.official.content')}>
<label className="check check-inline">
<input type="checkbox" checked={options.importSettings} disabled={busy} onChange={(event) => {
setOptions({ ...options, importSettings: event.target.checked });
setImported(false);
}} />
{t('saves.official.settings')}
</label>
<label className="check check-inline">
<input type="checkbox" checked={options.unlockVehicles} disabled={busy} onChange={(event) => {
setOptions({ ...options, unlockVehicles: event.target.checked });
setImported(false);
}} />
{t('saves.official.unlock')}
</label>
</Row>
<Row label={t('saves.official.equipment')}>
<Row label={t('saves.official.equipment')} hint={t('saves.official.equipmentHint')}>
<select className="select" aria-label={t('saves.official.equipment')} value={options.equipment} disabled={busy || !options.unlockVehicles}
onChange={(event) => setOptions({ ...options, equipment: event.target.value as OfficialImportOptions['equipment'] })}>
onChange={(event) => {
setOptions({ ...options, equipment: event.target.value as OfficialImportOptions['equipment'] });
setImported(false);
}}>
<option value="full">{t('saves.official.full')}</option>
<option value="basic">{t('saves.official.basic')}</option>
<option value="stock">{t('saves.official.stock')}</option>
</select>
<label className="check check-inline">
<input type="checkbox" checked={options.includeUsedVehicles} disabled={busy || !options.unlockVehicles} onChange={(event) => {
setOptions({ ...options, includeUsedVehicles: event.target.checked });
setPreview(null);
const nextInclude = event.target.checked;
setOptions({ ...options, includeUsedVehicles: nextInclude });
setImported(false);
if (paths.length > 0 && preview) {
load(paths, nextInclude);
} else {
setPreview(null);
}
}} />
{t('saves.official.includeUsed')}
</label>
</Row>
<div className="copy-list-actions">
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={load}>{t('saves.official.preview')}</button>
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={() => load()}>{t('saves.official.preview')}</button>
<button type="button" className="button button-primary"
disabled={busy || readOnly || !preview || imported || (!options.importSettings && !options.unlockVehicles)} onClick={apply}>
disabled={busy || readOnly || !preview || imported || !canImportSelection} onClick={apply}>
{t('saves.official.import')}
</button>
</div>
@@ -66,6 +66,13 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
setList((current) => current && { ...current, saves: current.saves.map((save) => save.userId === updated.save.userId ? updated.save : save) });
};
const refreshSave = (): void => {
ipcInvoke('saves:list', { copyId: copy.id }).then(setList).catch(onError);
if (userId) {
ipcInvoke('saves:details', { copyId: copy.id, userId }).then(updateDetails).catch(onError);
}
};
const submitNew = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const data = new FormData(event.currentTarget);
@@ -278,7 +285,9 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
</Row>
))
)}
{section === 'official' && <OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
{section === 'official' && (
<OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onImported={refreshSave} />
)}
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
</Sheet>
+9 -1
View File
@@ -17,7 +17,7 @@ import {
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts';
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, 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';
@@ -200,6 +200,14 @@ export const ipcContract = {
input: SaveKeysSchema.extend({ name: SaveBackupNameSchema }),
output: SaveDetailsSchema,
},
'saves:discoverOnlineData': {
input: z.void(),
output: z.array(OnlineDataSourceSchema),
},
'saves:copyOnlineData': {
input: SaveKeysSchema.extend({ accountId: z.string().regex(/^\d+$/) }),
output: z.array(z.string()),
},
'saves:pickOfficialBackups': {
input: z.void(),
output: z.array(z.string()),
@@ -69,6 +69,13 @@ export const SaveBackupSchema = z.object({
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import']), size: z.number().int().nonnegative(),
});
export const OnlineDataFileNameSchema = z.enum(['global.blk', 'machine.blk', 'storage.blk']);
export const OnlineDataSourceSchema = z.object({
accountId: z.string().regex(/^\d+$/),
folder: z.string().min(1),
files: z.array(OnlineDataFileNameSchema).min(1),
updatedAt: z.string(),
});
export const SaveOfficialRequestSchema = SaveKeysSchema.extend({
paths: z.array(z.string().min(1)).min(1).max(3),
});
@@ -95,6 +102,7 @@ export type ResearchBranch = z.output<typeof ResearchBranchSchema>;
export type ResearchOperation = z.output<typeof ResearchOperationSchema>;
export type SaveResearch = z.output<typeof SaveResearchSchema>;
export type OnlineDataSource = z.output<typeof OnlineDataSourceSchema>;
export type OfficialPreview = z.output<typeof OfficialPreviewSchema>;
export type OfficialImportOptions = z.output<typeof OfficialImportOptionsSchema>;