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:
1 parent
f39d7b05c1
commit
db84971823
8 files changed
+261
-25
No files matched your search
@@ -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' };
|
||||
|
||||
Reference in new issue
Block a user