From f02c30efdedc680dd24ae13251e3a8efc3e54753 Mon Sep 17 00:00:00 2001 From: Gronod Date: Thu, 21 May 2026 00:33:57 +0100 Subject: [PATCH] Fix CSP violations and ignoreAvailable reference error - Add .hidden utility class to style.css for CSP compliance - Replace all inline style='display: none' with class='hidden' in HTML - Update all UI modules to use classList.add/remove instead of style.display - Fix ignoreAvailable reference error in history.js (use state.ignoreAvailable) - Rebuild client bundle with vite --- client/src/ui/auth.js | 39 +++++++++++++++------------- client/src/ui/downloads.js | 4 +-- client/src/ui/filters.js | 6 ++--- client/src/ui/history.js | 30 +++++++++++----------- client/src/ui/statusPanel.js | 20 +++++++-------- client/src/ui/tabs.js | 12 ++++----- client/src/ui/webhooks.js | 49 +++++++++++++++++++++++++----------- public/app.js | 42 +++++++++++++++++++++++++++++++ public/index.html | 46 ++++++++++++++++----------------- public/style.css | 5 ++++ 10 files changed, 163 insertions(+), 90 deletions(-) create mode 100644 public/app.js diff --git a/client/src/ui/auth.js b/client/src/ui/auth.js index 66c0c2f..22924ae 100644 --- a/client/src/ui/auth.js +++ b/client/src/ui/auth.js @@ -11,7 +11,7 @@ export function fadeOutLogin() { const login = document.getElementById('login-container'); login.classList.add('fade-out'); login.addEventListener('transitionend', () => { - login.style.display = 'none'; + login.classList.add('hidden'); login.classList.remove('fade-out'); resolve(); }, { once: true }); @@ -20,7 +20,7 @@ export function fadeOutLogin() { export function showSplash() { const splash = document.getElementById('splash-screen'); - splash.style.display = 'flex'; + splash.classList.remove('hidden'); splash.style.opacity = '1'; splash.classList.remove('fade-out'); } @@ -36,12 +36,12 @@ export function dismissSplash(startTime) { // transitionend never fires (e.g. display was toggled in same frame) const TRANSITION_MS = 400; const fallback = setTimeout(() => { - splash.style.display = 'none'; + splash.classList.add('hidden'); resolve(); }, TRANSITION_MS + 100); splash.addEventListener('transitionend', () => { clearTimeout(fallback); - splash.style.display = 'none'; + splash.classList.add('hidden'); resolve(); }, { once: true }); }, remaining); @@ -115,22 +115,27 @@ export async function handleLogoutClick() { } export function showLogin() { - document.getElementById('login-container').style.display = 'flex'; - document.getElementById('dashboard-container').style.display = 'none'; + document.getElementById('login-container').classList.remove('hidden'); + document.getElementById('dashboard-container').classList.add('hidden'); hideLoginError(); } export function showDashboard() { - document.getElementById('login-container').style.display = 'none'; - document.getElementById('dashboard-container').style.display = 'block'; + document.getElementById('login-container').classList.add('hidden'); + document.getElementById('dashboard-container').classList.remove('hidden'); document.getElementById('currentUser').textContent = state.currentUser.name || '-'; // Always start with status panel hidden (guards against stale display value on re-login) const sp = document.getElementById('status-panel'); - sp.style.display = 'none'; + sp.classList.add('hidden'); // Also hide webhooks-section to keep them in sync (both show/hide together) const webhooksSection = document.getElementById('webhooks-section'); - if (webhooksSection) webhooksSection.style.display = 'none'; - document.getElementById('admin-controls').style.display = state.isAdmin ? 'flex' : 'none'; + if (webhooksSection) webhooksSection.classList.add('hidden'); + const adminControls = document.getElementById('admin-controls'); + if (state.isAdmin) { + adminControls.classList.remove('hidden'); + } else { + adminControls.classList.add('hidden'); + } // Note: webhooks-section visibility is controlled by toggleStatusPanel() // Initialise days input from saved value const daysInput = document.getElementById('history-days'); @@ -141,31 +146,31 @@ export function showDashboard() { export function showLoginError(message) { const errorDiv = document.getElementById('login-error'); errorDiv.textContent = message; - errorDiv.style.display = 'block'; + errorDiv.classList.remove('hidden'); } export function hideLoginError() { const errorDiv = document.getElementById('login-error'); - errorDiv.style.display = 'none'; + errorDiv.classList.add('hidden'); } export function showError(message) { const errorDiv = document.getElementById('error-message'); errorDiv.textContent = message; - errorDiv.style.display = 'block'; + errorDiv.classList.remove('hidden'); } export function hideError() { const errorDiv = document.getElementById('error-message'); - errorDiv.style.display = 'none'; + errorDiv.classList.add('hidden'); } export function showLoading() { const loading = document.getElementById('loading'); - loading.style.display = 'block'; + loading.classList.remove('hidden'); } export function hideLoading() { const loading = document.getElementById('loading'); - loading.style.display = 'none'; + loading.classList.add('hidden'); } diff --git a/client/src/ui/downloads.js b/client/src/ui/downloads.js index 1d1738f..7c92336 100644 --- a/client/src/ui/downloads.js +++ b/client/src/ui/downloads.js @@ -75,12 +75,12 @@ export function renderDownloads() { } if (filteredDownloads.length === 0) { - noDownloads.style.display = 'block'; + noDownloads.classList.remove('hidden'); downloadsList.innerHTML = ''; return; } - noDownloads.style.display = 'none'; + noDownloads.classList.add('hidden'); // Get existing cards const existingCards = new Map(); diff --git a/client/src/ui/filters.js b/client/src/ui/filters.js index ddc1aa6..08958d1 100644 --- a/client/src/ui/filters.js +++ b/client/src/ui/filters.js @@ -13,17 +13,17 @@ export function initDownloadClientFilter() { filterBtn.addEventListener('click', (e) => { e.stopPropagation(); - filterDropdown.style.display = filterDropdown.style.display === 'block' ? 'none' : 'block'; + filterDropdown.classList.toggle('open'); }); filterClose.addEventListener('click', () => { - filterDropdown.style.display = 'none'; + filterDropdown.classList.remove('open'); }); // Close dropdown when clicking outside document.addEventListener('click', (e) => { if (!filterDropdown.contains(e.target) && e.target !== filterBtn) { - filterDropdown.style.display = 'none'; + filterDropdown.classList.remove('open'); } }); diff --git a/client/src/ui/history.js b/client/src/ui/history.js index e1653b0..3de70f8 100644 --- a/client/src/ui/history.js +++ b/client/src/ui/history.js @@ -24,11 +24,11 @@ export function initHistoryControls() { refreshBtn.addEventListener('click', () => loadHistory(true)); } if (ignoreToggle) { - ignoreToggle.checked = ignoreAvailable; + ignoreToggle.checked = state.ignoreAvailable; ignoreToggle.addEventListener('change', () => { - ignoreAvailable = ignoreToggle.checked; - saveIgnoreAvailable(ignoreAvailable); - renderHistory(lastHistoryItems); + state.ignoreAvailable = ignoreToggle.checked; + saveIgnoreAvailable(state.ignoreAvailable); + renderHistory(state.lastHistoryItems); }); } @@ -53,8 +53,8 @@ export function stopHistoryRefresh() { export function clearHistory() { state.lastHistoryItems = []; document.getElementById('history-list').innerHTML = ''; - document.getElementById('no-history').style.display = 'none'; - document.getElementById('history-error').style.display = 'none'; + document.getElementById('no-history').classList.add('hidden'); + document.getElementById('history-error').classList.add('hidden'); } export async function loadHistory(forceRefresh = false) { @@ -63,24 +63,24 @@ export async function loadHistory(forceRefresh = false) { const errorEl = document.getElementById('history-error'); const noHistoryEl = document.getElementById('no-history'); - loadingEl.style.display = 'block'; - errorEl.style.display = 'none'; - noHistoryEl.style.display = 'none'; + loadingEl.classList.remove('hidden'); + errorEl.classList.add('hidden'); + noHistoryEl.classList.add('hidden'); try { const result = await apiLoadHistory(forceRefresh); - loadingEl.style.display = 'none'; + loadingEl.classList.add('hidden'); if (result.success) { state.lastHistoryItems = result.history; renderHistory(state.lastHistoryItems); } else { errorEl.textContent = result.error || 'Failed to load history.'; - errorEl.style.display = 'block'; + errorEl.classList.remove('hidden'); } } catch (err) { - loadingEl.style.display = 'none'; + loadingEl.classList.add('hidden'); errorEl.textContent = 'Failed to load history.'; - errorEl.style.display = 'block'; + errorEl.classList.remove('hidden'); console.error('[History] Load error:', err); } } @@ -93,10 +93,10 @@ export function renderHistory(items) { ? items.filter(item => !(item.outcome === 'failed' && item.availableForUpgrade)) : items; if (!visible.length) { - noHistoryEl.style.display = 'block'; + noHistoryEl.classList.remove('hidden'); return; } - noHistoryEl.style.display = 'none'; + noHistoryEl.classList.add('hidden'); visible.forEach(item => listEl.appendChild(createHistoryCard(item))); } diff --git a/client/src/ui/statusPanel.js b/client/src/ui/statusPanel.js index bf39e41..50774c4 100644 --- a/client/src/ui/statusPanel.js +++ b/client/src/ui/statusPanel.js @@ -7,24 +7,24 @@ import { fetchWebhookStatus } from './webhooks.js'; export async function toggleStatusPanel() { const panel = document.getElementById('status-panel'); const webhooksSection = document.getElementById('webhooks-section'); - if (panel.style.display !== 'none') { + if (!panel.classList.contains('hidden')) { // Close both panels (webhooks is a sibling, hide it too) - panel.style.display = 'none'; - if (webhooksSection) webhooksSection.style.display = 'none'; + panel.classList.add('hidden'); + if (webhooksSection) webhooksSection.classList.add('hidden'); if (state.statusRefreshHandle) { clearInterval(state.statusRefreshHandle); state.statusRefreshHandle = null; } return; } // Open status panel and webhooks section (siblings) - panel.style.display = 'block'; + panel.classList.remove('hidden'); // Show webhooks section for admin users (collapsed by default) if (webhooksSection && state.isAdmin) { - webhooksSection.style.display = 'block'; + webhooksSection.classList.remove('hidden'); state.webhookSectionExpanded = false; - document.getElementById('webhooks-content').style.display = 'none'; + document.getElementById('webhooks-content').classList.add('hidden'); document.getElementById('webhooks-toggle').classList.remove('expanded'); await fetchWebhookStatus(); } else if (webhooksSection) { - webhooksSection.style.display = 'none'; + webhooksSection.classList.add('hidden'); } refreshStatusPanel(); if (state.statusRefreshHandle) clearInterval(state.statusRefreshHandle); @@ -32,9 +32,9 @@ export async function toggleStatusPanel() { } export function closeStatusPanel() { - document.getElementById('status-panel').style.display = 'none'; + document.getElementById('status-panel').classList.add('hidden'); const webhooksSection = document.getElementById('webhooks-section'); - if (webhooksSection) webhooksSection.style.display = 'none'; + if (webhooksSection) webhooksSection.classList.add('hidden'); if (state.statusRefreshHandle) { clearInterval(state.statusRefreshHandle); state.statusRefreshHandle = null; } } @@ -42,7 +42,7 @@ export async function refreshStatusPanel() { const panel = document.getElementById('status-panel'); const contentDiv = document.getElementById('status-content'); console.log('[Status] panel found:', !!panel, 'contentDiv found:', !!contentDiv, 'panel display:', panel?.style?.display); - if (!panel || panel.style.display === 'none') return; + if (!panel || panel.classList.contains('hidden')) return; console.log('[Status] Refreshing status panel...'); try { const result = await apiRefreshStatusPanel(); diff --git a/client/src/ui/tabs.js b/client/src/ui/tabs.js index 4e064c8..26a1df3 100644 --- a/client/src/ui/tabs.js +++ b/client/src/ui/tabs.js @@ -26,20 +26,20 @@ export function initTabs() { export function activateTab(tab) { const downloadsTab = document.getElementById('downloads-tab'); const historyTab = document.getElementById('history-tab'); - const downloadsSection = document.getElementById('downloads-section'); - const historySection = document.getElementById('history-section'); + const downloadsSection = document.getElementById('tab-downloads'); + const historySection = document.getElementById('tab-history'); if (tab === 'downloads') { downloadsTab.classList.add('active'); historyTab.classList.remove('active'); - downloadsSection.style.display = 'block'; - historySection.style.display = 'none'; + downloadsSection.classList.remove('hidden'); + historySection.classList.add('hidden'); saveActiveTab('downloads'); } else if (tab === 'history') { historyTab.classList.add('active'); downloadsTab.classList.remove('active'); - historySection.style.display = 'block'; - downloadsSection.style.display = 'none'; + historySection.classList.remove('hidden'); + downloadsSection.classList.add('hidden'); saveActiveTab('history'); loadHistory(); } diff --git a/client/src/ui/webhooks.js b/client/src/ui/webhooks.js index ed35db5..55f720e 100644 --- a/client/src/ui/webhooks.js +++ b/client/src/ui/webhooks.js @@ -22,7 +22,11 @@ export function toggleWebhookSection() { const content = document.getElementById('webhooks-content'); const toggle = document.getElementById('webhooks-toggle'); - content.style.display = state.webhookSectionExpanded ? '' : 'none'; + if (state.webhookSectionExpanded) { + content.classList.remove('hidden'); + } else { + content.classList.add('hidden'); + } toggle.classList.toggle('expanded', state.webhookSectionExpanded); if (state.webhookSectionExpanded) { @@ -32,7 +36,7 @@ export function toggleWebhookSection() { export async function fetchWebhookStatus() { const loadingEl = document.getElementById('webhook-loading'); - loadingEl.style.display = ''; + loadingEl.classList.remove('hidden'); try { const result = await apiFetchWebhookStatus(); @@ -42,7 +46,7 @@ export async function fetchWebhookStatus() { } catch (err) { console.error('Failed to fetch webhook status:', err); } finally { - loadingEl.style.display = 'none'; + loadingEl.classList.add('hidden'); } } @@ -56,9 +60,15 @@ export function renderWebhookStatus() { sonarrStatus.textContent = sonarrWebhook.enabled ? '● Enabled' : '○ Disabled'; sonarrStatus.className = 'status-indicator ' + (sonarrWebhook.enabled ? 'enabled' : 'disabled'); - sonarrEnableBtn.style.display = sonarrWebhook.enabled ? 'none' : ''; - sonarrTestBtn.style.display = sonarrWebhook.enabled ? '' : 'none'; - sonarrTriggers.style.display = sonarrWebhook.enabled ? '' : 'none'; + if (sonarrWebhook.enabled) { + sonarrEnableBtn.classList.add('hidden'); + sonarrTestBtn.classList.remove('hidden'); + sonarrTriggers.classList.remove('hidden'); + } else { + sonarrEnableBtn.classList.remove('hidden'); + sonarrTestBtn.classList.add('hidden'); + sonarrTriggers.classList.add('hidden'); + } if (sonarrWebhook.enabled) { document.getElementById('sonarr-onGrab').textContent = sonarrWebhook.triggers.onGrab ? '✓' : '✗'; @@ -72,12 +82,12 @@ export function renderWebhookStatus() { } if (sonarrWebhook.stats) { - sonarrStats.style.display = ''; + sonarrStats.classList.remove('hidden'); document.getElementById('sonarr-events').textContent = sonarrWebhook.stats.eventsReceived ?? 0; document.getElementById('sonarr-polls').textContent = sonarrWebhook.stats.pollsSkipped ?? 0; document.getElementById('sonarr-last').textContent = formatTimeAgo(sonarrWebhook.stats.lastWebhookTimestamp); } else { - sonarrStats.style.display = 'none'; + sonarrStats.classList.add('hidden'); } // Radarr @@ -89,9 +99,15 @@ export function renderWebhookStatus() { radarrStatus.textContent = radarrWebhook.enabled ? '● Enabled' : '○ Disabled'; radarrStatus.className = 'status-indicator ' + (radarrWebhook.enabled ? 'enabled' : 'disabled'); - radarrEnableBtn.style.display = radarrWebhook.enabled ? 'none' : ''; - radarrTestBtn.style.display = radarrWebhook.enabled ? '' : 'none'; - radarrTriggers.style.display = radarrWebhook.enabled ? '' : 'none'; + if (radarrWebhook.enabled) { + radarrEnableBtn.classList.add('hidden'); + radarrTestBtn.classList.remove('hidden'); + radarrTriggers.classList.remove('hidden'); + } else { + radarrEnableBtn.classList.remove('hidden'); + radarrTestBtn.classList.add('hidden'); + radarrTriggers.classList.add('hidden'); + } if (radarrWebhook.enabled) { document.getElementById('radarr-onGrab').textContent = radarrWebhook.triggers.onGrab ? '✓' : '✗'; @@ -105,12 +121,12 @@ export function renderWebhookStatus() { } if (radarrWebhook.stats) { - radarrStats.style.display = ''; + radarrStats.classList.remove('hidden'); document.getElementById('radarr-events').textContent = radarrWebhook.stats.eventsReceived ?? 0; document.getElementById('radarr-polls').textContent = radarrWebhook.stats.pollsSkipped ?? 0; document.getElementById('radarr-last').textContent = formatTimeAgo(radarrWebhook.stats.lastWebhookTimestamp); } else { - radarrStats.style.display = 'none'; + radarrStats.classList.add('hidden'); } } @@ -188,5 +204,10 @@ export function setWebhookLoading(loading) { document.getElementById('enable-radarr-webhook').disabled = loading; document.getElementById('test-sonarr-webhook').disabled = loading; document.getElementById('test-radarr-webhook').disabled = loading; - document.getElementById('webhook-loading').style.display = loading ? '' : 'none'; + const loadingEl = document.getElementById('webhook-loading'); + if (loading) { + loadingEl.classList.remove('hidden'); + } else { + loadingEl.classList.add('hidden'); + } } diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..116c5c6 --- /dev/null +++ b/public/app.js @@ -0,0 +1,42 @@ +const o={currentUser:null,downloads:[],downloadClients:[],selectedDownloadClients:[],isAdmin:!1,showAll:!1,csrfToken:null,historyDays:7,historyRefreshHandle:null,ignoreAvailable:!1,lastHistoryItems:[],sseSource:null,sseReconnectTimer:null,statusRefreshHandle:null,webhookSectionExpanded:!1,webhookLoading:!1,sonarrWebhook:{enabled:!1,triggers:{onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1},stats:null},radarrWebhook:{enabled:!1,triggers:{onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1},stats:null},webhookMetrics:null},le=1200,ce=5*60*1e3,de=5e3;async function ue(){try{const[e,t]=await Promise.all([fetch("/api/auth/me"),fetch("/api/auth/csrf")]),n=await e.json(),s=await t.json();return s.csrfToken&&(o.csrfToken=s.csrfToken),n.authenticated?(o.currentUser=n.user,o.isAdmin=!!n.user.isAdmin,{authenticated:!0,user:n.user}):{authenticated:!1}}catch(e){return console.error("Authentication check failed:",e),{authenticated:!1}}}async function me(e,t,n){try{const a=await(await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,rememberMe:n})})).json();return a.success?(o.currentUser=a.user,o.isAdmin=!!a.user.isAdmin,a.csrfToken&&(o.csrfToken=a.csrfToken),{success:!0,user:a.user}):{success:!1,error:a.error||"Login failed"}}catch(s){return console.error(s),{success:!1,error:"Login failed. Please try again."}}}async function he(){try{return await fetch("/api/auth/logout",{method:"POST",headers:csrfToken?{"X-CSRF-Token":csrfToken}:{}}),currentUser=null,csrfToken=null,{success:!0}}catch(e){return console.error("Logout failed:",e),{success:!1}}}async function fe(e=!1){try{const t=new URLSearchParams({days:o.historyDays});o.showAll&&t.set("showAll","true"),e&&t.set("_t",Date.now());const n=await fetch(`/api/history/recent?${t}`);if(!n.ok)throw new Error(`HTTP ${n.status}`);return{success:!0,history:(await n.json()).history||[]}}catch(t){return console.error("[History] Load error:",t),{success:!1,error:"Failed to load history."}}}async function pe(e){try{const t=await fetch("/api/dashboard/blocklist-search",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":csrfToken},body:JSON.stringify({arrQueueId:e.arrQueueId,arrType:e.arrType,arrInstanceUrl:e.arrInstanceUrl,arrInstanceKey:e.arrInstanceKey,arrContentId:e.arrContentId,arrContentType:e.arrContentType})});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`HTTP ${t.status}`)}return{success:!0}}catch(t){throw console.error("[Blocklist] Error:",t),t}}async function ge(){try{return(await(await fetch("/health")).json()).version||null}catch{return null}}async function ye(){try{const e=await fetch("/api/dashboard/webhook-metrics");return e.ok?await e.json():null}catch{return null}}async function N(){var e,t;try{const n=ye();let s=!1,a={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const f=await fetch("/api/sonarr/notifications");if(f.ok){const d=(await f.json()).find(p=>p.name==="Sofarr");s=!!d,d&&(a={onGrab:d.onGrab,onDownload:d.onDownload,onImport:d.onImport,onUpgrade:d.onUpgrade})}}catch{}let l=!1,c={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const f=await fetch("/api/radarr/notifications");if(f.ok){const d=(await f.json()).find(p=>p.name==="Sofarr");l=!!d,d&&(c={onGrab:d.onGrab,onDownload:d.onDownload,onImport:d.onImport,onUpgrade:d.onUpgrade})}}catch{}o.webhookMetrics=await n;const m=o.webhookMetrics?Object.entries(o.webhookMetrics.instances||{}):[],u=((e=m.find(([f])=>f.includes("sonarr")))==null?void 0:e[1])||null,i=((t=m.find(([f])=>f.includes("radarr")))==null?void 0:t[1])||null;return o.sonarrWebhook={enabled:s,triggers:a,stats:u},o.radarrWebhook={enabled:l,triggers:c,stats:i},{success:!0}}catch(n){return console.error("Failed to fetch webhook status:",n),{success:!1}}}async function be(){try{if(!(await fetch("/api/sonarr/notifications/sofarr-webhook",{method:"POST",headers:{"X-CSRF-Token":csrfToken||""}})).ok)throw new Error("Failed to enable");return await N(),{success:!0}}catch(e){return console.error("Failed to enable Sonarr webhook:",e),{success:!1,error:e.message}}}async function ve(){try{if(!(await fetch("/api/radarr/notifications/sofarr-webhook",{method:"POST",headers:{"X-CSRF-Token":o.csrfToken||""}})).ok)throw new Error("Failed to enable");return await N(),{success:!0}}catch(e){return console.error("Failed to enable Radarr webhook:",e),{success:!1,error:e.message}}}async function Ee(){try{const e=await fetch("/api/sonarr/notifications");if(!e.ok)throw new Error("Failed to fetch notifications");const n=(await e.json()).find(a=>a.name==="Sofarr");if(!n)throw new Error("Sofarr webhook not found");if(!(await fetch("/api/sonarr/notifications/test",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":o.csrfToken||""},body:JSON.stringify(n)})).ok)throw new Error("Test failed");return await N(),{success:!0}}catch(e){return console.error("Failed to test Sonarr webhook:",e),{success:!1,error:e.message}}}async function we(){try{const e=await fetch("/api/radarr/notifications");if(!e.ok)throw new Error("Failed to fetch notifications");const n=(await e.json()).find(a=>a.name==="Sofarr");if(!n)throw new Error("Sofarr webhook not found");if(!(await fetch("/api/radarr/notifications/test",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":o.csrfToken||""},body:JSON.stringify(n)})).ok)throw new Error("Test failed");return await N(),{success:!0}}catch(e){return console.error("Failed to test Radarr webhook:",e),{success:!1,error:e.message}}}async function ke(){try{const e=await fetch("/api/dashboard/status");if(!e.ok)throw new Error("Failed to fetch status: "+e.status);return{success:!0,data:await e.json()}}catch(e){return console.error("[Status] Error fetching status:",e),{success:!1,error:e.message}}}function Se(e){if(!e)return"N/A";if(typeof e=="string")return e;const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}function Ce(e){if(!e||e===0)return"0 B/s";const t=["B/s","KB/s","MB/s","GB/s"];let n=e,s=0;for(;n>=1024&&s{const a="S"+String(s.season).padStart(2,"0")+"E"+String(s.episode).padStart(2,"0");return s.title?a+" — "+s.title:a});t.setAttribute("data-tooltip",n.join(` +`))}return t}function R(e,t,n){const s=document.createDocumentFragment();if(t&&e&&e.length>0){const a=e.filter(c=>!c.matchedUser),l=e.filter(c=>c.matchedUser);for(const c of a){const m=document.createElement("span");m.className="download-user-badge unmatched",m.textContent=c.label,s.appendChild(m)}for(const c of l){const m=document.createElement("span");m.className="download-user-badge",m.textContent=c.matchedUser,s.appendChild(m)}}else if(n){const a=document.createElement("span");a.className="download-user-badge",a.textContent=n,s.appendChild(a)}return s}function X(e){const t=document.createElement("span");t.className="download-client-logo-wrapper download-card-logo-wrapper";const n=document.createElement("img");return n.className="download-client-logo",n.src=`/images/clients/${e.client}.svg`,n.alt=`${e.instanceName||e.client} icon`,n.title=e.instanceName||e.client,n.onerror=()=>{t.textContent=e.client.charAt(0).toUpperCase(),t.classList.add("fallback")},t.appendChild(n),t}function Q(){const e=document.getElementById("downloads-list"),t=document.getElementById("no-downloads");let n=o.downloads;if(o.selectedDownloadClients.length>0){const l=o.selectedDownloadClients.map(c=>o.downloadClients[c]).filter(Boolean);n=o.downloads.filter(c=>l.some(m=>m.type===c.client&&m.id===c.instanceId))}if(o.downloadClients.length>0){const l=new Map(o.downloadClients.map((c,m)=>[c.id,m]));n=[...n].sort((c,m)=>{const u=l.get(c.instanceId)??1/0,i=l.get(m.instanceId)??1/0;return u-i})}if(n.length===0){t.classList.remove("hidden"),e.innerHTML="";return}t.classList.add("hidden");const s=new Map;e.querySelectorAll(".download-card").forEach(l=>{s.set(l.dataset.id,l)});const a=new Set;n.forEach(l=>{const c=l.title;a.add(c);const m=s.get(c);if(m)Le(m,l);else{const u=Te(l);e.appendChild(u)}}),s.forEach((l,c)=>{a.has(c)||l.remove()})}function Le(e,t){const n=e.querySelector(".download-header-right");n&&n.remove(),e.querySelectorAll(".download-header .download-user-badge").forEach(r=>r.remove());const a=e.querySelector(".download-header .download-client-logo-wrapper");a&&a.remove();const l=e.querySelector(".download-card-logo-wrapper");l&&l.remove();const c=e.querySelector(".download-header");if(c&&!c.querySelector(".download-header-right")){const r=document.createElement("div");r.className="download-header-right";const d=R(t.tagBadges,o.showAll,t.matchedUserTag);r.appendChild(d),c.appendChild(r)}t.client&&!e.querySelector(".download-card-logo-wrapper")&&e.appendChild(X(t));const m=e.querySelector(".download-status");m&&m.textContent!==t.status&&(m.textContent=t.status,m.className=`download-status ${t.status}`);const u=e.querySelector(".progress-container");if(u&&t.progress!==void 0){const r=u.querySelector(".progress-bar"),d=u.querySelector(".progress-text"),p=u.querySelector(".missing-text");if(r){const g=r.querySelector(".downloaded");g&&(g.style.width=t.progress+"%")}if(d&&(d.textContent=t.progress+"%"),p){const g=parseFloat(t.mb)||parseFloat(t.size),y=parseFloat(t.mbmissing)||0;y>0&&g>0?p.textContent=`(missing ${y.toFixed(1)} of ${g.toFixed(1)} MB)`:p.textContent=""}}const i=e.querySelector('.detail-item[data-label="Speed"] .detail-value');i&&t.speed!==void 0&&(i.textContent=t.speed);const f=e.querySelector('.detail-item[data-label="ETA"] .detail-value');if(f&&t.eta!==void 0&&(f.textContent=t.eta),t.qbittorrent){const r=e.querySelector('.detail-item[data-label="Seeds"] .detail-value');r&&t.seeds!==void 0&&(r.textContent=t.seeds);const d=e.querySelector('.detail-item[data-label="Peers"] .detail-value');d&&t.peers!==void 0&&(d.textContent=t.peers);const p=e.querySelector('.detail-item[data-label="Availability"]');p&&t.availability!==void 0&&(p.querySelector(".detail-value").textContent=`${t.availability}%`,p.classList.toggle("availability-warning",parseFloat(t.availability)<100))}}async function Be(e,t){if(confirm(`Blocklist "${t.title}" and trigger a new search? + +This will: +• Remove the download from the download client +• Add this release to the blocklist +• Trigger an automatic search for a new release`)){e.disabled=!0,e.textContent="⏳ Working…";try{await pe(t),e.textContent="✓ Done — searching…",e.className="blocklist-search-btn success"}catch(n){console.error("[Blocklist] Error:",n),e.disabled=!1,e.textContent="⛔ Blocklist & Search",e.className="blocklist-search-btn error",e.title=`Failed: ${n.message}`,setTimeout(()=>{e.className="blocklist-search-btn",e.title="Remove this release from the download client, add it to the blocklist, and trigger a new automatic search"},4e3)}}}function Te(e){const t=document.createElement("div");if(t.className=`download-card ${e.type}`,t.dataset.id=e.title,e.coverArt){const r=document.createElement("div");r.className="download-cover";const d=document.createElement("img");d.src=e.coverArt?"/api/dashboard/cover-art?url="+encodeURIComponent(e.coverArt):"",d.alt=e.movieName||e.seriesName||e.title,d.loading="lazy",r.appendChild(d),t.appendChild(r)}const n=document.createElement("div");n.className="download-info";const s=document.createElement("div");s.className="download-header";const a=document.createElement("span");if(a.className=`download-type ${e.type}`,e.type==="series")a.textContent="📺 Series";else if(e.type==="movie")a.textContent="🎬 Movie";else if(e.type==="torrent"){const r=e.instanceName?` (${e.instanceName})`:"";a.textContent=`📥 Torrent${r}`}else a.textContent=e.type;const l=document.createElement("span");if(l.className=`download-status ${e.status}`,l.textContent=e.status,s.appendChild(a),s.appendChild(l),e.importIssues&&e.importIssues.length>0){const r=document.createElement("span");r.className="import-issue-badge",r.textContent="Import Pending",r.setAttribute("data-tooltip",e.importIssues.join(` +`)),s.appendChild(r)}if((o.isAdmin||e.canBlocklist)&&e.arrQueueId){const r=document.createElement("button");r.className="blocklist-search-btn",r.textContent="⛔ Blocklist & Search",r.title="Remove this release from the download client, add it to the blocklist, and trigger a new automatic search",r.addEventListener("click",()=>Be(r,e)),s.appendChild(r)}const c=document.createElement("div");c.className="download-header-right";const m=R(e.tagBadges,o.showAll,e.matchedUserTag);c.appendChild(m),s.appendChild(c),e.client&&t.appendChild(X(e));const u=document.createElement("h3");if(u.className="download-title",u.textContent=e.title,n.appendChild(s),n.appendChild(u),e.seriesName){const r=document.createElement("p");r.className="download-series",o.isAdmin&&e.arrLink?r.innerHTML='Series: '+v(e.seriesName)+"":r.textContent=`Series: ${e.seriesName}`,n.appendChild(r);const d=K(e.episodes);d&&n.appendChild(d)}if(e.movieName){const r=document.createElement("p");r.className="download-movie",o.isAdmin&&e.arrLink?r.innerHTML='Movie: '+v(e.movieName)+"":r.textContent=`Movie: ${e.movieName}`,n.appendChild(r)}const i=document.createElement("div");i.className="download-details";const f=C("Size",Se(e.size));if(i.appendChild(f),e.progress!==void 0){const r=document.createElement("div");r.className="detail-item progress-item",r.dataset.label="Progress";const d=document.createElement("span");d.className="detail-label",d.textContent="Progress";const p=document.createElement("div");p.className="progress-container";const g=parseFloat(e.mb)||parseFloat(e.size),y=parseFloat(e.mbmissing)||0,B=parseFloat(e.progress)||0,I=document.createElement("div");if(I.className="progress-bar",B>0){const b=document.createElement("div");b.className="progress-segment downloaded",b.style.width=B+"%",I.appendChild(b)}p.appendChild(I);const L=document.createElement("span");if(L.className="progress-text",L.textContent=e.progress+"%",p.appendChild(L),e.client&&(e.client==="qbittorrent"||e.client==="rtorrent")&&y>0&&g>0){const b=document.createElement("span");b.className="missing-text",b.textContent=`(missing ${y.toFixed(1)} of ${g.toFixed(1)} MB)`,p.appendChild(b)}r.appendChild(d),r.appendChild(p),i.appendChild(r)}if(e.speed&&e.speed>0){const r=C("Speed",Ce(e.speed));i.appendChild(r)}if(e.eta){const r=C("ETA",e.eta);i.appendChild(r)}if(e.qbittorrent){if(e.seeds!==void 0){const r=C("Seeds",e.seeds);i.appendChild(r)}if(e.peers!==void 0){const r=C("Peers",e.peers);i.appendChild(r)}if(e.availability!==void 0){const r=C("Availability",`${e.availability}%`);parseFloat(e.availability)<100&&r.classList.add("availability-warning"),i.appendChild(r)}}if(e.completedAt){const r=C("Completed",xe(e.completedAt));i.appendChild(r)}if(o.isAdmin&&(e.downloadPath||e.targetPath)){const r=document.createElement("div");if(r.className="download-paths",e.downloadPath){const d=document.createElement("div");d.className="path-item",d.innerHTML='Download: '+v(e.downloadPath)+"",r.appendChild(d)}if(e.targetPath){const d=document.createElement("div");d.className="path-item",d.innerHTML='Target: '+v(e.targetPath)+"",r.appendChild(d)}i.appendChild(r)}return n.appendChild(i),t.appendChild(n),t}function C(e,t){const n=document.createElement("div");n.className="detail-item",n.dataset.label=e;const s=document.createElement("span");s.className="detail-label",s.textContent=e;const a=document.createElement("span");return a.className="detail-value",a.textContent=t,n.appendChild(s),n.appendChild(a),n}function xe(e){return e?new Date(e).toLocaleString():"N/A"}function F(){V();const e=o.showAll?"?showAll=true":"",t=new EventSource("/api/dashboard/stream"+e);o.sseSource=t;let n=!0;t.onmessage=s=>{try{const a=JSON.parse(s.data);if(o.currentUser=a.user,o.isAdmin=!!a.isAdmin,o.downloads=a.downloads,a.downloadClients){o.downloadClients=a.downloadClients;const l=new CustomEvent("downloadClientsUpdated");document.dispatchEvent(l)}document.getElementById("currentUser").textContent=o.currentUser||"-",Q(),nt(),n&&(n=!1,st())}catch(a){console.error("[SSE] Failed to parse message:",a)}},t.onerror=()=>{console.warn("[SSE] Connection lost, browser will retry...")},console.log("[SSE] Stream connected")}function V(){o.sseSource&&(o.sseSource.close(),o.sseSource=null,console.log("[SSE] Stream closed"))}function Ne(e){o.showAll=e,F();const t=new CustomEvent("historyReload");document.dispatchEvent(t)}(function(){const t=localStorage.getItem("sofarr-download-client");if(t&&t!=="all")try{o.selectedDownloadClients=[t],localStorage.setItem("sofarr-download-clients",JSON.stringify(o.selectedDownloadClients)),localStorage.removeItem("sofarr-download-client")}catch(n){console.error("[Migration] Failed to migrate download client filter:",n)}else try{const n=localStorage.getItem("sofarr-download-clients");o.selectedDownloadClients=n?JSON.parse(n):[]}catch(n){console.error("[Migration] Failed to load download client filter:",n),o.selectedDownloadClients=[]}})();(function(){try{const t=localStorage.getItem("sofarr-history-days");t&&(o.historyDays=parseInt(t,10)||7)}catch(t){console.error("[Storage] Failed to load history days:",t)}})();(function(){try{const t=localStorage.getItem("sofarr-ignore-available");o.ignoreAvailable=t==="true"}catch(t){console.error("[Storage] Failed to load ignore available:",t)}})();function De(e){localStorage.setItem("sofarr-history-days",e)}function Me(e){localStorage.setItem("sofarr-ignore-available",e)}function Ae(e){localStorage.setItem("sofarr-download-clients",JSON.stringify(e))}function Y(){return localStorage.getItem("sofarr-theme")||"light"}function Re(e){localStorage.setItem("sofarr-theme",e)}function Fe(){return localStorage.getItem("sofarr-active-tab")||"downloads"}function j(e){localStorage.setItem("sofarr-active-tab",e)}function $e(){const e=document.getElementById("history-days"),t=document.getElementById("history-refresh-btn"),n=document.getElementById("ignore-available-toggle");e&&e.addEventListener("change",()=>{const s=parseInt(e.value,10);s>0&&s<=90&&(historyDays=s,De(s),x(!0))}),t&&t.addEventListener("click",()=>x(!0)),n&&(n.checked=o.ignoreAvailable,n.addEventListener("change",()=>{o.ignoreAvailable=n.checked,Me(o.ignoreAvailable),ee(o.lastHistoryItems)})),document.addEventListener("historyReload",()=>{x(!0)})}function He(){Z(),o.historyRefreshHandle=setInterval(()=>x(),ce)}function Z(){o.historyRefreshHandle&&(clearInterval(o.historyRefreshHandle),o.historyRefreshHandle=null)}function We(){o.lastHistoryItems=[],document.getElementById("history-list").innerHTML="",document.getElementById("no-history").classList.add("hidden"),document.getElementById("history-error").classList.add("hidden")}async function x(e=!1){document.getElementById("history-list");const t=document.getElementById("history-loading"),n=document.getElementById("history-error"),s=document.getElementById("no-history");t.classList.remove("hidden"),n.classList.add("hidden"),s.classList.add("hidden");try{const a=await fe(e);t.classList.add("hidden"),a.success?(o.lastHistoryItems=a.history,ee(o.lastHistoryItems)):(n.textContent=a.error||"Failed to load history.",n.classList.remove("hidden"))}catch(a){t.classList.add("hidden"),n.textContent="Failed to load history.",n.classList.remove("hidden"),console.error("[History] Load error:",a)}}function ee(e){const t=document.getElementById("history-list"),n=document.getElementById("no-history");t.innerHTML="";const s=o.ignoreAvailable?e.filter(a=>!(a.outcome==="failed"&&a.availableForUpgrade)):e;if(!s.length){n.classList.remove("hidden");return}n.classList.add("hidden"),s.forEach(a=>t.appendChild(Ue(a)))}function Ue(e){const t=document.createElement("div");if(t.className=`history-card ${e.type} ${e.outcome}`,e.coverArt){const i=document.createElement("div");i.className="history-cover";const f=document.createElement("img");f.src="/api/dashboard/cover-art?url="+encodeURIComponent(e.coverArt),f.alt=e.movieName||e.seriesName||e.title,f.loading="lazy",i.appendChild(f),t.appendChild(i)}const n=document.createElement("div");n.className="history-info";const s=document.createElement("div");s.className="history-card-header";const a=document.createElement("span");a.className=`history-type-badge ${e.type}`,a.textContent=e.type==="series"?"📺 Series":"🎬 Movie",s.appendChild(a);const l=document.createElement("span");if(l.className=`history-outcome-badge ${e.outcome}`,l.textContent=e.outcome==="imported"?"✓ Imported":"✗ Failed",s.appendChild(l),e.availableForUpgrade){const i=document.createElement("span");i.className="history-upgrade-badge",i.title="A previous version of this item is available. An upgrade download has failed.",i.textContent="⬆ Available",s.appendChild(i)}if(e.instanceName){const i=document.createElement("span");i.className="history-instance-badge",i.textContent=e.instanceName,s.appendChild(i)}const c=R(e.tagBadges,o.showAll,e.matchedUserTag);s.appendChild(c),n.appendChild(s);const m=document.createElement("h3");if(m.className="history-title",m.textContent=e.title,n.appendChild(m),e.seriesName){const i=document.createElement("p");i.className="history-media-name",o.isAdmin&&e.arrLink?i.innerHTML='Series: '+v(e.seriesName)+"":i.textContent="Series: "+e.seriesName,n.appendChild(i);const f=K(e.episodes);f&&n.appendChild(f)}if(e.movieName){const i=document.createElement("p");i.className="history-media-name",o.isAdmin&&e.arrLink?i.innerHTML='Movie: '+v(e.movieName)+"":i.textContent="Movie: "+e.movieName,n.appendChild(i)}const u=document.createElement("div");if(u.className="history-details",e.completedAt&&u.appendChild(G("Completed",Ie(e.completedAt))),e.quality&&u.appendChild(G("Quality",e.quality)),e.outcome==="failed"&&e.failureMessage){const i=document.createElement("div");i.className="history-failure-message",i.textContent=e.failureMessage,u.appendChild(i)}return n.appendChild(u),t.appendChild(n),t}function G(e,t){const n=document.createElement("div");n.className="detail-item",n.dataset.label=e;const s=document.createElement("span");s.className="detail-label",s.textContent=e;const a=document.createElement("span");return a.className="detail-value",a.textContent=t,n.appendChild(s),n.appendChild(a),n}function Pe(){document.getElementById("webhooks-section")&&(document.getElementById("webhooks-header").addEventListener("click",qe),document.getElementById("enable-sonarr-webhook").addEventListener("click",je),document.getElementById("enable-radarr-webhook").addEventListener("click",Ge),document.getElementById("test-sonarr-webhook").addEventListener("click",_e),document.getElementById("test-radarr-webhook").addEventListener("click",ze))}function qe(){o.webhookSectionExpanded=!o.webhookSectionExpanded;const e=document.getElementById("webhooks-content"),t=document.getElementById("webhooks-toggle");o.webhookSectionExpanded?e.classList.remove("hidden"):e.classList.add("hidden"),t.classList.toggle("expanded",o.webhookSectionExpanded),o.webhookSectionExpanded&&te()}async function te(){const e=document.getElementById("webhook-loading");e.classList.remove("hidden");try{(await N()).success&&Oe()}catch(t){console.error("Failed to fetch webhook status:",t)}finally{e.classList.add("hidden")}}function Oe(){const e=document.getElementById("sonarr-status"),t=document.getElementById("enable-sonarr-webhook"),n=document.getElementById("test-sonarr-webhook"),s=document.getElementById("sonarr-triggers"),a=document.getElementById("sonarr-stats");e.textContent=sonarrWebhook.enabled?"● Enabled":"○ Disabled",e.className="status-indicator "+(sonarrWebhook.enabled?"enabled":"disabled"),sonarrWebhook.enabled?(t.classList.add("hidden"),n.classList.remove("hidden"),s.classList.remove("hidden")):(t.classList.remove("hidden"),n.classList.add("hidden"),s.classList.add("hidden")),sonarrWebhook.enabled&&(document.getElementById("sonarr-onGrab").textContent=sonarrWebhook.triggers.onGrab?"✓":"✗",document.getElementById("sonarr-onGrab").className="trigger-value "+(sonarrWebhook.triggers.onGrab?"active":"inactive"),document.getElementById("sonarr-onDownload").textContent=sonarrWebhook.triggers.onDownload?"✓":"✗",document.getElementById("sonarr-onDownload").className="trigger-value "+(sonarrWebhook.triggers.onDownload?"active":"inactive"),document.getElementById("sonarr-onImport").textContent=sonarrWebhook.triggers.onImport?"✓":"✗",document.getElementById("sonarr-onImport").className="trigger-value "+(sonarrWebhook.triggers.onImport?"active":"inactive"),document.getElementById("sonarr-onUpgrade").textContent=sonarrWebhook.triggers.onUpgrade?"✓":"✗",document.getElementById("sonarr-onUpgrade").className="trigger-value "+(sonarrWebhook.triggers.onUpgrade?"active":"inactive")),sonarrWebhook.stats?(a.classList.remove("hidden"),document.getElementById("sonarr-events").textContent=sonarrWebhook.stats.eventsReceived??0,document.getElementById("sonarr-polls").textContent=sonarrWebhook.stats.pollsSkipped??0,document.getElementById("sonarr-last").textContent=O(sonarrWebhook.stats.lastWebhookTimestamp)):a.classList.add("hidden");const l=document.getElementById("radarr-status"),c=document.getElementById("enable-radarr-webhook"),m=document.getElementById("test-radarr-webhook"),u=document.getElementById("radarr-triggers"),i=document.getElementById("radarr-stats");l.textContent=radarrWebhook.enabled?"● Enabled":"○ Disabled",l.className="status-indicator "+(radarrWebhook.enabled?"enabled":"disabled"),radarrWebhook.enabled?(c.classList.add("hidden"),m.classList.remove("hidden"),u.classList.remove("hidden")):(c.classList.remove("hidden"),m.classList.add("hidden"),u.classList.add("hidden")),radarrWebhook.enabled&&(document.getElementById("radarr-onGrab").textContent=radarrWebhook.triggers.onGrab?"✓":"✗",document.getElementById("radarr-onGrab").className="trigger-value "+(radarrWebhook.triggers.onGrab?"active":"inactive"),document.getElementById("radarr-onDownload").textContent=radarrWebhook.triggers.onDownload?"✓":"✗",document.getElementById("radarr-onDownload").className="trigger-value "+(radarrWebhook.triggers.onDownload?"active":"inactive"),document.getElementById("radarr-onImport").textContent=radarrWebhook.triggers.onImport?"✓":"✗",document.getElementById("radarr-onImport").className="trigger-value "+(radarrWebhook.triggers.onImport?"active":"inactive"),document.getElementById("radarr-onUpgrade").textContent=radarrWebhook.triggers.onUpgrade?"✓":"✗",document.getElementById("radarr-onUpgrade").className="trigger-value "+(radarrWebhook.triggers.onUpgrade?"active":"inactive")),radarrWebhook.stats?(i.classList.remove("hidden"),document.getElementById("radarr-events").textContent=radarrWebhook.stats.eventsReceived??0,document.getElementById("radarr-polls").textContent=radarrWebhook.stats.pollsSkipped??0,document.getElementById("radarr-last").textContent=O(radarrWebhook.stats.lastWebhookTimestamp)):i.classList.add("hidden")}async function je(){w(!0);try{const e=await be();e.success||(console.error("Failed to enable Sonarr webhook:",e.error),alert("Failed to enable Sonarr webhook. Check console for details."))}catch(e){console.error("Failed to enable Sonarr webhook:",e),alert("Failed to enable Sonarr webhook. Check console for details.")}finally{w(!1)}}async function Ge(){w(!0);try{const e=await ve();e.success||(console.error("Failed to enable Radarr webhook:",e.error),alert("Failed to enable Radarr webhook. Check console for details."))}catch(e){console.error("Failed to enable Radarr webhook:",e),alert("Failed to enable Radarr webhook. Check console for details.")}finally{w(!1)}}async function _e(){w(!0);try{const e=await Ee();e.success?alert("Sonarr webhook test sent successfully!"):(console.error("Failed to test Sonarr webhook:",e.error),alert("Failed to test Sonarr webhook. Check console for details."))}catch(e){console.error("Failed to test Sonarr webhook:",e),alert("Failed to test Sonarr webhook. Check console for details.")}finally{w(!1)}}async function ze(){w(!0);try{const e=await we();e.success?alert("Radarr webhook test sent successfully!"):(console.error("Failed to test Radarr webhook:",e.error),alert("Failed to test Radarr webhook. Check console for details."))}catch(e){console.error("Failed to test Radarr webhook:",e),alert("Failed to test Radarr webhook. Check console for details.")}finally{w(!1)}}function w(e){o.webhookLoading=e,document.getElementById("enable-sonarr-webhook").disabled=e,document.getElementById("enable-radarr-webhook").disabled=e,document.getElementById("test-sonarr-webhook").disabled=e,document.getElementById("test-radarr-webhook").disabled=e;const t=document.getElementById("webhook-loading");e?t.classList.remove("hidden"):t.classList.add("hidden")}async function Je(){const e=document.getElementById("status-panel"),t=document.getElementById("webhooks-section");if(!e.classList.contains("hidden")){e.classList.add("hidden"),t&&t.classList.add("hidden"),o.statusRefreshHandle&&(clearInterval(o.statusRefreshHandle),o.statusRefreshHandle=null);return}e.classList.remove("hidden"),t&&o.isAdmin?(t.classList.remove("hidden"),o.webhookSectionExpanded=!1,document.getElementById("webhooks-content").classList.add("hidden"),document.getElementById("webhooks-toggle").classList.remove("expanded"),await te()):t&&t.classList.add("hidden"),_(),o.statusRefreshHandle&&clearInterval(o.statusRefreshHandle),o.statusRefreshHandle=setInterval(_,de)}function Ke(){document.getElementById("status-panel").classList.add("hidden");const e=document.getElementById("webhooks-section");e&&e.classList.add("hidden"),o.statusRefreshHandle&&(clearInterval(o.statusRefreshHandle),o.statusRefreshHandle=null)}async function _(){var n;const e=document.getElementById("status-panel"),t=document.getElementById("status-content");if(console.log("[Status] panel found:",!!e,"contentDiv found:",!!t,"panel display:",(n=e==null?void 0:e.style)==null?void 0:n.display),!(!e||e.classList.contains("hidden"))){console.log("[Status] Refreshing status panel...");try{const s=await ke();s.success&&(console.log("[Status] Got status data, rendering..."),Xe(s.data,e))}catch(s){console.error("[Status] Error fetching status:",s),t&&(!t.innerHTML||t.innerHTML.includes("status-loading"))&&(t.innerHTML='

Failed to load status: '+s.message+"

")}}}function Xe(e,t){var I,L,b,$,H,W,U,P,q;console.log("[Status] renderStatusPanel called with data:",e?"yes":"no","keys:",e?Object.keys(e):"none");const n=e.server,s=Math.floor(n.uptimeSeconds/3600),a=Math.floor(n.uptimeSeconds%3600/60),l=n.uptimeSeconds%60,c=`${s}h ${a}m ${l}s`,m=(e.cache.totalSizeBytes/1024).toFixed(1);let u=` +
+

Server Status

+ +
+
+
+
Server
+
Uptime${c}
+
Node${D(n.nodeVersion)}
+
Memory (RSS)${n.memoryUsageMB} MB
+
Heap${n.heapUsedMB} / ${n.heapTotalMB} MB
+
+
+
Data Refresh
`;const i=e.polling.intervalMs,r=(e.clients||[]).filter(h=>h.type==="sse");e.polling.enabled?u+=`
Background poll${i/1e3}s
`:u+='
Background pollDisabled
';const d=r.length>0?'SSE push':e.polling.enabled?"Background":"On-demand (idle)";u+=`
Delivery mode${d}
`,u+=`
SSE clients${r.length}
`;for(const h of r){const k=Math.round((Date.now()-h.connectedAt)/1e3);u+=`
${D(h.user)}connected ${k}s ago
`}if(u+="
",o.isAdmin&&e.webhooks){const h=e.webhooks,k=(I=h.sonarr)!=null&&I.enabled?"●":"○",E=(L=h.radarr)!=null&&L.enabled?"●":"○",S=((b=h.sonarr)==null?void 0:b.eventsReceived)||0,oe=(($=h.radarr)==null?void 0:$.eventsReceived)||0,re=((H=h.sonarr)==null?void 0:H.pollsSkipped)||0,ie=((W=h.radarr)==null?void 0:W.pollsSkipped)||0;u+=` +
+
Webhooks
+
Sonarr${k} ${(U=h.sonarr)!=null&&U.enabled?"Enabled":"Disabled"}
+
Radarr${E} ${(P=h.radarr)!=null&&P.enabled?"Enabled":"Disabled"}
+
EventsS:${S} R:${oe}
+
Polls skippedS:${re} R:${ie}
+
`}const p=e.polling.lastPoll;if(p){const h=Math.round((Date.now()-new Date(p.timestamp).getTime())/1e3);u+=` +
+
Last Poll (${p.totalMs}ms total, ${h}s ago)
+
`;const k=p.tasks.reduce((E,S)=>Math.max(E,S.ms),1);for(const E of p.tasks){const S=Math.max(2,E.ms/k*100);u+=` +
+ ${D(E.label)} +
+ ${E.ms}ms +
`}u+="
"}u+=` +
+
Cache (${e.cache.entryCount} entries, ${m} KB)
+ + + `;for(const h of e.cache.entries){const k=h.sizeBytes>1024?(h.sizeBytes/1024).toFixed(1)+" KB":h.sizeBytes+" B",E=h.expired?'expired':(h.ttlRemainingMs/1e3).toFixed(0)+"s",S=h.itemCount!==null?h.itemCount:"—";u+=``}u+="
KeyItemsSizeTTL
${D(h.key)}${S}${k}${E}
";const g=document.getElementById("status-content"),y=document.getElementById("status-panel");console.log("[Status] contentDiv found:",!!g,"panel children:",(q=y==null?void 0:y.children)==null?void 0:q.length,"HTML length:",u.length),y&&console.log("[Status] panel innerHTML preview:",y.innerHTML.substring(0,200)),g?(g.innerHTML=u,console.log("[Status] HTML rendered, contentDiv innerHTML length:",g.innerHTML.length)):console.error("[Status] contentDiv not found!");const B=document.getElementById("status-close-btn");B&&B.addEventListener("click",Ke),t.querySelectorAll(".timing-bar[data-w]").forEach(h=>{h.style.width=h.dataset.w+"%"})}function D(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function Qe(){return new Promise(e=>{const t=document.getElementById("login-container");t.classList.add("fade-out"),t.addEventListener("transitionend",()=>{t.classList.add("hidden"),t.classList.remove("fade-out"),e()},{once:!0})})}function Ve(){const e=document.getElementById("splash-screen");e.classList.remove("hidden"),e.style.opacity="1",e.classList.remove("fade-out")}function M(e){return new Promise(t=>{const n=Date.now()-(e||0),s=Math.max(0,le-n);setTimeout(()=>{const a=document.getElementById("splash-screen");a.classList.add("fade-out");const c=setTimeout(()=>{a.classList.add("hidden"),t()},400+100);a.addEventListener("transitionend",()=>{clearTimeout(c),a.classList.add("hidden"),t()},{once:!0})},s)})}async function Ye(){const e=Date.now();try{(await ue()).authenticated?(ne(),se(),F(),await M(e)):(await M(e),A())}catch(t){console.error("Authentication check failed:",t),await M(e),A()}}async function Ze(e){e.preventDefault();const t=document.getElementById("username").value,n=document.getElementById("password").value,s=document.getElementById("remember-me").checked;try{const a=await me(t,n,s);if(a.success){await Qe(),Ve(),await new Promise(c=>requestAnimationFrame(()=>requestAnimationFrame(c))),ne(),se();const l=Date.now();F(),await M(l)}else z(a.error||"Login failed")}catch(a){z("Login failed. Please try again."),console.error(a)}}async function et(){try{V(),Z(),statusRefreshHandle&&(clearInterval(statusRefreshHandle),statusRefreshHandle.value=null),await he(),currentUser=null,We(),A()}catch(e){console.error("Logout failed:",e)}}function A(){document.getElementById("login-container").classList.remove("hidden"),document.getElementById("dashboard-container").classList.add("hidden"),tt()}function ne(){document.getElementById("login-container").classList.add("hidden"),document.getElementById("dashboard-container").classList.remove("hidden"),document.getElementById("currentUser").textContent=o.currentUser.name||"-",document.getElementById("status-panel").classList.add("hidden");const t=document.getElementById("webhooks-section");t&&t.classList.add("hidden");const n=document.getElementById("admin-controls");o.isAdmin?n.classList.remove("hidden"):n.classList.add("hidden");const s=document.getElementById("history-days");s&&(s.value=o.historyDays),He()}function z(e){const t=document.getElementById("login-error");t.textContent=e,t.classList.remove("hidden")}function tt(){document.getElementById("login-error").classList.add("hidden")}function nt(){document.getElementById("error-message").classList.add("hidden")}function se(){document.getElementById("loading").classList.remove("hidden")}function st(){document.getElementById("loading").classList.add("hidden")}function at(){const e=document.getElementById("download-client-filter-btn"),t=document.getElementById("download-client-filter-dropdown"),n=document.getElementById("download-client-filter-close");!e||!t||(e.addEventListener("click",s=>{s.stopPropagation(),t.classList.toggle("open")}),n.addEventListener("click",()=>{t.classList.remove("open")}),document.addEventListener("click",s=>{!t.contains(s.target)&&s.target!==e&&t.classList.remove("open")}),document.addEventListener("downloadClientsUpdated",J),J())}function J(){const e=document.getElementById("download-client-filter-list");e&&(e.innerHTML="",o.downloadClients.forEach((t,n)=>{const s=document.createElement("div");s.className="filter-item",s.dataset.index=n;const a=document.createElement("input");a.type="checkbox",a.id=`client-${n}`,a.checked=o.selectedDownloadClients.includes(n),a.addEventListener("change",()=>ot(n));const l=document.createElement("label");l.htmlFor=`client-${n}`,l.textContent=t.name||`${t.type} (${t.id})`,s.appendChild(a),s.appendChild(l),e.appendChild(s)}),ae())}function ot(e){const t=o.selectedDownloadClients.indexOf(e);t>-1?o.selectedDownloadClients.splice(t,1):o.selectedDownloadClients.push(e),Ae(o.selectedDownloadClients),ae(),Q()}function ae(){const e=document.getElementById("download-client-filter-count");e&&(o.selectedDownloadClients.length===0?e.textContent="All":e.textContent=o.selectedDownloadClients.length)}(function(){const t=Y();t&&document.documentElement.setAttribute("data-theme",t)})();function rt(){const e=document.getElementById("theme-toggle");e&&e.addEventListener("click",()=>{const n=Y()==="dark"?"light":"dark";it(n)})}function it(e){document.documentElement.setAttribute("data-theme",e),Re(e)}function lt(){const e=document.getElementById("downloads-tab"),t=document.getElementById("history-tab");if(document.getElementById("downloads-section"),document.getElementById("history-section"),!e||!t)return;const n=Fe();T(n==="history"?"history":"downloads"),e.addEventListener("click",()=>T("downloads")),t.addEventListener("click",()=>T("history"))}function T(e){const t=document.getElementById("downloads-tab"),n=document.getElementById("history-tab"),s=document.getElementById("tab-downloads"),a=document.getElementById("tab-history");e==="downloads"?(t.classList.add("active"),n.classList.remove("active"),s.classList.remove("hidden"),a.classList.add("hidden"),j("downloads")):e==="history"&&(n.classList.add("active"),t.classList.remove("active"),a.classList.remove("hidden"),s.classList.add("hidden"),j("history"),x())}function ct(){T("downloads")}document.addEventListener("DOMContentLoaded",()=>{const e=document.getElementById("login-form");e&&e.addEventListener("submit",Ze);const t=document.getElementById("logout-btn");t&&t.addEventListener("click",et);const n=document.getElementById("show-all-toggle");n&&n.addEventListener("change",l=>Ne(l.target.checked));const s=document.getElementById("status-toggle");s&&s.addEventListener("click",Je);const a=document.getElementById("home-btn");a&&a.addEventListener("click",ct),rt(),lt(),at(),$e(),Pe(),ge().then(l=>{const c=document.getElementById("app-version");c&&l&&(c.textContent="v"+l)}),Ye()}); diff --git a/public/index.html b/public/index.html index c30ab5a..7356847 100644 --- a/public/index.html +++ b/public/index.html @@ -18,7 +18,7 @@
- -