feat/makepkg + project structure #12

Open
nvrl wants to merge 15 commits from feat/makepkg into main
Showing only changes of commit 3f4b1abc4b - Show all commits

View File

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