diff --git a/src/main/index.ts b/src/main/index.ts index 5489db9..e879f66 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -7,6 +7,7 @@ import { isMacOS } from './platform'; import { ensureRomsStructure } from './emulators'; import { setupAutoUpdater } from './updater'; import { generatePegasusCollectionsForRomDir } from './configurator'; +import { startSyncthing } from './syncthing'; let mainWindow: BrowserWindow | null = null; let tray: Tray | null = null; @@ -132,6 +133,14 @@ app.whenReady().then(() => { } } catch { /* ignore */ } + // Auto-start Syncthing if cloud sync was previously enabled + try { + const s = settings.get(); + if (s.cloudSyncEnabled) { + startSyncthing().catch(() => { /* ignore */ }); + } + } catch { /* ignore */ } + app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); else mainWindow?.show(); diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 81b074c..c4ae7cd 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -25,6 +25,16 @@ import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail, ca import { getGameAchievements } from './ra'; import { scanBiosDirectory, getKnownBiosList, getDefaultBiosDir, updateRetroarchBiosPath } from './bios'; import { listAllSaves, deleteSave, backupSave } from './saveManager'; +import { + installSyncthing, + startSyncthing, + stopSyncthing, + getSyncthingStatus, + addRemoteDevice, + removeRemoteDevice, + addSharedFolder, + removeSharedFolder, +} from './syncthing'; export function registerIpcHandlers(): void { // System @@ -351,4 +361,69 @@ export function registerIpcHandlers(): void { settings.save({ saveDirectories: dirs }); return true; }); + + // Cloud Sync (Syncthing) + ipcMain.handle('cloud:status', async () => { + try { + return await getSyncthingStatus(); + } catch (err) { + console.error('cloud:status error:', err); + return { installed: false, running: false, deviceId: '', apiAddress: '', apiKey: '', version: '', folders: [], remoteDevices: [] }; + } + }); + + ipcMain.handle('cloud:install', async (event) => { + const win = BrowserWindow.fromWebContents(event.sender); + const ok = await installSyncthing((stage, percent, message) => { + win?.webContents.send('cloud:install-progress', { stage, percent, message }); + }); + return ok; + }); + + ipcMain.handle('cloud:start', async () => { + try { + // Fire-and-forget: start the process, don't block IPC + startSyncthing().catch(err => console.error('cloud:start background error:', err)); + // Give it a moment to see if it comes up quickly + await new Promise(r => setTimeout(r, 2000)); + return await getSyncthingStatus(); + } catch (err) { + console.error('cloud:start error:', err); + return null; + } + }); + + ipcMain.handle('cloud:stop', async () => { + try { + await stopSyncthing(); + } catch (err) { + console.error('cloud:stop error:', err); + } + return getSyncthingStatus(); + }); + + ipcMain.handle('cloud:add-device', async (_event, deviceId: string, name: string) => { + return addRemoteDevice(deviceId, name); + }); + + ipcMain.handle('cloud:remove-device', async (_event, deviceId: string) => { + return removeRemoteDevice(deviceId); + }); + + ipcMain.handle('cloud:add-folder', async (_event, id: string, label: string, path: string, deviceIds: string[]) => { + return addSharedFolder(id, label, path, deviceIds); + }); + + ipcMain.handle('cloud:remove-folder', async (_event, folderId: string) => { + return removeSharedFolder(folderId); + }); + + ipcMain.handle('cloud:open-web-ui', async () => { + const status = await getSyncthingStatus(); + if (status.running && status.apiAddress) { + shell.openExternal(status.apiAddress); + return true; + } + return false; + }); } diff --git a/src/main/preload.ts b/src/main/preload.ts index c159815..117de6a 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -9,6 +9,7 @@ import type { ConfigPreset, GameMetadata, AchievementInfo, + SyncthingStatus, } from '../shared/types'; const api = { @@ -151,6 +152,27 @@ const api = { return () => ipcRenderer.removeListener('updates:download-progress', handler); }, }, + + cloud: { + status: (): Promise => ipcRenderer.invoke('cloud:status'), + install: (): Promise => ipcRenderer.invoke('cloud:install'), + start: (): Promise => ipcRenderer.invoke('cloud:start'), + stop: (): Promise => ipcRenderer.invoke('cloud:stop'), + addDevice: (deviceId: string, name: string): Promise => + ipcRenderer.invoke('cloud:add-device', deviceId, name), + removeDevice: (deviceId: string): Promise => + ipcRenderer.invoke('cloud:remove-device', deviceId), + addFolder: (id: string, label: string, path: string, deviceIds: string[]): Promise => + ipcRenderer.invoke('cloud:add-folder', id, label, path, deviceIds), + removeFolder: (folderId: string): Promise => + ipcRenderer.invoke('cloud:remove-folder', folderId), + openWebUI: (): Promise => ipcRenderer.invoke('cloud:open-web-ui'), + onInstallProgress: (cb: (progress: { stage: string; percent: number; message: string }) => void) => { + const handler = (_event: Electron.IpcRendererEvent, p: { stage: string; percent: number; message: string }) => cb(p); + ipcRenderer.on('cloud:install-progress', handler); + return () => ipcRenderer.removeListener('cloud:install-progress', handler); + }, + }, }; contextBridge.exposeInMainWorld('omni', api); diff --git a/src/main/saveManager.ts b/src/main/saveManager.ts index 2860afa..31db3d9 100644 --- a/src/main/saveManager.ts +++ b/src/main/saveManager.ts @@ -1,4 +1,4 @@ -import { existsSync, readdirSync, statSync, unlinkSync, copyFileSync, mkdirSync } from 'fs'; +import { existsSync, readdirSync, statSync, unlinkSync, copyFileSync, mkdirSync, readFileSync } from 'fs'; import { join, extname, basename } from 'path'; import { app } from 'electron'; import { homedir } from 'os'; @@ -15,20 +15,102 @@ interface SaveDirConfig { states?: string; } +function parseRetroarchConfig(cfgPath: string): Record { + try { + if (!existsSync(cfgPath)) return {}; + const content = readFileSync(cfgPath, 'utf-8'); + const result: Record = {}; + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const eqIdx = trimmed.indexOf('='); + if (eqIdx < 0) continue; + const key = trimmed.slice(0, eqIdx).trim(); + let val = trimmed.slice(eqIdx + 1).trim(); + if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { + val = val.slice(1, -1); + } + result[key] = val; + } + return result; + } catch { return {}; } +} + +function resolveRetroarchSaveDirs(): SaveDirConfig { + const candidates: string[] = []; + + if (platform === 'win32') { + candidates.push(join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch')); + } else if (platform === 'darwin') { + candidates.push(join(home, 'Library', 'Application Support', 'RetroArch')); + candidates.push(join(home, 'Documents', 'RetroArch')); + candidates.push(join(home, 'Desktop', 'RetroArch')); + } else { + candidates.push(join(home, '.config', 'retroarch')); + } + + const customDirs = settings.get().saveDirectories || {}; + if (customDirs.retroarch) { + candidates.unshift(customDirs.retroarch); + } + + for (const dir of candidates) { + const cfgPath = join(dir, 'retroarch.cfg'); + if (existsSync(cfgPath)) { + const cfg = parseRetroarchConfig(cfgPath); + const saveDir = cfg['savefile_directory']; + const stateDir = cfg['savestate_directory']; + + let saves: string; + let states: string | undefined; + + if (saveDir && saveDir !== 'default') { + saves = saveDir.startsWith('/') ? saveDir : join(dir, saveDir); + } else { + saves = join(dir, 'saves'); + } + + if (stateDir && stateDir !== 'default') { + states = stateDir.startsWith('/') ? stateDir : join(dir, stateDir); + } else { + states = join(dir, 'states'); + } + + if (existsSync(saves) || existsSync(states || '')) { + return { saves, states }; + } + } + + const saves = join(dir, 'saves'); + const states = join(dir, 'states'); + if (existsSync(saves) || existsSync(states)) { + return { saves, states }; + } + } + + return { + saves: platform === 'win32' + ? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'saves') + : platform === 'darwin' + ? join(home, 'Library', 'Application Support', 'RetroArch', 'saves') + : join(home, '.config', 'retroarch', 'saves'), + states: platform === 'win32' + ? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'states') + : platform === 'darwin' + ? join(home, 'Library', 'Application Support', 'RetroArch', 'states') + : join(home, '.config', 'retroarch', 'states'), + }; +} + +let _retroarchDirs: SaveDirConfig | null = null; +function getRetroarchSaveDirs(): SaveDirConfig { + if (!_retroarchDirs) _retroarchDirs = resolveRetroarchSaveDirs(); + return _retroarchDirs; +} + function emulatorSaveDirs(emuId: string): SaveDirConfig | null { const configs: Record = { - retroarch: { - saves: platform === 'win32' - ? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'saves') - : platform === 'darwin' - ? join(home, 'Library', 'Application Support', 'RetroArch', 'saves') - : join(home, '.config', 'retroarch', 'saves'), - states: platform === 'win32' - ? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'states') - : platform === 'darwin' - ? join(home, 'Library', 'Application Support', 'RetroArch', 'states') - : join(home, '.config', 'retroarch', 'states'), - }, + retroarch: getRetroarchSaveDirs(), dolphin: { saves: platform === 'win32' ? join(home, 'Documents', 'Dolphin Emulator', 'GC') @@ -129,31 +211,38 @@ function gameNameFromSave(fileName: string): string { return name.trim() || fileName; } -function scanDir(dir: string): SaveEntry[] { +function scanDir(dir: string, maxDepth = 3): SaveEntry[] { if (!existsSync(dir)) return []; const entries: SaveEntry[] = []; - try { - const files = readdirSync(dir); - for (const file of files) { - const fullPath = join(dir, file); - try { - const st = statSync(fullPath); - if (!st.isFile()) continue; - const type = isSaveFile(file); - if (!type) continue; - entries.push({ - id: fullPath, - emulatorId: '', - gameName: gameNameFromSave(file), - fileName: file, - filePath: fullPath, - fileSize: st.size, - lastModified: st.mtime.toISOString(), - type, - }); - } catch { /* skip unreadable */ } - } - } catch { /* skip unreadable dir */ } + const scan = (d: string, depth: number) => { + if (depth > maxDepth) return; + try { + const files = readdirSync(d); + for (const file of files) { + const fullPath = join(d, file); + try { + const st = statSync(fullPath); + if (st.isDirectory()) { + scan(fullPath, depth + 1); + continue; + } + const type = isSaveFile(file); + if (!type) continue; + entries.push({ + id: fullPath, + emulatorId: '', + gameName: gameNameFromSave(file), + fileName: file, + filePath: fullPath, + fileSize: st.size, + lastModified: st.mtime.toISOString(), + type, + }); + } catch { /* skip unreadable */ } + } + } catch { /* skip unreadable dir */ } + }; + scan(dir, 0); return entries; } diff --git a/src/main/settings.ts b/src/main/settings.ts index cc6a919..867ff82 100644 --- a/src/main/settings.ts +++ b/src/main/settings.ts @@ -32,6 +32,7 @@ const defaultSettings: AppSettings = { retroAchievementsPassword: '', retroAchievementsApiKey: '', steamGridDbApiKey: '', + syncthingPort: 8384, }; let cached: AppSettings | null = null; diff --git a/src/main/syncthing.ts b/src/main/syncthing.ts new file mode 100644 index 0000000..6921b44 --- /dev/null +++ b/src/main/syncthing.ts @@ -0,0 +1,461 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'; +import { join } from 'path'; +import { app } from 'electron'; +import http from 'http'; +import { spawn, ChildProcess } from 'child_process'; +import { getPlatform, getArch } from './platform'; +import { settings } from './settings'; +import { SyncthingStatus, SyncthingFolder, SyncthingRemoteDevice } from '../shared/types'; + +let stProcess: ChildProcess | null = null; + +const VERSION = 'v2.1.2'; + +function getSyncthingDir(): string { + return join(app.getPath('userData'), 'syncthing'); +} + +function getBinaryPath(): string { + const platform = getPlatform(); + const dir = getSyncthingDir(); + return platform === 'win32' ? join(dir, 'syncthing.exe') : join(dir, 'syncthing'); +} + +function getConfigDir(): string { + return join(getSyncthingDir(), 'config'); +} + +function getDataDir(): string { + return join(getSyncthingDir(), 'data'); +} + +function getApiKeyPath(): string { + return join(getSyncthingDir(), '.apikey'); +} + +function generateApiKey(): string { + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let key = ''; + for (let i = 0; i < 32; i++) { + key += chars.charAt(Math.floor(Math.random() * chars.length)); + } + return key; +} + +function getApiKey(): string { + const apiKeyPath = getApiKeyPath(); + if (existsSync(apiKeyPath)) { + return readFileSync(apiKeyPath, 'utf-8').trim(); + } + const key = generateApiKey(); + const dir = getSyncthingDir(); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); + writeFileSync(apiKeyPath, key, 'utf-8'); + return key; +} + +function getPort(): number { + return settings.get().syncthingPort || 8384; +} + +function apiUrl(path: string): string { + return `http://127.0.0.1:${getPort()}${path}`; +} + +function httpRequest( + method: string, + url: string, + headers: Record, + body?: string +): Promise<{ status: number; body: string }> { + return new Promise((resolve, reject) => { + const req = http.request(url, { method, headers, timeout: 5000 }, (res) => { + let data = ''; + res.on('data', (chunk: Buffer) => { data += chunk.toString(); }); + res.on('end', () => resolve({ status: res.statusCode || 0, body: data })); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); + if (body) req.write(body); + req.end(); + }); +} + +async function apiRequest(method: string, path: string, body?: any): Promise { + const url = apiUrl(path); + const apiKey = getApiKey(); + + const resp = await httpRequest(method, url, { + 'X-API-Key': apiKey, + 'Content-Type': 'application/json', + }, body ? JSON.stringify(body) : undefined); + + if (resp.status < 200 || resp.status >= 300) { + throw new Error(`Syncthing API ${method} ${path} failed (${resp.status}): ${resp.body}`); + } + + if (!resp.body) return null; + try { return JSON.parse(resp.body); } catch { return resp.body; } +} + +async function healthCheck(timeoutMs = 1000): Promise { + return new Promise((resolve) => { + const req = http.request(apiUrl('/rest/noauth/health'), { method: 'GET', timeout: timeoutMs }, (res) => { + let data = ''; + res.on('data', () => {}); + res.on('end', () => resolve(res.statusCode === 200)); + }); + req.on('error', () => resolve(false)); + req.on('timeout', () => { req.destroy(); resolve(false); }); + req.end(); + }); +} + +function ensureConfigXml(): void { + const configDir = getConfigDir(); + const dataDir = getDataDir(); + if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true }); + if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true }); + + const cfgPath = join(configDir, 'config.xml'); + if (existsSync(cfgPath)) return; + + const apiKey = getApiKey(); + const port = getPort(); + + const xml = ` + + basic + 1 + + +
dynamic
+
+ +
127.0.0.1:${port}
+ ${apiKey} + default +
+ + default + false + true + false + -1 + +
`; + + writeFileSync(cfgPath, xml, 'utf-8'); +} + +export async function installSyncthing( + onProgress?: (stage: string, percent: number, message: string) => void +): Promise { + const platform = getPlatform(); + const arch = getArch(); + + let assetName: string; + let ext: string; + if (platform === 'win32') { + assetName = `syncthing-windows-amd64-${VERSION}`; + ext = 'zip'; + } else if (platform === 'darwin') { + assetName = arch === 'arm64' + ? `syncthing-macos-arm64-${VERSION}` + : `syncthing-macos-amd64-${VERSION}`; + ext = 'zip'; + } else { + assetName = `syncthing-linux-amd64-${VERSION}`; + ext = 'tar.gz'; + } + + const url = `https://github.com/syncthing/syncthing/releases/download/${VERSION}/${assetName}.${ext}`; + const dir = getSyncthingDir(); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); + + onProgress?.('downloading', 0, `Downloading Syncthing ${VERSION}...`); + + const tmpFile = join(dir, `tmp_${Date.now()}.${ext}`); + + try { + const buffer = await downloadFile(url, (received, total) => { + const pct = total > 0 ? Math.round((received / total) * 60) : 0; + onProgress?.('downloading', pct, `Downloading... ${Math.round(received / 1024 / 1024 * 10) / 10}MB`); + }); + writeFileSync(tmpFile, buffer); + + onProgress?.('extracting', 70, 'Extracting...'); + + if (ext === 'zip') { + const { execSync } = require('child_process'); + if (platform === 'win32') { + execSync(`powershell -Command "Expand-Archive -Path '${tmpFile}' -DestinationPath '${dir}' -Force"`); + const extracted = join(dir, `${assetName}\\syncthing.exe`); + const target = join(dir, 'syncthing.exe'); + if (existsSync(extracted) && !existsSync(target)) { + const { renameSync } = require('fs'); + renameSync(extracted, target); + } + } else { + execSync(`ditto -x -k '${tmpFile}' '${dir}'`, { stdio: 'ignore' }); + const binaryPath = getBinaryPath(); + if (!existsSync(binaryPath)) { + try { execSync(`unzip -o '${tmpFile}' -d '${dir}'`, { stdio: 'ignore' }); } catch { /* ignore */ } + } + } + // Move binary out of nested directory if needed + const binaryPath = getBinaryPath(); + if (!existsSync(binaryPath)) { + const nestedBinary = join(dir, assetName, getPlatform() === 'win32' ? 'syncthing.exe' : 'syncthing'); + if (existsSync(nestedBinary)) { + const { renameSync } = require('fs'); + renameSync(nestedBinary, binaryPath); + } + } + } else { + const { execSync } = require('child_process'); + execSync(`tar -xzf '${tmpFile}' -C '${dir}' --strip-components=1`, { stdio: 'ignore' }); + } + + onProgress?.('installing', 90, 'Setting up...'); + const binaryPath = getBinaryPath(); + if (platform !== 'win32' && existsSync(binaryPath)) { + const { chmodSync } = require('fs'); + chmodSync(binaryPath, 0o755); + } + + ensureConfigXml(); + + onProgress?.('done', 100, 'Syncthing installed!'); + return true; + } catch (err) { + onProgress?.('error', 0, `Install failed: ${err}`); + return false; + } finally { + try { const { unlinkSync } = require('fs'); unlinkSync(tmpFile); } catch { /* ignore */ } + } +} + +function downloadFile( + url: string, + onProgress?: (received: number, total: number) => void +): Promise { + return new Promise((resolve, reject) => { + const https = require('https'); + const get = url.startsWith('https') ? https.get : http.get; + get(url, (res: any) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + downloadFile(res.headers.location, onProgress).then(resolve, reject); + return; + } + if (res.statusCode !== 200) { + reject(new Error(`HTTP ${res.statusCode}`)); + return; + } + const total = parseInt(res.headers['content-length'] || '0', 10); + const chunks: Buffer[] = []; + let received = 0; + res.on('data', (chunk: Buffer) => { + chunks.push(chunk); + received += chunk.length; + onProgress?.(received, total); + }); + res.on('end', () => resolve(Buffer.concat(chunks))); + res.on('error', reject); + }).on('error', reject); + }); +} + +export async function startSyncthing(): Promise { + const binaryPath = getBinaryPath(); + if (!existsSync(binaryPath)) return false; + + // If already running and healthy, just return + if (stProcess && !stProcess.killed && await healthCheck()) return true; + + // Kill stale process if any + if (stProcess && !stProcess.killed) { + try { stProcess.kill(); } catch { /* ignore */ } + stProcess = null; + await new Promise(r => setTimeout(r, 500)); + } + + ensureConfigXml(); + + stProcess = spawn(binaryPath, [ + '--no-browser', + '--no-restart', + '--config', getConfigDir(), + '--data', getDataDir(), + ], { + detached: false, + stdio: 'ignore', + }); + + stProcess.on('error', () => { stProcess = null; }); + stProcess.on('exit', (code) => { stProcess = null; }); + + // Quick check — if process died immediately, bail + await new Promise(r => setTimeout(r, 300)); + if (!stProcess || stProcess.killed) return false; + + // Wait for Syncthing to become healthy, but bail early if process dies + for (let i = 0; i < 15; i++) { + await new Promise(r => setTimeout(r, 1000)); + // Process died — don't keep polling + if (!stProcess || stProcess.killed) return false; + if (await healthCheck()) return true; + } + + return false; +} + +export async function stopSyncthing(): Promise { + if (!stProcess || stProcess.killed) return; + + try { + await apiRequest('POST', '/rest/system/shutdown'); + await new Promise((resolve) => { + const timeout = setTimeout(() => { + stProcess?.kill(); + resolve(); + }, 3000); + stProcess!.on('exit', () => { + clearTimeout(timeout); + resolve(); + }); + }); + } catch { + stProcess?.kill(); + } + stProcess = null; +} + +export async function getSyncthingStatus(): Promise { + const installed = existsSync(getBinaryPath()); + const running = installed ? await healthCheck() : false; + + if (!running) { + return { + installed, + running: false, + deviceId: '', + apiAddress: '', + apiKey: '', + version: '', + folders: [], + remoteDevices: [], + }; + } + + try { + const status = await apiRequest('GET', '/rest/system/status'); + const config = await apiRequest('GET', '/rest/config'); + + const folders: SyncthingFolder[] = (config.folders || []).map((f: any) => ({ + id: f.id, + label: f.label || f.id, + path: f.path, + type: f.type, + })); + + const remoteDevices: SyncthingRemoteDevice[] = (config.devices || []) + .filter((d: any) => d.id && d.id !== status.myID) + .map((d: any) => ({ + id: d.id, + name: d.name || (d.id ? d.id.slice(0, 8) : 'Unknown'), + addresses: d.addresses || [], + connected: !!status?.connections?.[d.id]?.connected, + })); + + return { + installed: true, + running: true, + deviceId: status.myID || '', + apiAddress: apiUrl(''), + apiKey: getApiKey(), + version: status?.version || VERSION, + folders, + remoteDevices, + }; + } catch { + return { + installed: true, + running: true, + deviceId: '', + apiAddress: apiUrl(''), + apiKey: getApiKey(), + version: '', + folders: [], + remoteDevices: [], + }; + } +} + +export async function addRemoteDevice(deviceId: string, name: string): Promise { + try { + await apiRequest('POST', '/rest/config/devices', { + deviceID: deviceId, + name: name || deviceId.slice(0, 8), + addresses: ['dynamic'], + compression: 'metadata', + introducer: false, + }); + return true; + } catch { + return false; + } +} + +export async function removeRemoteDevice(deviceId: string): Promise { + try { + await apiRequest('DELETE', `/rest/config/devices/${deviceId}`); + return true; + } catch { + return false; + } +} + +export async function addSharedFolder( + id: string, + label: string, + path: string, + deviceIds: string[] +): Promise { + try { + const devices = deviceIds.map(dId => ({ deviceID: dId })); + await apiRequest('POST', '/rest/config/folders', { + id, + label, + path, + type: 'sendreceive', + rescanIntervalS: 3600, + fsWatcherEnabled: true, + fsWatcherDelayS: 10, + devices, + }); + return true; + } catch { + return false; + } +} + +export async function removeSharedFolder(folderId: string): Promise { + try { + await apiRequest('DELETE', `/rest/config/folders/${folderId}`); + return true; + } catch { + return false; + } +} + +export async function getSyncthingVersion(): Promise { + try { + const status = await apiRequest('GET', '/rest/system/version'); + return status?.version || ''; + } catch { + return ''; + } +} + +export { getBinaryPath, getPort, getApiKey, apiUrl, getSyncthingDir }; diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 7331007..086d2a1 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -1,5 +1,6 @@ import React, { useState, useEffect } from 'react'; import { Sidebar } from './components/Sidebar'; +import { ErrorBoundary } from './components/ErrorBoundary'; import { Dashboard } from './pages/Dashboard'; import { EmulatorsPage } from './pages/EmulatorsPage'; import { LibraryPage } from './pages/LibraryPage'; @@ -7,9 +8,10 @@ import { SettingsPage } from './pages/SettingsPage'; import { ControllerPage } from './pages/ControllerPage'; import { UtilitiesPage } from './pages/UtilitiesPage'; import { SaveManagerPage } from './pages/SaveManagerPage'; +import { CloudSyncPage } from './pages/CloudSyncPage'; import { useGamepadNav } from './hooks/useGamepadNav'; -type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities'; +type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities'; export function applyTheme(theme: string) { if (theme === 'system') { @@ -39,6 +41,8 @@ export function App() { return ; case 'saves': return ; + case 'cloud': + return ; case 'settings': return ; case 'controller': diff --git a/src/renderer/components/ErrorBoundary.tsx b/src/renderer/components/ErrorBoundary.tsx new file mode 100644 index 0000000..2b9f4c3 --- /dev/null +++ b/src/renderer/components/ErrorBoundary.tsx @@ -0,0 +1,51 @@ +import React, { Component, ErrorInfo, ReactNode } from 'react'; + +interface Props { + children: ReactNode; + fallback?: ReactNode; +} + +interface State { + hasError: boolean; + error: Error | null; +} + +export class ErrorBoundary extends Component { + constructor(props: Props) { + super(props); + this.state = { hasError: false, error: null }; + } + + static getDerivedStateFromError(error: Error): State { + return { hasError: true, error }; + } + + componentDidCatch(error: Error, errorInfo: ErrorInfo) { + console.error('ErrorBoundary caught:', error, errorInfo); + } + + render() { + if (this.state.hasError) { + if (this.props.fallback) return this.props.fallback; + return ( +
+

