// Copyright (c) 2026 Gordon Bolton. MIT License. import { state, SSE_RECONNECT_MS } from './state.js'; import { renderDownloads } from './ui/downloads.js'; import { hideError, hideLoading } from './ui/auth.js'; import { loadHistory } from './ui/history.js'; export function startSSE() { stopSSE(); const params = state.showAll ? '?showAll=true' : ''; const source = new EventSource('/api/dashboard/stream' + params); state.sseSource = source; let firstMessage = true; source.onmessage = (event) => { try { const data = JSON.parse(event.data); state.currentUser = data.user; state.isAdmin = !!data.isAdmin; state.downloads = data.downloads; // Store download clients and update filter dropdown if (data.downloadClients) { state.downloadClients = data.downloadClients; // Trigger filter update const filterUpdateEvent = new CustomEvent('downloadClientsUpdated'); document.dispatchEvent(filterUpdateEvent); } // Store Ombi requests and base URL if (data.ombiRequests) { state.ombiRequests = data.ombiRequests; // Trigger requests update event const requestsUpdateEvent = new CustomEvent('ombiRequestsUpdated'); document.dispatchEvent(requestsUpdateEvent); } if (data.ombiBaseUrl) { state.ombiBaseUrl = data.ombiBaseUrl; } document.getElementById('currentUser').textContent = state.currentUser || '-'; renderDownloads(); hideError(); if (firstMessage) { firstMessage = false; hideLoading(); } } catch (err) { console.error('[SSE] Failed to parse message:', err); } }; // Listen for history-update events from server source.addEventListener('history-update', (event) => { try { const data = JSON.parse(event.data); console.log('[SSE] History update received:', data.type); // Trigger history reload const historyReloadEvent = new CustomEvent('historyReload'); document.dispatchEvent(historyReloadEvent); } catch (err) { console.error('[SSE] Failed to parse history-update message:', err); } }); source.onerror = () => { // EventSource retries automatically; we just log and show a reconnecting indicator console.warn('[SSE] Connection lost, browser will retry...'); }; console.log('[SSE] Stream connected'); } export function stopSSE() { if (state.sseReconnectTimer) { clearTimeout(state.sseReconnectTimer); state.sseReconnectTimer = null; } if (state.sseSource) { state.sseSource.close(); state.sseSource = null; console.log('[SSE] Stream closed'); } } export function handleShowAllToggle(checked) { state.showAll = checked; // Re-open stream with updated showAll param startSSE(); // Trigger history reload with updated showAll param const historyReloadEvent = new CustomEvent('historyReload'); document.dispatchEvent(historyReloadEvent); }