const { app, BrowserWindow, ipcMain } = require('electron'); const path = require('path'); const { startServer } = require('./server'); const { createTray } = require('./tray'); const PORT = 9095; const OVERLAY_DIR = path.join(__dirname, '..', 'overlay'); const YT_MUSIC_URL = 'https://music.youtube.com'; let serverHandle = null; let mainWindow = null; let tray = null; async function createWindow() { mainWindow = new BrowserWindow({ width: 1280, height: 800, title: "What's That Music", autoHideMenuBar: true, webPreferences: { preload: path.join(__dirname, 'yt-scraper.js'), contextIsolation: true, nodeIntegration: false, sandbox: false, }, }); mainWindow.on('closed', () => { mainWindow = null; }); await mainWindow.loadURL(YT_MUSIC_URL); } app.whenReady().then(async () => { serverHandle = await startServer({ port: PORT, overlayDir: OVERLAY_DIR }); ipcMain.on('wtm:state', (_event, payload) => { const next = serverHandle.setState(payload || { isPlaying: false }); if (tray) tray.update({ title: next.title, artist: next.artist }); }); await createWindow(); tray = createTray({ port: PORT, onShow: () => { if (!mainWindow) return; if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.show(); mainWindow.focus(); }, onQuit: () => app.quit(), }); }); app.on('window-all-closed', () => { app.quit(); }); app.on('before-quit', async (e) => { if (serverHandle) { e.preventDefault?.(); try { await serverHandle.stop(); } catch (_) {} serverHandle = null; app.exit(0); } });