diff --git a/frontend/electron/main.ts b/frontend/electron/main.ts index 67a27cd..e562715 100644 --- a/frontend/electron/main.ts +++ b/frontend/electron/main.ts @@ -76,9 +76,7 @@ const downloadAvatar = async (steamId: string, url: string): Promise { const config = store.get('serverConfig'); if (config && config.enabled && config.url) { backend = new BackendService(config.url, config.token); - } else { - backend = null; - } + } else { backend = null; } }; // --- System Tray --- const createTray = () => { const possiblePaths = [ - '/usr/share/pixmaps/ultimate-ban-tracker.png', // System installed + '/usr/share/pixmaps/ultimate-ban-tracker.png', path.join(process.resourcesPath, 'assets-build', 'icon.png'), path.join(app.getAppPath(), 'assets-build', 'icon.png'), path.join(__dirname, '..', 'assets-build', 'icon.png') ]; let iconPath = ''; - for (const p of possiblePaths) { - if (p && fs.existsSync(p)) { iconPath = p; break; } - } + for (const p of possiblePaths) { if (p && fs.existsSync(p)) { iconPath = p; break; } } - console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`); - - if (!iconPath) { - console.warn(`[Tray] FAILED: No valid icon found.`); - // Fallback to a native empty icon just to avoid crashing if possible - try { - tray = new Tray(nativeImage.createEmpty()); - } catch (e) {} - return; - } + if (!iconPath) { try { tray = new Tray(nativeImage.createEmpty()); } catch (e) {} return; } try { const icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 }); tray = new Tray(icon); tray.setToolTip('Ultimate Ban Tracker'); - - if (process.platform === 'linux') { - tray.setIgnoreMouseEvents(false); - } - + if (process.platform === 'linux') tray.setIgnoreMouseEvents(false); tray.on('click', () => { if (mainWindow) { mainWindow.show(); mainWindow.focus(); } }); - - // Force initial menu build updateTrayMenu(); - const config = store.get('serverConfig'); - if (config?.theme) { - setAppIcon(config.theme); - } - console.log(`[Tray] Successfully initialized`); - } catch (e: any) { - console.error(`[Tray] Error: ${e.message}`); - } + if (config?.theme) setAppIcon(config.theme); + } catch (e: any) { console.error(`[Tray] Error: ${e.message}`); } }; const updateTrayMenu = () => { if (!tray) return; const accounts = store.get('accounts') as Account[]; const config = store.get('serverConfig'); - - console.log(`[Tray] Building menu with ${accounts.length} accounts`); - const contextMenu = Menu.buildFromTemplate([ { label: `Ultimate Ban Tracker v${app.getVersion()}`, enabled: false }, { type: 'separator' }, @@ -155,17 +125,13 @@ const updateTrayMenu = () => { submenu: accounts.length > 0 ? accounts.map(acc => ({ label: `${acc.personaName} ${acc.loginName ? `(${acc.loginName})` : ''}`, enabled: !!acc.loginName, - click: () => { - console.log(`[Tray] Switching to ${acc.loginName}`); - handleSwitchAccount(acc.loginName); - } + click: () => handleSwitchAccount(acc.loginName) })) : [{ label: 'No accounts found', enabled: false }] }, { label: 'Sync Now', enabled: !!config?.enabled, click: () => syncAccounts(true) }, { type: 'separator' }, { label: 'Show Dashboard', click: () => { if (mainWindow) { mainWindow.show(); mainWindow.focus(); } } }, { label: 'Quit', click: () => { - console.log('[Tray] Quit requested'); (app as any).isQuitting = true; if (tray) tray.destroy(); app.quit(); @@ -175,25 +141,18 @@ const updateTrayMenu = () => { }; const setAppIcon = (themeName: string = 'steam') => { - // Check system icons folder first on Linux const possiblePaths = [ path.join(__dirname, '..', 'assets-build', 'icons', `${themeName}.svg`), path.join(app.getAppPath(), 'assets-build', 'icons', `${themeName}.svg`), - '/usr/share/pixmaps/ultimate-ban-tracker.png' // Global fallback + '/usr/share/pixmaps/ultimate-ban-tracker.png' ]; - let iconPath = ''; - for (const p of possiblePaths) { - if (fs.existsSync(p)) { iconPath = p; break; } - } - + for (const p of possiblePaths) { if (fs.existsSync(p)) { iconPath = p; break; } } if (!iconPath) return; - const icon = nativeImage.createFromPath(iconPath); if (tray) tray.setImage(icon.resize({ width: 16, height: 16 })); if (mainWindow) mainWindow.setIcon(icon); - - updateTrayMenu(); // Always rebuild menu after icon update to ensure it's fresh + updateTrayMenu(); }; // --- Steam Logic --- @@ -212,17 +171,24 @@ const startSteam = () => { const handleSwitchAccount = async (loginName: string) => { if (!loginName) return false; try { - await killSteam(); const accounts = store.get('accounts') as Account[]; const account = accounts.find(a => a.loginName === loginName); - if (process.platform === 'win32') { - const regCommand = `reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`; - const rememberCommand = `reg add "HKCU\\Software\\Valve\\Steam" /v RememberPassword /t REG_DWORD /d 1 /f`; - await new Promise((res, rej) => exec(`${regCommand} && ${rememberCommand}`, (e) => e ? rej(e) : res())); - if (account && account.loginConfig) steamClient.injectAccountConfig(loginName, account.loginConfig); - } else if (process.platform === 'linux') { - await steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId); + if (account && !account._id.startsWith('shared_')) { + const freshConfig = steamClient.extractAccountConfig(loginName); + if (freshConfig) { + account.loginConfig = freshConfig; + account.sessionUpdatedAt = new Date().toISOString(); + if (backend) await backend.shareAccount(account); + store.set('accounts', accounts); + } } + await killSteam(); + if (process.platform === 'win32') { + const regBase = 'reg add "HKCU\\Software\\Valve\\Steam"'; + const commands = [`${regBase} /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`,`${regBase} /v RememberPassword /t REG_DWORD /d 1 /f`,`${regBase} /v AlreadyLoggedIn /t REG_DWORD /d 1 /f`,`${regBase} /v WantsOfflineMode /t REG_DWORD /d 0 /f`]; + await new Promise((res, rej) => exec(commands.join(' && '), (e) => e ? rej(e) : res())); + if (account && account.loginConfig) steamClient.injectAccountConfig(loginName, account.loginConfig); + } else if (process.platform === 'linux') { await steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId); } startSteam(); return true; } catch (e) { return false; } @@ -254,31 +220,18 @@ const scrapeAccountData = async (account: Account) => { account.cooldownExpiresAt = undefined; if (backend) await backend.pushCooldown(account.steamId, undefined, now.toISOString()); } - } catch (e: any) { - if (e instanceof SteamAuthError) { - account.authError = true; - } else { - console.error(`[Scraper] Temporary error for ${account.personaName}: ${e.message}`); - } - } - } - if (backend && !account._id.startsWith('shared_')) { - await backend.shareAccount(account); + } catch (e: any) { if (e instanceof SteamAuthError) account.authError = true; } } + if (backend && !account._id.startsWith('shared_')) await backend.shareAccount(account); return true; - } catch (e) { - console.error(`[Scraper] Failed to scrape ${account.personaName}:`, e); - return false; - } + } catch (e) { return false; } }; // --- Sync Worker --- const syncAccounts = async (isManual = false) => { - console.log(`[Sync] Phase 1: Pulling from server...`); initBackend(); let accounts = store.get('accounts') as Account[]; let hasChanges = false; - if (backend) { try { const shared = await backend.getSharedAccounts(); @@ -296,46 +249,27 @@ const syncAccounts = async (isManual = false) => { }); hasChanges = true; } else { - const sDate = s.sessionUpdatedAt ? new Date(s.sessionUpdatedAt) : new Date(0); - const lDate = exists.sessionUpdatedAt ? new Date(exists.sessionUpdatedAt) : new Date(0); - // 1. SENSITIVE DATA SYNC (Credentials) const sSessionDate = s.sessionUpdatedAt ? new Date(s.sessionUpdatedAt) : new Date(0); const lSessionDate = exists.sessionUpdatedAt ? new Date(exists.sessionUpdatedAt) : new Date(0); - const isLocalAccount = !exists._id.startsWith('shared_'); const isLocalSessionHealthy = exists.steamLoginSecure && !exists.authError; - - // SMART OVERWRITE LOGIC: - // - If it's a remote shared account: Newest wins. - // - If it's a LOCAL account: Only overwrite if our local session is broken/missing. const shouldOverwriteCredentials = !isLocalAccount ? (sSessionDate > lSessionDate) : (!isLocalSessionHealthy && sSessionDate > lSessionDate); - if (shouldOverwriteCredentials) { if (s.loginName) exists.loginName = s.loginName; if (s.loginConfig) exists.loginConfig = s.loginConfig; - if (s.steamLoginSecure) { - exists.steamLoginSecure = s.steamLoginSecure; - exists.autoCheckCooldown = true; - exists.authError = false; - } + if (s.steamLoginSecure) { exists.steamLoginSecure = s.steamLoginSecure; exists.autoCheckCooldown = true; exists.authError = false; } exists.sessionUpdatedAt = s.sessionUpdatedAt; hasChanges = true; } - - // 2. Metadata Sync (Pull) - Always "Newest Wins" const sMetaDate = s.lastMetadataCheck ? new Date(s.lastMetadataCheck) : new Date(0); const lMetaDate = exists.lastBanCheck ? new Date(exists.lastBanCheck) : new Date(0); if (sMetaDate > lMetaDate) { - exists.personaName = s.personaName; - exists.avatar = s.avatar; - exists.vacBanned = s.vacBanned; - exists.gameBans = s.gameBans; + exists.personaName = s.personaName; exists.avatar = s.avatar; + exists.vacBanned = s.vacBanned; exists.gameBans = s.gameBans; exists.status = (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none'; exists.lastBanCheck = s.lastMetadataCheck; hasChanges = true; } - - // Cooldown Sync (Pull) const sScrapeDate = s.lastScrapeTime ? new Date(s.lastScrapeTime) : new Date(0); const lScrapeDate = exists.lastScrapeTime ? new Date(exists.lastScrapeTime) : new Date(0); if (sScrapeDate > lScrapeDate) { @@ -343,25 +277,14 @@ const syncAccounts = async (isManual = false) => { exists.lastScrapeTime = s.lastScrapeTime; hasChanges = true; } - - if (JSON.stringify(exists.sharedWith) !== JSON.stringify(s.sharedWith)) { - exists.sharedWith = s.sharedWith; - hasChanges = true; - } + if (JSON.stringify(exists.sharedWith) !== JSON.stringify(s.sharedWith)) { exists.sharedWith = s.sharedWith; hasChanges = true; } } } } catch (e) { } } - - if (hasChanges) { - store.set('accounts', accounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); - updateTrayMenu(); - } - - // Phase 2: Background Scrapes + if (hasChanges) { store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); } + const runScrapes = async () => { - console.log(`[Sync] Phase 2: Starting background checks for ${accounts.length} accounts...`); const currentAccounts = [...store.get('accounts') as Account[]]; let scrapeChanges = false; for (const account of currentAccounts) { @@ -372,27 +295,18 @@ const syncAccounts = async (isManual = false) => { const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0); const needsMetadata = (now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName; const needsCooldown = account.autoCheckCooldown && account.steamLoginSecure && (now.getTime() - lastScrape.getTime()) / 3600000 > 8; - if (needsMetadata || needsCooldown || isManual) { if (!isManual && needsCooldown) await new Promise(r => setTimeout(r, Math.floor(Math.random() * 30000) + 5000)); if (await scrapeAccountData(account)) scrapeChanges = true; } } catch (error) { } } - if (scrapeChanges) { - store.set('accounts', currentAccounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts); - updateTrayMenu(); - } - console.log('[Sync] Sync cycle finished.'); + if (scrapeChanges) { store.set('accounts', currentAccounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts); updateTrayMenu(); } }; - if (isManual) await runScrapes(); else runScrapes(); }; -const scheduleNextSync = () => { - setTimeout(async () => { await syncAccounts(false); scheduleNextSync(); }, isDev ? 300000 : 1800000); -}; +const scheduleNextSync = () => { setTimeout(async () => { await syncAccounts(false); scheduleNextSync(); }, isDev ? 300000 : 1800000); }; // --- Discovery --- const addingAccounts = new Set(); @@ -402,23 +316,15 @@ const handleLocalAccountsFound = async (localAccounts: LocalSteamAccount[]) => { for (const local of localAccounts) { if (addingAccounts.has(local.steamId)) continue; const exists = currentAccounts.find(a => a.steamId === local.steamId); - if (exists) { - if (!exists.loginName && local.accountName) { exists.loginName = local.accountName; hasChanges = true; } + if (exists) { if (!exists.loginName && local.accountName) { exists.loginName = local.accountName; hasChanges = true; } } else { addingAccounts.add(local.steamId); try { const profile = await fetchProfileData(local.steamId); const bans = await scrapeBanStatus(profile.profileUrl); const localPath = await downloadAvatar(profile.steamId, profile.avatar); - - // Wait and retry snagging the config (Steam takes time to write it) let loginConfig = undefined; - for (let i = 0; i < 3; i++) { - await new Promise(r => setTimeout(r, 2000)); - loginConfig = steamClient.extractAccountConfig(local.accountName); - if (loginConfig) break; - } - + for (let i = 0; i < 3; i++) { await new Promise(r => setTimeout(r, 2000)); loginConfig = steamClient.extractAccountConfig(local.accountName); if (loginConfig) break; } currentAccounts.push({ _id: Date.now().toString() + Math.random().toString().slice(2, 5), steamId: local.steamId, personaName: profile.personaName || local.accountName, @@ -433,69 +339,51 @@ const handleLocalAccountsFound = async (localAccounts: LocalSteamAccount[]) => { addingAccounts.delete(local.steamId); } } - if (hasChanges) { - store.set('accounts', currentAccounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts); - updateTrayMenu(); - } + if (hasChanges) { store.set('accounts', currentAccounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts); updateTrayMenu(); } }; -// --- Main Window --- -function createWindow() { - mainWindow = new BrowserWindow({ - width: 1280, height: 800, title: "Ultimate Ban Tracker", backgroundColor: '#171a21', autoHideMenuBar: true, - webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: false, contextIsolation: true } +// --- Single Instance & Window --- +const gotTheLock = app.requestSingleInstanceLock(); +if (!gotTheLock) { + app.quit(); +} else { + app.on('second-instance', () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.show(); mainWindow.focus(); } }); + + function createWindow() { + mainWindow = new BrowserWindow({ + width: 1280, height: 800, title: "Ultimate Ban Tracker", backgroundColor: '#171a21', autoHideMenuBar: true, + webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: false, contextIsolation: true } + }); + mainWindow.setMenu(null); + mainWindow.on('close', (event) => { if (!(app as any).isQuitting) { event.preventDefault(); mainWindow?.hide(); } return false; }); + if (isDev) mainWindow.loadURL('http://localhost:5173'); + else mainWindow.loadFile(path.join(__dirname, '..', 'dist', 'index.html')); + } + + app.whenReady().then(() => { + protocol.handle('steam-resource', (request) => { + let rawPath = decodeURIComponent(request.url.replace('steam-resource://', '')); + if (process.platform !== 'win32' && !rawPath.startsWith('/')) rawPath = '/' + rawPath; + const absolutePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(rawPath); + if (!fs.existsSync(absolutePath)) return new Response('Not Found', { status: 404 }); + try { return net.fetch(pathToFileURL(absolutePath).toString()); } catch (e) { return new Response('Error', { status: 500 }); } + }); + createWindow(); createTray(); initBackend(); + setTimeout(() => syncAccounts(false), 5000); scheduleNextSync(); + steamClient.startWatching(handleLocalAccountsFound); }); - mainWindow.setMenu(null); - mainWindow.on('close', (event) => { - if (!(app as any).isQuitting) { event.preventDefault(); mainWindow?.hide(); } - return false; - }); - if (isDev) mainWindow.loadURL('http://localhost:5173'); - else mainWindow.loadFile(path.join(__dirname, '..', 'dist', 'index.html')); } -app.whenReady().then(() => { - protocol.handle('steam-resource', (request) => { - let rawPath = decodeURIComponent(request.url.replace('steam-resource://', '')); - if (process.platform !== 'win32' && !rawPath.startsWith('/')) rawPath = '/' + rawPath; - const absolutePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(rawPath); - if (!fs.existsSync(absolutePath)) return new Response('Not Found', { status: 404 }); - try { return net.fetch(pathToFileURL(absolutePath).toString()); } catch (e) { return new Response('Error', { status: 500 }); } - }); - createWindow(); - createTray(); - initBackend(); - setTimeout(() => syncAccounts(false), 5000); - scheduleNextSync(); - steamClient.startWatching(handleLocalAccountsFound); -}); +app.on('before-quit', () => { (app as any).isQuitting = true; if (tray) tray.destroy(); }); +app.on('window-all-closed', () => { if (process.platform !== 'darwin' && (app as any).isQuitting) app.quit(); }); +app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0 && gotTheLock) createWindow(); else mainWindow?.show(); }); -// Support for background running -(app as any).isQuitting = false; - -app.on('before-quit', () => { - console.log('[App] Preparing to quit...'); - (app as any).isQuitting = true; - if (tray) { - tray.destroy(); - tray = null; - } -}); - -app.on('window-all-closed', () => { - if (process.platform !== 'darwin' && (app as any).isQuitting) { - app.quit(); - } -}); - -app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); else mainWindow?.show(); }); - -// Handle terminal termination (Ctrl+C) -process.on('SIGINT', () => { - (app as any).isQuitting = true; - app.quit(); -}); +const handleSignal = (signal: string) => { + if (!(app as any).isQuitting && mainWindow) { mainWindow.hide(); } + else if ((app as any).isQuitting) { app.quit(); } +}; +process.on('SIGINT', () => handleSignal('SIGINT')); +process.on('SIGTERM', () => handleSignal('SIGTERM')); // --- IPC Handlers --- ipcMain.handle('get-accounts', () => store.get('accounts')); @@ -504,33 +392,23 @@ ipcMain.handle('update-server-config', (event, config: Partial) => const current = store.get('serverConfig'); const updated = { ...current, ...config }; store.set('serverConfig', updated); - initBackend(); - return updated; + initBackend(); return updated; }); - ipcMain.handle('login-to-server', async () => { initBackend(); const config = store.get('serverConfig') as ServerConfig; if (!config.url) return false; return new Promise((resolve) => { - const authWindow = new BrowserWindow({ - width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Server', - webPreferences: { nodeIntegration: false, contextIsolation: true } - }); + const authWindow = new BrowserWindow({ width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Server', webPreferences: { nodeIntegration: false, contextIsolation: true } }); authWindow.loadURL(`${config.url}/auth/steam`); let captured = false; const saveServerAuth = (token: string) => { if (captured) return; captured = true; let serverSteamId = undefined; let isAdmin = false; - try { - const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64').toString()); - serverSteamId = payload.steamId; isAdmin = !!payload.isAdmin; - } catch (e) {} + try { const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64').toString()); serverSteamId = payload.steamId; isAdmin = !!payload.isAdmin; } catch (e) {} const current = store.get('serverConfig'); store.set('serverConfig', { ...current, token, serverSteamId, isAdmin, enabled: true }); - initBackend(); - authWindow.close(); - resolve(true); + initBackend(); authWindow.close(); resolve(true); }; const filter = { urls: [`${config.url}/*`] }; authWindow.webContents.session.webRequest.onHeadersReceived(filter, (details, callback) => { @@ -539,29 +417,20 @@ ipcMain.handle('login-to-server', async () => { if (authToken) saveServerAuth(authToken); callback({ cancel: false }); }); - authWindow.on('page-title-updated', (event, title) => { - if (title.includes('AUTH_TOKEN:')) { const token = title.split('AUTH_TOKEN:')[1]; if (token) saveServerAuth(token); } - }); + authWindow.on('page-title-updated', (event, title) => { if (title.includes('AUTH_TOKEN:')) { const token = title.split('AUTH_TOKEN:')[1]; if (token) saveServerAuth(token); } }); authWindow.on('closed', () => resolve(false)); }); }); - ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId })); ipcMain.handle('sync-now', async () => { await syncAccounts(true); return true; }); - ipcMain.handle('scrape-account', async (event, steamId: string) => { const accounts = store.get('accounts') as Account[]; const account = accounts.find(a => a.steamId === steamId); if (!account) return false; const success = await scrapeAccountData(account); - if (success) { - store.set('accounts', accounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); - updateTrayMenu(); - } + if (success) { store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); } return success; }); - ipcMain.handle('add-account', async (event, { identifier }) => { try { initBackend(); @@ -580,41 +449,27 @@ ipcMain.handle('add-account', async (event, { identifier }) => { autoCheckCooldown: !!existing.steamLoginSecure, status: (existing.vacBanned || existing.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString(), sharedWith: existing.sharedWith }; - store.set('accounts', [...accounts, newAccount]); - updateTrayMenu(); - return newAccount; + store.set('accounts', [...accounts, newAccount]); updateTrayMenu(); return newAccount; } } const profile = await fetchProfileData(identifier); const bans = await scrapeBanStatus(profile.profileUrl); const localAvatar = await downloadAvatar(profile.steamId, profile.avatar); const accounts = store.get('accounts') as Account[]; - const newAccount: Account = { - _id: Date.now().toString(), steamId: profile.steamId, personaName: profile.personaName, - loginName: '', avatar: profile.avatar, localAvatar: localAvatar, profileUrl: profile.profileUrl, - autoCheckCooldown: false, vacBanned: bans.vacBanned, gameBans: bans.gameBans, - status: (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString() - }; - store.set('accounts', [...accounts, newAccount]); - updateTrayMenu(); - return newAccount; + const newAccount: Account = { _id: Date.now().toString(), steamId: profile.steamId, personaName: profile.personaName, loginName: '', avatar: profile.avatar, localAvatar: localAvatar, profileUrl: profile.profileUrl, autoCheckCooldown: false, vacBanned: bans.vacBanned, gameBans: bans.gameBans, status: (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString() }; + store.set('accounts', [...accounts, newAccount]); updateTrayMenu(); return newAccount; } catch (error: any) { throw error; } }); - ipcMain.handle('update-account', (event, id: string, data: Partial) => { const accounts = store.get('accounts') as Account[]; const index = accounts.findIndex((a: Account) => a._id === id); if (index !== -1) { accounts[index] = { ...accounts[index], ...data } as Account; store.set('accounts', accounts); updateTrayMenu(); return accounts[index]; } return null; }); - ipcMain.handle('delete-account', (event, id: string) => { const accounts = store.get('accounts') as Account[]; - store.set('accounts', accounts.filter((a: Account) => a._id !== id)); - updateTrayMenu(); - return true; + store.set('accounts', accounts.filter((a: Account) => a._id !== id)); updateTrayMenu(); return true; }); - ipcMain.handle('share-account-with-user', async (event, steamId: string, targetSteamId: string) => { initBackend(); if (backend) { @@ -625,87 +480,46 @@ ipcMain.handle('share-account-with-user', async (event, steamId: string, targetS } throw new Error('Backend not configured'); }); - -ipcMain.handle('revoke-account-access', async (event, steamId: string, targetSteamId: string) => { - initBackend(); - if (backend) return await backend.revokeAccess(steamId, targetSteamId); - throw new Error('Backend not configured'); -}); - -ipcMain.handle('revoke-all-account-access', async (event, steamId: string) => { - initBackend(); - if (backend) return await backend.revokeAllAccess(steamId); - throw new Error('Backend not configured'); -}); - +ipcMain.handle('revoke-account-access', async (event, steamId: string, targetSteamId: string) => { initBackend(); if (backend) return await backend.revokeAccess(steamId, targetSteamId); throw new Error('Backend not configured'); }); +ipcMain.handle('revoke-all-account-access', async (event, steamId: string) => { initBackend(); if (backend) return await backend.revokeAllAccess(steamId); throw new Error('Backend not configured'); }); ipcMain.handle('get-community-accounts', async () => { initBackend(); return backend ? await backend.getCommunityAccounts() : []; }); ipcMain.handle('get-server-users', async () => { initBackend(); return backend ? await backend.getServerUsers() : []; }); - -// --- Admin IPC --- ipcMain.handle('admin-get-stats', async () => { initBackend(); return backend ? await backend.getAdminStats() : null; }); ipcMain.handle('admin-get-users', async () => { initBackend(); return backend ? await backend.getAdminUsers() : []; }); ipcMain.handle('admin-delete-user', async (event, userId: string) => { initBackend(); if (backend) await backend.deleteUser(userId); return true; }); ipcMain.handle('admin-get-accounts', async () => { initBackend(); return backend ? await backend.getAdminAccounts() : []; }); ipcMain.handle('admin-remove-account', async (event, steamId: string) => { initBackend(); if (backend) await backend.forceRemoveAccount(steamId); return true; }); - ipcMain.handle('force-sync', async () => { await syncAccounts(true); return true; }); - -ipcMain.handle('update-app-icon', (event, themeName: string) => { - setAppIcon(themeName); - return true; -}); - +ipcMain.handle('update-app-icon', (event, themeName: string) => { setAppIcon(themeName); return true; }); ipcMain.handle('switch-account', async (event, loginName: string) => { if (!loginName) return false; try { - // PROACTIVE SYNC: Try to snag the freshest token before we kill Steam const accounts = store.get('accounts') as Account[]; const account = accounts.find(a => a.loginName === loginName); if (account && !account._id.startsWith('shared_')) { const freshConfig = steamClient.extractAccountConfig(loginName); - if (freshConfig) { - account.loginConfig = freshConfig; - account.sessionUpdatedAt = new Date().toISOString(); - if (backend) await backend.shareAccount(account); - store.set('accounts', accounts); - } + if (freshConfig) { account.loginConfig = freshConfig; account.sessionUpdatedAt = new Date().toISOString(); if (backend) await backend.shareAccount(account); store.set('accounts', accounts); } } - await killSteam(); - if (process.platform === 'win32') { const regBase = 'reg add "HKCU\\Software\\Valve\\Steam"'; - const commands = [ - `${regBase} /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`, - `${regBase} /v RememberPassword /t REG_DWORD /d 1 /f`, - `${regBase} /v AlreadyLoggedIn /t REG_DWORD /d 1 /f`, - `${regBase} /v WantsOfflineMode /t REG_DWORD /d 0 /f` - ]; + const commands = [`${regBase} /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`,`${regBase} /v RememberPassword /t REG_DWORD /d 1 /f`,`${regBase} /v AlreadyLoggedIn /t REG_DWORD /d 1 /f`,`${regBase} /v WantsOfflineMode /t REG_DWORD /d 0 /f`]; await new Promise((res, rej) => exec(commands.join(' && '), (e) => e ? rej(e) : res())); if (account && account.loginConfig) steamClient.injectAccountConfig(loginName, account.loginConfig); - } else if (process.platform === 'linux') { - await steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId); - } - startSteam(); - return true; + } else if (process.platform === 'linux') { await steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId); } + startSteam(); return true; } catch (e) { return false; } }); - ipcMain.handle('open-external', (event, url: string) => shell.openExternal(url)); - ipcMain.handle('open-steam-app-login', async () => { await killSteam(); if (process.platform === 'win32') { const clearReg = 'reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "" /f'; await new Promise((res) => exec(clearReg, () => res())); - } else if (process.platform === 'linux') { - await steamClient.setAutoLoginUser("", undefined, ""); - } + } else if (process.platform === 'linux') { await steamClient.setAutoLoginUser("", undefined, ""); } const command = process.platform === 'win32' ? 'start steam://open/login' : 'xdg-open steam://open/login'; - exec(command); - return true; + exec(command); return true; }); - ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => { const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new'; const loginSession = session.fromPartition(partitionId); @@ -724,10 +538,7 @@ ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => { } } return new Promise((resolve) => { - const loginWindow = new BrowserWindow({ - width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Steam', - webPreferences: { nodeIntegration: false, contextIsolation: true, partition: partitionId } - }); + const loginWindow = new BrowserWindow({ width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Steam', webPreferences: { nodeIntegration: false, contextIsolation: true, partition: partitionId } }); loginWindow.loadURL('https://steamcommunity.com/login/home/?goto=my/gcpd/730'); const checkCookie = setInterval(async () => { try { @@ -743,24 +554,11 @@ ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => { const accountIndex = accounts.findIndex(a => a.steamId === steamId); if (accountIndex !== -1) { const account = accounts[accountIndex]!; - account.steamLoginSecure = cookieString; account.autoCheckCooldown = true; account.authError = false; - account.sessionUpdatedAt = new Date().toISOString(); - if (account.loginName) { - const config = steamClient.extractAccountConfig(account.loginName); - if (config) account.loginConfig = config; - } - try { - const result = await scrapeCooldown(account.steamId, cookieString); - account.lastScrapeTime = new Date().toISOString(); - account.cooldownExpiresAt = result.isActive && result.expiresAt ? result.expiresAt.toISOString() : undefined; - } catch (e) { } - initBackend(); - if (backend) await backend.shareAccount(account); - store.set('accounts', accounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); - updateTrayMenu(); - loginWindow.close(); - resolve(true); + account.steamLoginSecure = cookieString; account.autoCheckCooldown = true; account.authError = false; account.sessionUpdatedAt = new Date().toISOString(); + if (account.loginName) { const config = steamClient.extractAccountConfig(account.loginName); if (config) account.loginConfig = config; } + try { const result = await scrapeCooldown(account.steamId, cookieString); account.lastScrapeTime = new Date().toISOString(); account.cooldownExpiresAt = result.isActive && result.expiresAt ? result.expiresAt.toISOString() : undefined; } catch (e) { } + initBackend(); if (backend) await backend.shareAccount(account); + store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); loginWindow.close(); resolve(true); } } }