diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 31b2332..df3a00a 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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)); diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 7354946..51eaffb 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -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 { + 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 { + const root = onlineSavesRoot(); + const entries = await readdir(root, { withFileTypes: true }).catch(() => []); + const found: Array = []; + + 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 { + 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 { 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; diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts index e5f190c..5e56fb6 100644 --- a/apps/launcher/src/main/workers/save-protocol.ts +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -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 } diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts index c41eae5..a8803e9 100644 --- a/apps/launcher/src/main/workers/save-worker.ts +++ b/apps/launcher/src/main/workers/save-worker.ts @@ -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' }; diff --git a/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx index af88008..07ad496 100644 --- a/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx @@ -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(null); + const [selectedAccount, setSelectedAccount] = useState(''); const [paths, setPaths] = useState([]); const [options, setOptions] = useState(DEFAULTS); const [preview, setPreview] = useState(null); const [busy, setBusy] = useState(false); const [imported, setImported] = useState(false); - const request = { copyId, userId, paths }; + + const stageAndPreview = async (accountId: string, includeUsed: boolean): Promise => { + 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 ( <> + + + + + {sources !== null && sources.length === 0 && ( +

{t('saves.official.notFound')}

+ )} + {sources !== null && sources.length > 0 && ( + 1 ? t('saves.official.multipleAccounts', { count: sources.length }) : undefined}> + + + )} - {paths.length > 0 && {paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')}} + {paths.length > 0 && ( + + {paths.map((path) => path.split(/[\\/]/).at(-1)).join(', ')} + + )} - +
- +
diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index 304d477..a4ba2d8 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -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): void => { event.preventDefault(); const data = new FormData(event.currentTarget); @@ -278,7 +285,9 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
)) )} - {section === 'official' && } + {section === 'official' && ( + + )} {section === 'backup' && } {section === 'vehicles' && } diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 2a18a72..7335c25 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -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()), diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index 3e11fd1..b02c778 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -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; export type ResearchOperation = z.output; export type SaveResearch = z.output; +export type OnlineDataSource = z.output; export type OfficialPreview = z.output; export type OfficialImportOptions = z.output;