From c208ecea954eca5a75d528aa80257631b0a80cd4 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Sat, 21 Feb 2026 04:16:41 +0100 Subject: [PATCH 1/3] feat: implement manual per-account refresh for instant ban and cooldown updates --- frontend/electron/main.ts | 102 ++++++++++++++++++++--------- frontend/electron/preload.ts | 1 + frontend/src/hooks/useAccounts.tsx | 9 ++- frontend/src/pages/Dashboard.tsx | 16 ++++- 4 files changed, 93 insertions(+), 35 deletions(-) diff --git a/frontend/electron/main.ts b/frontend/electron/main.ts index 28f25f7..8413f1e 100644 --- a/frontend/electron/main.ts +++ b/frontend/electron/main.ts @@ -188,6 +188,57 @@ const handleSwitchAccount = async (loginName: string) => { } catch (e) { return false; } }; +// --- Scraper Helper --- +const scrapeAccountData = async (account: Account) => { + const now = new Date(); + try { + // 1. Refresh Basic Profile & Bans + const profile = await fetchProfileData(account.steamId, account.steamLoginSecure); + const bans = await scrapeBanStatus(profile.profileUrl, account.steamLoginSecure); + + account.personaName = profile.personaName; + account.profileUrl = profile.profileUrl; + account.vacBanned = bans.vacBanned; + account.gameBans = bans.gameBans; + account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none'; + account.lastBanCheck = now.toISOString(); + + if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) { + account.avatar = profile.avatar; + const localPath = await downloadAvatar(account.steamId, profile.avatar); + if (localPath) account.localAvatar = localPath; + } + + // 2. Refresh Cooldowns if session is active + if (account.steamLoginSecure) { + try { + const result = await scrapeCooldown(account.steamId, account.steamLoginSecure); + account.authError = false; + account.lastScrapeTime = now.toISOString(); + if (result.isActive) { + account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString(); + if (backend) await backend.pushCooldown(account.steamId, account.cooldownExpiresAt); + } else { + account.cooldownExpiresAt = undefined; + if (backend) await backend.pushCooldown(account.steamId, undefined); + } + } catch (e: any) { + if (e.message.includes('cookie') || e.message.includes('Sign In')) account.authError = true; + } + } + + // 3. Share updated state with backend + 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; + } +}; + // --- Sync Worker --- const syncAccounts = async () => { initBackend(); @@ -244,30 +295,13 @@ const syncAccounts = async () => { const now = new Date(); // OPTIMIZATION: Ensure ALL authenticated accounts are shared with the server on every sync cycle - // this guarantees that even if a push failed previously, it will be reconciled now. if (backend && !account._id.startsWith('shared_')) { - console.log(`[Sync] Reconciling account with server: ${account.personaName}`); await backend.shareAccount(account); } const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0); if ((now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName) { - const profile = await fetchProfileData(account.steamId, account.steamLoginSecure); - const bans = await scrapeBanStatus(profile.profileUrl, account.steamLoginSecure); - account.personaName = profile.personaName; account.profileUrl = profile.profileUrl; - account.vacBanned = bans.vacBanned; account.gameBans = bans.gameBans; - account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none'; - account.lastBanCheck = now.toISOString(); - if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) { - account.avatar = profile.avatar; - const localPath = await downloadAvatar(account.steamId, profile.avatar); - if (localPath) account.localAvatar = localPath; - } - if (account.loginName) { - const config = steamClient.extractAccountConfig(account.loginName); - if (config) { account.loginConfig = config; account.sessionUpdatedAt = new Date().toISOString(); } - } - if (backend) await backend.shareAccount(account); + await scrapeAccountData(account); scrapeChanges = true; } @@ -276,20 +310,8 @@ const syncAccounts = async () => { const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0); if ((now.getTime() - lastScrape.getTime()) / 3600000 > 8) { await new Promise(r => setTimeout(r, Math.floor(Math.random() * 60000) + 5000)); - try { - const result = await scrapeCooldown(account.steamId, account.steamLoginSecure); - account.authError = false; account.lastScrapeTime = new Date().toISOString(); - if (result.isActive) { - account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString(); - if (backend) await backend.pushCooldown(account.steamId, account.cooldownExpiresAt); - } else if (account.cooldownExpiresAt) { - account.cooldownExpiresAt = undefined; - if (backend) await backend.pushCooldown(account.steamId, undefined); - } - scrapeChanges = true; - } catch (e: any) { - if (e.message.includes('cookie') || e.message.includes('Sign In')) { account.authError = true; scrapeChanges = true; } - } + await scrapeAccountData(account); + scrapeChanges = true; } } } catch (error) { } @@ -437,6 +459,22 @@ ipcMain.handle('login-to-server', async () => { ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId })); ipcMain.handle('sync-now', async () => { await syncAccounts(); 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; + + console.log(`[Main] Manually triggering scrape for ${account.personaName}...`); + const success = await scrapeAccountData(account); + 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(); diff --git a/frontend/electron/preload.ts b/frontend/electron/preload.ts index c8c8385..5da78f1 100644 --- a/frontend/electron/preload.ts +++ b/frontend/electron/preload.ts @@ -19,6 +19,7 @@ contextBridge.exposeInMainWorld('electronAPI', { loginToServer: () => ipcRenderer.invoke('login-to-server'), getServerUserInfo: () => ipcRenderer.invoke('get-server-user-info'), syncNow: () => ipcRenderer.invoke('sync-now'), + scrapeAccount: (steamId: string) => ipcRenderer.invoke('scrape-account', steamId), getCommunityAccounts: () => ipcRenderer.invoke('get-community-accounts'), getServerUsers: () => ipcRenderer.invoke('get-server-users'), diff --git a/frontend/src/hooks/useAccounts.tsx b/frontend/src/hooks/useAccounts.tsx index aed28de..e5722e5 100644 --- a/frontend/src/hooks/useAccounts.tsx +++ b/frontend/src/hooks/useAccounts.tsx @@ -49,6 +49,7 @@ interface AccountsContextType { updateServerConfig: (config: Partial) => Promise; loginToServer: () => Promise; syncNow: () => Promise; + scrapeAccount: (steamId: string) => Promise; getCommunityAccounts: () => Promise; getServerUsers: () => Promise; refreshAccounts: (showLoading?: boolean) => Promise; @@ -114,6 +115,12 @@ export const AccountsProvider: React.FC<{ children: React.ReactNode }> = ({ chil } }; + const scrapeAccount = async (steamId: string) => { + const success = await (window as any).electronAPI.scrapeAccount(steamId); + if (success) await syncNow(); + return success; + }; + const addAccount = async (data: { identifier: string }) => { await (window as any).electronAPI.addAccount(data); await refreshAccounts(); @@ -194,7 +201,7 @@ export const AccountsProvider: React.FC<{ children: React.ReactNode }> = ({ chil accounts, serverConfig, isLoading, isSyncing, addAccount, updateAccount, deleteAccount, switchAccount, openSteamAppLogin, openSteamLogin, updateServerConfig, loginToServer, getCommunityAccounts, getServerUsers, shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, syncNow, refreshAccounts, - adminGetStats, adminGetUsers, adminDeleteUser, adminGetAccounts, adminRemoveAccount + scrapeAccount, adminGetStats, adminGetUsers, adminDeleteUser, adminGetAccounts, adminRemoveAccount }}> {children} diff --git a/frontend/src/pages/Dashboard.tsx b/frontend/src/pages/Dashboard.tsx index 16d6dee..b1e25f4 100644 --- a/frontend/src/pages/Dashboard.tsx +++ b/frontend/src/pages/Dashboard.tsx @@ -376,11 +376,12 @@ const AccountRow: React.FC<{ onSwitch: (login: string) => void, onAuth: () => void }> = ({ account, onDelete, onSwitch, onAuth }) => { - const { shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, getServerUsers, serverConfig } = useAccounts(); + const { shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, getServerUsers, serverConfig, scrapeAccount } = useAccounts(); const [timeLeft, setTimeLeft] = useState(null); const [isShareOpen, setIsShareOpen] = useState(false); const [targetUserId, setTargetUserId] = useState(''); const [isSharing, setIsSharing] = useState(false); + const [isRefreshing, setIsRefreshing] = useState(false); const [serverUsers, setServerUsers] = useState([]); const cooldownDate = account?.cooldownExpiresAt ? new Date(account.cooldownExpiresAt) : null; @@ -404,6 +405,12 @@ const AccountRow: React.FC<{ const [imgSrc, setImgSrc] = useState(avatarSrc); useEffect(() => { setImgSrc(avatarSrc); }, [avatarSrc]); + const handleRefresh = async () => { + setIsRefreshing(true); + await scrapeAccount(account.steamId); + setIsRefreshing(false); + }; + const handleOpenShare = async () => { setIsShareOpen(true); try { @@ -522,7 +529,12 @@ const AccountRow: React.FC<{ {account.steamLoginSecure && !account.authError ? : (account.authError ? : )} {account.steamLoginSecure && !account.authError && ( - TRACKING + + TRACKING + + {isRefreshing ? : } + + )} From 83dbfce8b21781ebbea8a46af40a093cc58655d8 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Sat, 21 Feb 2026 04:20:47 +0100 Subject: [PATCH 2/3] fix: implement non-blocking split-phase synchronization to resolve UI hanging on sync --- frontend/electron/main.ts | 195 ++++++++++++-------------------------- 1 file changed, 61 insertions(+), 134 deletions(-) diff --git a/frontend/electron/main.ts b/frontend/electron/main.ts index 8413f1e..ab9c6dd 100644 --- a/frontend/electron/main.ts +++ b/frontend/electron/main.ts @@ -40,6 +40,7 @@ interface Account { cooldownExpiresAt?: string; authError?: boolean; notes?: string; + sharedWith?: any[]; } interface ServerConfig { @@ -48,6 +49,7 @@ interface ServerConfig { serverSteamId?: string; enabled: boolean; theme?: string; + isAdmin?: boolean; } // --- App State --- @@ -94,44 +96,24 @@ const createTray = () => { const assetsDir = path.join(__dirname, '..', 'assets-build'); const possibleIcons = ['icon.svg', 'icon.png']; let iconPath = ''; - for (const name of possibleIcons) { const fullPath = path.join(assetsDir, name); - if (fs.existsSync(fullPath)) { - iconPath = fullPath; - break; - } + if (fs.existsSync(fullPath)) { iconPath = fullPath; break; } } - - console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`); - - if (!iconPath) { - console.warn(`[Tray] FAILED: No valid icon found in ${assetsDir}`); - return; - } - + if (!iconPath) return; try { const icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 }); tray = new Tray(icon); tray.setToolTip('Ultimate Ban Tracker'); - tray.on('click', () => { - if (mainWindow) { - mainWindow.show(); - mainWindow.focus(); - } - }); + tray.on('click', () => { if (mainWindow) { mainWindow.show(); mainWindow.focus(); } }); updateTrayMenu(); - console.log(`[Tray] Successfully initialized`); - } catch (e: any) { - console.error(`[Tray] Critical error during initialization: ${e.message}`); - } + } catch (e) { } }; const updateTrayMenu = () => { if (!tray) return; const accounts = store.get('accounts') as Account[]; const config = store.get('serverConfig'); - const contextMenu = Menu.buildFromTemplate([ { label: `Ultimate Ban Tracker v${app.getVersion()}`, enabled: false }, { type: 'separator' }, @@ -143,16 +125,11 @@ const updateTrayMenu = () => { click: () => handleSwitchAccount(acc.loginName) })) : [{ label: 'No accounts found', enabled: false }] }, - { - label: 'Sync Now', - enabled: !!config?.enabled, - click: () => syncAccounts() - }, + { label: 'Sync Now', enabled: !!config?.enabled, click: () => syncAccounts(true) }, { type: 'separator' }, { label: 'Show Dashboard', click: () => { if (mainWindow) mainWindow.show(); } }, { label: 'Quit', click: () => { (app as any).isQuitting = true; app.quit(); } } ]); - tray.setContextMenu(contextMenu); }; @@ -192,29 +169,21 @@ const handleSwitchAccount = async (loginName: string) => { const scrapeAccountData = async (account: Account) => { const now = new Date(); try { - // 1. Refresh Basic Profile & Bans const profile = await fetchProfileData(account.steamId, account.steamLoginSecure); const bans = await scrapeBanStatus(profile.profileUrl, account.steamLoginSecure); - - account.personaName = profile.personaName; - account.profileUrl = profile.profileUrl; - account.vacBanned = bans.vacBanned; - account.gameBans = bans.gameBans; + account.personaName = profile.personaName; account.profileUrl = profile.profileUrl; + account.vacBanned = bans.vacBanned; account.gameBans = bans.gameBans; account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none'; account.lastBanCheck = now.toISOString(); - if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) { account.avatar = profile.avatar; const localPath = await downloadAvatar(account.steamId, profile.avatar); if (localPath) account.localAvatar = localPath; } - - // 2. Refresh Cooldowns if session is active if (account.steamLoginSecure) { try { const result = await scrapeCooldown(account.steamId, account.steamLoginSecure); - account.authError = false; - account.lastScrapeTime = now.toISOString(); + account.authError = false; account.lastScrapeTime = now.toISOString(); if (result.isActive) { account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString(); if (backend) await backend.pushCooldown(account.steamId, account.cooldownExpiresAt); @@ -226,12 +195,9 @@ const scrapeAccountData = async (account: Account) => { if (e.message.includes('cookie') || e.message.includes('Sign In')) account.authError = true; } } - - // 3. Share updated state with backend if (backend && !account._id.startsWith('shared_')) { await backend.shareAccount(account); } - return true; } catch (e) { console.error(`[Scraper] Failed to scrape ${account.personaName}:`, e); @@ -240,7 +206,8 @@ const scrapeAccountData = async (account: Account) => { }; // --- Sync Worker --- -const syncAccounts = async () => { +const syncAccounts = async (isManual = false) => { + console.log(`[Sync] Phase 1: Pulling from server...`); initBackend(); let accounts = store.get('accounts') as Account[]; let hasChanges = false; @@ -252,12 +219,13 @@ const syncAccounts = async () => { const exists = accounts.find(a => a.steamId === s.steamId); if (!exists) { accounts.push({ - _id: `shared_${s.steamId}`, - steamId: s.steamId, personaName: s.personaName, avatar: s.avatar, profileUrl: s.profileUrl, - vacBanned: s.vacBanned, gameBans: s.gameBans, cooldownExpiresAt: s.cooldownExpiresAt, - loginName: s.loginName || '', steamLoginSecure: s.steamLoginSecure, loginConfig: s.loginConfig, - sessionUpdatedAt: s.sessionUpdatedAt, autoCheckCooldown: !!s.steamLoginSecure, - status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString() + _id: `shared_${s.steamId}`, steamId: s.steamId, personaName: s.personaName, + avatar: s.avatar, profileUrl: s.profileUrl, vacBanned: s.vacBanned, + gameBans: s.gameBans, cooldownExpiresAt: s.cooldownExpiresAt, + loginName: s.loginName || '', steamLoginSecure: s.steamLoginSecure, + loginConfig: s.loginConfig, sessionUpdatedAt: s.sessionUpdatedAt, + autoCheckCooldown: !!s.steamLoginSecure, status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none', + lastBanCheck: new Date().toISOString(), sharedWith: s.sharedWith }); hasChanges = true; } else { @@ -274,6 +242,10 @@ const syncAccounts = async () => { exists.cooldownExpiresAt = s.cooldownExpiresAt; hasChanges = true; } + if (JSON.stringify(exists.sharedWith) !== JSON.stringify(s.sharedWith)) { + exists.sharedWith = s.sharedWith; + hasChanges = true; + } } } } catch (e) { } @@ -285,47 +257,39 @@ const syncAccounts = async () => { updateTrayMenu(); } - if (accounts.length === 0) return; - - const updatedAccounts = [...accounts]; - let scrapeChanges = false; - - for (const account of updatedAccounts) { - try { - const now = new Date(); - - // OPTIMIZATION: Ensure ALL authenticated accounts are shared with the server on every sync cycle - if (backend && !account._id.startsWith('shared_')) { - await backend.shareAccount(account); - } - - const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0); - if ((now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName) { - await scrapeAccountData(account); - scrapeChanges = true; - } - - if (account.autoCheckCooldown && account.steamLoginSecure) { - if (account.cooldownExpiresAt && new Date(account.cooldownExpiresAt) > now) continue; + // Phase 2: Background Scrapes + 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) { + try { + const now = new Date(); + if (backend && !account._id.startsWith('shared_')) await backend.shareAccount(account); + const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0); const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0); - if ((now.getTime() - lastScrape.getTime()) / 3600000 > 8) { - await new Promise(r => setTimeout(r, Math.floor(Math.random() * 60000) + 5000)); - await scrapeAccountData(account); - scrapeChanges = true; - } - } - } catch (error) { } - } + const needsMetadata = (now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName; + const needsCooldown = account.autoCheckCooldown && account.steamLoginSecure && (now.getTime() - lastScrape.getTime()) / 3600000 > 8; - if (scrapeChanges) { - store.set('accounts', updatedAccounts); - if (mainWindow) mainWindow.webContents.send('accounts-updated', updatedAccounts); - updateTrayMenu(); - } + 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 (isManual) await runScrapes(); else runScrapes(); }; const scheduleNextSync = () => { - setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, isDev ? 120000 : 1800000); + setTimeout(async () => { await syncAccounts(false); scheduleNextSync(); }, isDev ? 300000 : 1800000); }; // --- Discovery --- @@ -364,28 +328,21 @@ const handleLocalAccountsFound = async (localAccounts: LocalSteamAccount[]) => { } }; -// --- Main Window Creation --- +// --- 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 } }); - mainWindow.setMenu(null); - mainWindow.on('close', (event) => { - if (!(app as any).isQuitting) { - event.preventDefault(); - mainWindow?.hide(); - } + 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 Lifecycle --- app.whenReady().then(() => { protocol.handle('steam-resource', (request) => { let rawPath = decodeURIComponent(request.url.replace('steam-resource://', '')); @@ -394,11 +351,10 @@ app.whenReady().then(() => { 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, 5000); + setTimeout(() => syncAccounts(false), 5000); scheduleNextSync(); steamClient.startWatching(handleLocalAccountsFound); }); @@ -423,19 +379,17 @@ ipcMain.handle('login-to-server', async () => { 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 Ban Tracker Server', + 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; + let serverSteamId = undefined; let isAdmin = false; try { const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64').toString()); - serverSteamId = payload.steamId; - isAdmin = !!payload.isAdmin; + serverSteamId = payload.steamId; isAdmin = !!payload.isAdmin; } catch (e) {} const current = store.get('serverConfig'); store.set('serverConfig', { ...current, token, serverSteamId, isAdmin, enabled: true }); @@ -458,14 +412,12 @@ ipcMain.handle('login-to-server', async () => { }); ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId })); -ipcMain.handle('sync-now', async () => { await syncAccounts(); return true; }); +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; - - console.log(`[Main] Manually triggering scrape for ${account.personaName}...`); const success = await scrapeAccountData(account); if (success) { store.set('accounts', accounts); @@ -491,7 +443,7 @@ ipcMain.handle('add-account', async (event, { identifier }) => { loginName: existing.loginName || '', steamLoginSecure: existing.steamLoginSecure, loginConfig: existing.loginConfig, sessionUpdatedAt: existing.sessionUpdatedAt, autoCheckCooldown: !!existing.steamLoginSecure, status: (existing.vacBanned || existing.gameBans > 0) ? 'banned' : 'none', - lastBanCheck: new Date().toISOString() + lastBanCheck: new Date().toISOString(), sharedWith: existing.sharedWith }; store.set('accounts', [...accounts, newAccount]); updateTrayMenu(); @@ -565,60 +517,35 @@ ipcMain.handle('switch-account', async (event, loginName: string) => await handl ipcMain.handle('open-external', (event, url: string) => shell.openExternal(url)); ipcMain.handle('open-steam-app-login', async () => { - console.log('[SteamClient] Preparing for fresh login...'); await killSteam(); - if (process.platform === 'win32') { - // Clear auto-login registry 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') { - // On Linux we can use the steamClient helper to set an empty user await steamClient.setAutoLoginUser("", undefined, ""); } - const command = process.platform === 'win32' ? 'start steam://open/login' : 'xdg-open steam://open/login'; exec(command); return true; }); ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => { - // Use a unique partition per account to prevent session bleeding const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new'; const loginSession = session.fromPartition(partitionId); - - // If adding a brand new account, explicitly clear previous trash - if (!expectedSteamId) { - console.log('[Auth] Clearing session for new account login...'); - await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] }); - } - - // If we have an existing cookie string for this account, pre-inject it + if (!expectedSteamId) await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] }); if (expectedSteamId) { const accounts = store.get('accounts') as Account[]; const account = accounts.find(a => a.steamId === expectedSteamId); if (account?.steamLoginSecure) { - console.log(`[Auth] Pre-injecting existing cookies for ${account.personaName}...`); const cookiePairs = account.steamLoginSecure.split(';').map(c => c.trim()); for (const pair of cookiePairs) { const [name, value] = pair.split('='); if (name && value) { - try { - await loginSession.cookies.set({ - url: 'https://steamcommunity.com', - domain: 'steamcommunity.com', - name: name, - value: value, - path: '/', - secure: true, - httpOnly: name.includes('Secure') - }); - } catch (e) {} + try { await loginSession.cookies.set({ url: 'https://steamcommunity.com', domain: 'steamcommunity.com', name, value, path: '/', secure: true, httpOnly: name.includes('Secure') }); } catch (e) {} } } } } - return new Promise((resolve) => { const loginWindow = new BrowserWindow({ width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Steam', From 34a71de2dc72f20b9a7760169ac1a88ac97b8cf5 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Sat, 21 Feb 2026 04:24:09 +0100 Subject: [PATCH 3/3] fix: ensure assets-build is included in production bundle and implement robust tray icon path resolution for AppImage --- frontend/dist-electron/main.js | 245 +++++++++++++++--------------- frontend/dist-electron/preload.js | 1 + frontend/electron/main.ts | 43 +++++- frontend/package.json | 3 +- 4 files changed, 159 insertions(+), 133 deletions(-) diff --git a/frontend/dist-electron/main.js b/frontend/dist-electron/main.js index 44ef93c..b3e288c 100644 --- a/frontend/dist-electron/main.js +++ b/frontend/dist-electron/main.js @@ -70,27 +70,19 @@ const createTray = () => { break; } } - console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`); - if (!iconPath) { - console.warn(`[Tray] FAILED: No valid icon found in ${assetsDir}`); + if (!iconPath) return; - } try { const icon = electron_1.nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 }); tray = new electron_1.Tray(icon); tray.setToolTip('Ultimate Ban Tracker'); - tray.on('click', () => { - if (mainWindow) { - mainWindow.show(); - mainWindow.focus(); - } - }); + tray.on('click', () => { if (mainWindow) { + mainWindow.show(); + mainWindow.focus(); + } }); updateTrayMenu(); - console.log(`[Tray] Successfully initialized`); - } - catch (e) { - console.error(`[Tray] Critical error during initialization: ${e.message}`); } + catch (e) { } }; const updateTrayMenu = () => { if (!tray) @@ -108,11 +100,7 @@ const updateTrayMenu = () => { click: () => handleSwitchAccount(acc.loginName) })) : [{ label: 'No accounts found', enabled: false }] }, - { - label: 'Sync Now', - enabled: !!config?.enabled, - click: () => syncAccounts() - }, + { label: 'Sync Now', enabled: !!config?.enabled, click: () => syncAccounts(true) }, { type: 'separator' }, { label: 'Show Dashboard', click: () => { if (mainWindow) mainWindow.show(); } }, @@ -155,8 +143,58 @@ const handleSwitchAccount = async (loginName) => { return false; } }; +// --- Scraper Helper --- +const scrapeAccountData = async (account) => { + const now = new Date(); + try { + const profile = await (0, steam_web_1.fetchProfileData)(account.steamId, account.steamLoginSecure); + const bans = await (0, steam_web_1.scrapeBanStatus)(profile.profileUrl, account.steamLoginSecure); + account.personaName = profile.personaName; + account.profileUrl = profile.profileUrl; + account.vacBanned = bans.vacBanned; + account.gameBans = bans.gameBans; + account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none'; + account.lastBanCheck = now.toISOString(); + if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) { + account.avatar = profile.avatar; + const localPath = await downloadAvatar(account.steamId, profile.avatar); + if (localPath) + account.localAvatar = localPath; + } + if (account.steamLoginSecure) { + try { + const result = await (0, scraper_1.scrapeCooldown)(account.steamId, account.steamLoginSecure); + account.authError = false; + account.lastScrapeTime = now.toISOString(); + if (result.isActive) { + account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString(); + if (backend) + await backend.pushCooldown(account.steamId, account.cooldownExpiresAt); + } + else { + account.cooldownExpiresAt = undefined; + if (backend) + await backend.pushCooldown(account.steamId, undefined); + } + } + catch (e) { + if (e.message.includes('cookie') || e.message.includes('Sign In')) + 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; + } +}; // --- Sync Worker --- -const syncAccounts = async () => { +const syncAccounts = async (isManual = false) => { + console.log(`[Sync] Phase 1: Pulling from server...`); initBackend(); let accounts = store.get('accounts'); let hasChanges = false; @@ -167,12 +205,13 @@ const syncAccounts = async () => { const exists = accounts.find(a => a.steamId === s.steamId); if (!exists) { accounts.push({ - _id: `shared_${s.steamId}`, - steamId: s.steamId, personaName: s.personaName, avatar: s.avatar, profileUrl: s.profileUrl, - vacBanned: s.vacBanned, gameBans: s.gameBans, cooldownExpiresAt: s.cooldownExpiresAt, - loginName: s.loginName || '', steamLoginSecure: s.steamLoginSecure, loginConfig: s.loginConfig, - sessionUpdatedAt: s.sessionUpdatedAt, autoCheckCooldown: !!s.steamLoginSecure, - status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString() + _id: `shared_${s.steamId}`, steamId: s.steamId, personaName: s.personaName, + avatar: s.avatar, profileUrl: s.profileUrl, vacBanned: s.vacBanned, + gameBans: s.gameBans, cooldownExpiresAt: s.cooldownExpiresAt, + loginName: s.loginName || '', steamLoginSecure: s.steamLoginSecure, + loginConfig: s.loginConfig, sessionUpdatedAt: s.sessionUpdatedAt, + autoCheckCooldown: !!s.steamLoginSecure, status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none', + lastBanCheck: new Date().toISOString(), sharedWith: s.sharedWith }); hasChanges = true; } @@ -196,6 +235,10 @@ const syncAccounts = async () => { exists.cooldownExpiresAt = s.cooldownExpiresAt; hasChanges = true; } + if (JSON.stringify(exists.sharedWith) !== JSON.stringify(s.sharedWith)) { + exists.sharedWith = s.sharedWith; + hasChanges = true; + } } } } @@ -207,88 +250,44 @@ const syncAccounts = async () => { mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); } - if (accounts.length === 0) - return; - const updatedAccounts = [...accounts]; - let scrapeChanges = false; - for (const account of updatedAccounts) { - try { - const now = new Date(); - // OPTIMIZATION: Ensure ALL authenticated accounts are shared with the server on every sync cycle - // this guarantees that even if a push failed previously, it will be reconciled now. - if (backend && !account._id.startsWith('shared_')) { - console.log(`[Sync] Reconciling account with server: ${account.personaName}`); - await backend.shareAccount(account); - } - const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0); - if ((now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName) { - const profile = await (0, steam_web_1.fetchProfileData)(account.steamId, account.steamLoginSecure); - const bans = await (0, steam_web_1.scrapeBanStatus)(profile.profileUrl, account.steamLoginSecure); - account.personaName = profile.personaName; - account.profileUrl = profile.profileUrl; - account.vacBanned = bans.vacBanned; - account.gameBans = bans.gameBans; - account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none'; - account.lastBanCheck = now.toISOString(); - if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) { - account.avatar = profile.avatar; - const localPath = await downloadAvatar(account.steamId, profile.avatar); - if (localPath) - account.localAvatar = localPath; - } - if (account.loginName) { - const config = steam_client_1.steamClient.extractAccountConfig(account.loginName); - if (config) { - account.loginConfig = config; - account.sessionUpdatedAt = new Date().toISOString(); - } - } - if (backend) + // Phase 2: Background Scrapes + const runScrapes = async () => { + console.log(`[Sync] Phase 2: Starting background checks for ${accounts.length} accounts...`); + const currentAccounts = [...store.get('accounts')]; + let scrapeChanges = false; + for (const account of currentAccounts) { + try { + const now = new Date(); + if (backend && !account._id.startsWith('shared_')) await backend.shareAccount(account); - scrapeChanges = true; - } - if (account.autoCheckCooldown && account.steamLoginSecure) { - if (account.cooldownExpiresAt && new Date(account.cooldownExpiresAt) > now) - continue; + const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0); const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0); - if ((now.getTime() - lastScrape.getTime()) / 3600000 > 8) { - await new Promise(r => setTimeout(r, Math.floor(Math.random() * 60000) + 5000)); - try { - const result = await (0, scraper_1.scrapeCooldown)(account.steamId, account.steamLoginSecure); - account.authError = false; - account.lastScrapeTime = new Date().toISOString(); - if (result.isActive) { - account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString(); - if (backend) - await backend.pushCooldown(account.steamId, account.cooldownExpiresAt); - } - else if (account.cooldownExpiresAt) { - account.cooldownExpiresAt = undefined; - if (backend) - await backend.pushCooldown(account.steamId, undefined); - } + 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 (e) { - if (e.message.includes('cookie') || e.message.includes('Sign In')) { - account.authError = true; - scrapeChanges = true; - } - } } } + catch (error) { } } - catch (error) { } - } - if (scrapeChanges) { - store.set('accounts', updatedAccounts); - if (mainWindow) - mainWindow.webContents.send('accounts-updated', updatedAccounts); - updateTrayMenu(); - } + if (scrapeChanges) { + store.set('accounts', currentAccounts); + if (mainWindow) + mainWindow.webContents.send('accounts-updated', currentAccounts); + updateTrayMenu(); + } + console.log('[Sync] Sync cycle finished.'); + }; + if (isManual) + await runScrapes(); + else + runScrapes(); }; const scheduleNextSync = () => { - setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, isDev ? 120000 : 1800000); + setTimeout(async () => { await syncAccounts(false); scheduleNextSync(); }, isDev ? 300000 : 1800000); }; // --- Discovery --- const addingAccounts = new Set(); @@ -332,7 +331,7 @@ const handleLocalAccountsFound = async (localAccounts) => { updateTrayMenu(); } }; -// --- Main Window Creation --- +// --- Main Window --- function createWindow() { mainWindow = new electron_1.BrowserWindow({ width: 1280, height: 800, title: "Ultimate Ban Tracker", backgroundColor: '#171a21', autoHideMenuBar: true, @@ -351,7 +350,6 @@ function createWindow() { else mainWindow.loadFile(path_1.default.join(__dirname, '..', 'dist', 'index.html')); } -// --- App Lifecycle --- electron_1.app.whenReady().then(() => { electron_1.protocol.handle('steam-resource', (request) => { let rawPath = decodeURIComponent(request.url.replace('steam-resource://', '')); @@ -370,7 +368,7 @@ electron_1.app.whenReady().then(() => { createWindow(); createTray(); initBackend(); - setTimeout(syncAccounts, 5000); + setTimeout(() => syncAccounts(false), 5000); scheduleNextSync(); steam_client_1.steamClient.startWatching(handleLocalAccountsFound); }); @@ -397,7 +395,7 @@ electron_1.ipcMain.handle('login-to-server', async () => { return false; return new Promise((resolve) => { const authWindow = new electron_1.BrowserWindow({ - width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Ban Tracker Server', + width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Server', webPreferences: { nodeIntegration: false, contextIsolation: true } }); authWindow.loadURL(`${config.url}/auth/steam`); @@ -439,7 +437,21 @@ electron_1.ipcMain.handle('login-to-server', async () => { }); }); electron_1.ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId })); -electron_1.ipcMain.handle('sync-now', async () => { await syncAccounts(); return true; }); +electron_1.ipcMain.handle('sync-now', async () => { await syncAccounts(true); return true; }); +electron_1.ipcMain.handle('scrape-account', async (event, steamId) => { + const accounts = store.get('accounts'); + 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(); + } + return success; +}); electron_1.ipcMain.handle('add-account', async (event, { identifier }) => { try { initBackend(); @@ -457,7 +469,7 @@ electron_1.ipcMain.handle('add-account', async (event, { identifier }) => { loginName: existing.loginName || '', steamLoginSecure: existing.steamLoginSecure, loginConfig: existing.loginConfig, sessionUpdatedAt: existing.sessionUpdatedAt, autoCheckCooldown: !!existing.steamLoginSecure, status: (existing.vacBanned || existing.gameBans > 0) ? 'banned' : 'none', - lastBanCheck: new Date().toISOString() + lastBanCheck: new Date().toISOString(), sharedWith: existing.sharedWith }; store.set('accounts', [...accounts, newAccount]); updateTrayMenu(); @@ -535,15 +547,12 @@ electron_1.ipcMain.handle('admin-remove-account', async (event, steamId) => { in electron_1.ipcMain.handle('switch-account', async (event, loginName) => await handleSwitchAccount(loginName)); electron_1.ipcMain.handle('open-external', (event, url) => electron_1.shell.openExternal(url)); electron_1.ipcMain.handle('open-steam-app-login', async () => { - console.log('[SteamClient] Preparing for fresh login...'); await killSteam(); if (process.platform === 'win32') { - // Clear auto-login registry const clearReg = 'reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "" /f'; await new Promise((res) => (0, child_process_1.exec)(clearReg, () => res())); } else if (process.platform === 'linux') { - // On Linux we can use the steamClient helper to set an empty user await steam_client_1.steamClient.setAutoLoginUser("", undefined, ""); } const command = process.platform === 'win32' ? 'start steam://open/login' : 'xdg-open steam://open/login'; @@ -551,34 +560,20 @@ electron_1.ipcMain.handle('open-steam-app-login', async () => { return true; }); electron_1.ipcMain.handle('open-steam-login', async (event, expectedSteamId) => { - // Use a unique partition per account to prevent session bleeding const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new'; const loginSession = electron_1.session.fromPartition(partitionId); - // If adding a brand new account, explicitly clear previous trash - if (!expectedSteamId) { - console.log('[Auth] Clearing session for new account login...'); + if (!expectedSteamId) await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] }); - } - // If we have an existing cookie string for this account, pre-inject it if (expectedSteamId) { const accounts = store.get('accounts'); const account = accounts.find(a => a.steamId === expectedSteamId); if (account?.steamLoginSecure) { - console.log(`[Auth] Pre-injecting existing cookies for ${account.personaName}...`); const cookiePairs = account.steamLoginSecure.split(';').map(c => c.trim()); for (const pair of cookiePairs) { const [name, value] = pair.split('='); if (name && value) { try { - await loginSession.cookies.set({ - url: 'https://steamcommunity.com', - domain: 'steamcommunity.com', - name: name, - value: value, - path: '/', - secure: true, - httpOnly: name.includes('Secure') - }); + await loginSession.cookies.set({ url: 'https://steamcommunity.com', domain: 'steamcommunity.com', name, value, path: '/', secure: true, httpOnly: name.includes('Secure') }); } catch (e) { } } diff --git a/frontend/dist-electron/preload.js b/frontend/dist-electron/preload.js index 854d74d..4c648d2 100644 --- a/frontend/dist-electron/preload.js +++ b/frontend/dist-electron/preload.js @@ -19,6 +19,7 @@ electron_1.contextBridge.exposeInMainWorld('electronAPI', { loginToServer: () => electron_1.ipcRenderer.invoke('login-to-server'), getServerUserInfo: () => electron_1.ipcRenderer.invoke('get-server-user-info'), syncNow: () => electron_1.ipcRenderer.invoke('sync-now'), + scrapeAccount: (steamId) => electron_1.ipcRenderer.invoke('scrape-account', steamId), getCommunityAccounts: () => electron_1.ipcRenderer.invoke('get-community-accounts'), getServerUsers: () => electron_1.ipcRenderer.invoke('get-server-users'), // Admin API diff --git a/frontend/electron/main.ts b/frontend/electron/main.ts index ab9c6dd..7907be7 100644 --- a/frontend/electron/main.ts +++ b/frontend/electron/main.ts @@ -93,14 +93,43 @@ const initBackend = () => { // --- System Tray --- const createTray = () => { - const assetsDir = path.join(__dirname, '..', 'assets-build'); - const possibleIcons = ['icon.svg', 'icon.png']; - let iconPath = ''; - for (const name of possibleIcons) { - const fullPath = path.join(assetsDir, name); - if (fs.existsSync(fullPath)) { iconPath = fullPath; break; } + // Try to find the icon in various standard locations + const possiblePaths = [ + path.join(__dirname, '..', 'assets-build'), // Dev + path.join(process.resourcesPath, 'assets-build'), // Packaged (External) + path.join(app.getAppPath(), 'dist', 'assets-build'), // Packaged (Internal dist) + path.join(app.getAppPath(), 'assets-build') // Packaged (Internal root) + ]; + + let assetsDir = ''; + for (const p of possiblePaths) { + if (fs.existsSync(p)) { + assetsDir = p; + break; + } } - if (!iconPath) return; + + const possibleIcons = ['icon.png', 'icon.svg']; + let iconPath = ''; + + if (assetsDir) { + for (const name of possibleIcons) { + const fullPath = path.join(assetsDir, name); + if (fs.existsSync(fullPath)) { + iconPath = fullPath; + break; + } + } + } + + console.log(`[Tray] Resolved assets directory: ${assetsDir || 'NOT FOUND'}`); + console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`); + + if (!iconPath) { + console.warn(`[Tray] FAILED: No valid icon found in searched paths.`); + return; + } + try { const icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 }); tray = new Tray(icon); diff --git a/frontend/package.json b/frontend/package.json index 9717162..0ddea69 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -28,7 +28,8 @@ }, "files": [ "dist/**/*", - "dist-electron/**/*" + "dist-electron/**/*", + "assets-build/**/*" ], "linux": { "target": [