Something went wrong

+

+ An error occurred while loading this page. +

+
+ {this.state.error?.message || 'Unknown error'} +
+ +
+ ); + } + return this.props.children; + } +} diff --git a/src/renderer/components/Sidebar.tsx b/src/renderer/components/Sidebar.tsx index 523fc7b..948a896 100644 --- a/src/renderer/components/Sidebar.tsx +++ b/src/renderer/components/Sidebar.tsx @@ -1,6 +1,6 @@ import React from 'react'; -type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities'; +type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities'; interface TopBarProps { currentPage: Page; @@ -12,6 +12,7 @@ const navItems: { page: Page; label: string; icon: string }[] = [ { page: 'emulators', label: 'Emulators', icon: 'đŸ•šī¸' }, { page: 'library', label: 'Library', icon: '📚' }, { page: 'saves', label: 'Saves', icon: '💾' }, + { page: 'cloud', label: 'Cloud Sync', icon: 'â˜ī¸' }, { page: 'controller', label: 'Controller', icon: '🎮' }, { page: 'utilities', label: 'Utilities', icon: '🔧' }, { page: 'settings', label: 'Settings', icon: 'âš™ī¸' }, diff --git a/src/renderer/hooks/useGamepadNav.ts b/src/renderer/hooks/useGamepadNav.ts index 8c2fae6..49268e4 100644 --- a/src/renderer/hooks/useGamepadNav.ts +++ b/src/renderer/hooks/useGamepadNav.ts @@ -3,9 +3,9 @@ import { useEffect, useRef, useState, useCallback } from 'react'; const DEBOUNCE_MS = 180; const LEGEND_TIMEOUT_MS = 8000; -type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities'; +type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities'; -const pageOrder: Page[] = ['dashboard', 'emulators', 'library', 'saves', 'controller', 'utilities', 'settings']; +const pageOrder: Page[] = ['dashboard', 'emulators', 'library', 'saves', 'cloud', 'controller', 'utilities', 'settings']; export function useGamepadNav(onNavigate: (page: Page) => void, currentPage: Page) { const lastTime = useRef>({}); diff --git a/src/renderer/pages/CloudSyncPage.tsx b/src/renderer/pages/CloudSyncPage.tsx new file mode 100644 index 0000000..6eae21f --- /dev/null +++ b/src/renderer/pages/CloudSyncPage.tsx @@ -0,0 +1,641 @@ +import React, { useEffect, useState, useCallback, useRef } from 'react'; +import type { SyncthingStatus } from '../../shared/types'; + +type SetupStep = 'install' | 'start' | 'setup' | 'ready'; + +export function CloudSyncPage() { + const [status, setStatus] = useState(null); + const [loading, setLoading] = useState(true); + const [installing, setInstalling] = useState(false); + const [installMsg, setInstallMsg] = useState(''); + const [installPercent, setInstallPercent] = useState(0); + const [error, setError] = useState(''); + const [success, setSuccess] = useState(''); + const [remoteDeviceId, setRemoteDeviceId] = useState(''); + const [remoteDeviceName, setRemoteDeviceName] = useState(''); + const [addingDevice, setAddingDevice] = useState(false); + const [folderLabel, setFolderLabel] = useState(''); + const [folderPath, setFolderPath] = useState(''); + const [showAddFolder, setShowAddFolder] = useState(false); + const [copied, setCopied] = useState(false); + const [cloudEnabled, setCloudEnabled] = useState(false); + const uninstallRef = useRef(null); + + const DEFAULT_STATUS: SyncthingStatus = { + installed: false, running: false, deviceId: '', apiAddress: '', + apiKey: '', version: '', folders: [], remoteDevices: [], + }; + + const loadStatus = useCallback(async () => { + setLoading(true); + try { + const s = await Promise.race([ + window.omni.cloud.status(), + new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 8000)), + ]); + if (s) setStatus(s); + else setStatus(DEFAULT_STATUS); + } catch { + setStatus(DEFAULT_STATUS); + } + setLoading(false); + }, []); + + const loadSettings = useCallback(async () => { + try { + const s = await window.omni.settings.get(); + setCloudEnabled(!!s.cloudSyncEnabled); + } catch { /* ignore */ } + }, []); + + useEffect(() => { loadStatus(); loadSettings(); }, [loadStatus, loadSettings]); + + useEffect(() => { + const unsub = window.omni.cloud.onInstallProgress((p) => { + setInstallMsg(p.message); + setInstallPercent(p.percent); + if (p.stage === 'done' || p.stage === 'error') { + setInstalling(false); + if (p.stage === 'done') { + loadStatus(); + } + } + }); + return unsub; + }, [loadStatus]); + + const showSuccess = (msg: string) => { + setSuccess(msg); + setError(''); + setTimeout(() => setSuccess(''), 4000); + }; + + const showError = (msg: string) => { + setError(msg); + setSuccess(''); + setTimeout(() => setError(''), 4000); + }; + + const saveCloudEnabled = async (enabled: boolean) => { + setCloudEnabled(enabled); + try { await window.omni.settings.save({ cloudSyncEnabled: enabled }); } catch { /* ignore */ } + }; + + const handleInstall = async () => { + setInstalling(true); + setInstallPercent(0); + setInstallMsg('Starting download...'); + try { + const ok = await window.omni.cloud.install(); + if (!ok) { + setInstalling(false); + showError('Installation failed'); + } + } catch (err) { + setInstalling(false); + showError(`Install error: ${err}`); + } + }; + + const handleStart = async () => { + setLoading(true); + try { + // Start kicks off the process in the background + const s = await window.omni.cloud.start(); + if (s) { + setStatus(s); + if (s.running) { + await saveCloudEnabled(true); + showSuccess('Syncthing started! Auto-start enabled.'); + } else { + // Process was kicked off but may need more time — poll + let attempts = 0; + const poll = setInterval(async () => { + attempts++; + try { + const latest = await window.omni.cloud.status(); + setStatus(latest); + if (latest.running) { + clearInterval(poll); + await saveCloudEnabled(true); + showSuccess('Syncthing started! Auto-start enabled.'); + setLoading(false); + } else if (attempts >= 15) { + clearInterval(poll); + showError('Syncthing took too long to start. Check that the binary is not blocked by your OS.'); + setLoading(false); + } + } catch { + if (attempts >= 15) { + clearInterval(poll); + showError('Could not reach Syncthing.'); + setLoading(false); + } + } + }, 1000); + } + } else { + showError('Failed to start Syncthing — binary not found'); + } + } catch (err) { + showError(`Start error: ${err}`); + } + setLoading(false); + }; + + const handleStop = async () => { + setLoading(true); + try { + const s = await window.omni.cloud.stop(); + setStatus(s); + await saveCloudEnabled(false); + showSuccess('Syncthing stopped. Auto-start disabled.'); + } catch (err) { + showError(`Stop error: ${err}`); + } + setLoading(false); + }; + + const handleAddDevice = async () => { + if (!remoteDeviceId.trim()) { + showError('Enter a device ID'); + return; + } + setAddingDevice(true); + try { + const ok = await window.omni.cloud.addDevice(remoteDeviceId.trim(), remoteDeviceName.trim()); + if (ok) { + showSuccess('Device added! Wait for it to accept, or add this device on the other machine.'); + setRemoteDeviceId(''); + setRemoteDeviceName(''); + loadStatus(); + } else { + showError('Failed to add device'); + } + } catch (err) { + showError(`Error: ${err}`); + } + setAddingDevice(false); + }; + + const handleRemoveDevice = async (deviceId: string) => { + try { + await window.omni.cloud.removeDevice(deviceId); + showSuccess('Device removed'); + loadStatus(); + } catch { /* ignore */ } + }; + + const handleAddFolder = async () => { + if (!folderLabel.trim() || !folderPath.trim()) { + showError('Enter folder label and path'); + return; + } + const id = folderLabel.toLowerCase().replace(/[^a-z0-9]/g, '-'); + const deviceIds = status?.remoteDevices?.map(d => d.id) || []; + try { + const ok = await window.omni.cloud.addFolder(id, folderLabel.trim(), folderPath.trim(), deviceIds); + if (ok) { + showSuccess('Shared folder added'); + setFolderLabel(''); + setFolderPath(''); + setShowAddFolder(false); + loadStatus(); + } else { + showError('Failed to add folder'); + } + } catch (err) { + showError(`Error: ${err}`); + } + }; + + const handleRemoveFolder = async (folderId: string) => { + try { + await window.omni.cloud.removeFolder(folderId); + showSuccess('Folder removed'); + loadStatus(); + } catch { /* ignore */ } + }; + + const handleCopyDeviceId = () => { + if (status?.deviceId) { + navigator.clipboard.writeText(status.deviceId); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } + }; + + const handleCopyApiKey = () => { + if (status?.apiKey) { + navigator.clipboard.writeText(status.apiKey); + showSuccess('API key copied'); + } + }; + + const handleOpenWebUI = async () => { + await window.omni.cloud.openWebUI(); + }; + + if (loading && !status) { + return
Checking Syncthing status...
; + } + + const installed = status?.installed ?? false; + const running = status?.running ?? false; + + // Determine current step + let step: SetupStep; + if (!installed) step = 'install'; + else if (!running) step = 'start'; + else if (!cloudEnabled || (status?.remoteDevices?.length ?? 0) === 0) step = 'setup'; + else step = 'ready'; + + return ( +
+

Cloud Sync

+

+ Sync your game saves between devices using Syncthing. Once set up, it runs automatically on launch. +

+ + {error && ( +
{error}
+ )} + {success && ( +
{success}
+ )} + + {/* Progress indicator */} +
+ {(['install', 'start', 'setup', 'ready'] as SetupStep[]).map((s, i) => ( + +
i + ? 'var(--success, #44ff44)' : 'var(--bg-tertiary, #333)'), + color: step === s ? '#fff' : 'var(--text-muted, #888)', + transition: 'all 0.2s ease', + }}> + {['install', 'start', 'setup', 'ready'].indexOf(step) > i ? '✓' : i + 1} +
+ + {s === 'install' ? 'Install' : s === 'start' ? 'Start' : s === 'setup' ? 'Pair' : 'Syncing'} + + {i < 3 &&
} + + ))} +
+ + {/* Status badge */} + {running && ( +
+ + {cloudEnabled ? 'Cloud sync active' : 'Running — not yet paired'} +
+ )} + + {/* Step 1: Install */} + {!installed && !installing && ( +
+
+

Install Syncthing

+
+
+

+ Syncthing is the engine behind cloud sync. It's free, open-source, and runs locally — no third-party accounts needed. +

+ +
+
+ )} + + {installing && ( +
+
+

Installing Syncthing...

+
+
+
{installMsg}
+
+
+
+
+
+ )} + + {/* Step 2: Start */} + {installed && !running && ( +
+
+

Start Syncthing

+
+
+

+ Start the sync service. It will auto-start on future app launches once enabled. +

+ +
+
+ )} + + {/* Steps 3-4: Host & Pair (running) */} + {running && ( + <> + {/* Host section — show your device ID */} +
+
+

Host — Share This Device

+
+
+

+ Copy this Device ID and paste it into the other machine's OmniEmu or Syncthing to pair. +

+
+