5b3034e290
Docs Check / Markdown lint (push) Successful in 46s
Build and Push Docker Image / build (push) Successful in 1m40s
Licence Check / Licence compatibility and copyright header verification (push) Successful in 2m22s
CI / Security audit (push) Successful in 2m48s
CI / Swagger Validation & Coverage (push) Successful in 3m3s
Docs Check / Mermaid diagram parse check (push) Successful in 3m9s
CI / Tests & coverage (push) Successful in 3m36s
45 lines
62 KiB
JavaScript
45 lines
62 KiB
JavaScript
const o={currentUser:null,downloads:[],downloadClients:[],selectedDownloadClients:[],isAdmin:!1,showAll:!1,csrfToken:null,ombiBaseUrl:null,ombiRequests: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},ombiWebhook:{enabled:!1,triggers:{requestAvailable:!1,requestApproved:!1,requestDeclined:!1,requestPending:!1,requestProcessing:!1},stats:null},webhookMetrics:null,selectedRequestTypes:["movie","tv"],selectedRequestStatuses:[],requestSortMode:"requestedDate_desc",requestSearchQuery:""},Fe=1200,$e=5*60*1e3,Me=5e3;async function Ue(){try{const[e,t]=await Promise.all([fetch("/api/auth/me"),fetch("/api/auth/csrf")]),s=await e.json(),n=await t.json();return n.csrfToken&&(o.csrfToken=n.csrfToken),s.authenticated?(o.currentUser=s.user,o.isAdmin=!!s.user.isAdmin,{authenticated:!0,user:s.user}):{authenticated:!1}}catch(e){return console.error("Authentication check failed:",e),{authenticated:!1}}}async function We(e,t,s){try{const a=await(await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,rememberMe:s})})).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(n){return console.error(n),{success:!1,error:"Login failed. Please try again."}}}async function He(){try{return await fetch("/api/auth/logout",{method:"POST",headers:o.csrfToken?{"X-CSRF-Token":o.csrfToken}:{}}),o.currentUser=null,o.csrfToken=null,{success:!0}}catch(e){return console.error("Logout failed:",e),{success:!1}}}async function Oe(e=!1){try{const t=new URLSearchParams({days:o.historyDays});o.showAll&&t.set("showAll","true"),e&&t.set("_t",Date.now());const s=await fetch(`/api/history/recent?${t}`);if(!s.ok)throw new Error(`HTTP ${s.status}`);return{success:!0,history:(await s.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":o.csrfToken},body:JSON.stringify({arrQueueId:e.arrQueueId,arrType:e.arrType,arrInstanceUrl:e.arrInstanceUrl,arrInstanceKey:e.arrInstanceKey,arrContentId:e.arrContentId,arrContentIds:e.arrContentIds,arrSeriesId:e.arrSeriesId,arrContentType:e.arrContentType})});if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s.error||`HTTP ${t.status}`)}return{success:!0}}catch(t){throw console.error("[Blocklist] Error:",t),t}}async function je(){try{return(await(await fetch("/health")).json()).version||null}catch{return null}}async function _e(){try{const e=await fetch("/api/dashboard/webhook-metrics");return e.ok?await e.json():null}catch{return null}}async function q(){var e,t;try{const s=_e();let n=!1;try{const h=await fetch("/api/webhook/config");h.ok&&(n=(await h.json()).valid||!1)}catch{}let a=!1,i={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const h=await fetch("/api/sonarr/notifications");if(h.ok){const b=(await h.json()).find(v=>v.name==="Sofarr");a=n&&!!b,b&&(i={onGrab:b.onGrab,onDownload:b.onDownload,onImport:b.onImport,onUpgrade:b.onUpgrade})}}catch{}let l=!1,m={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const h=await fetch("/api/radarr/notifications");if(h.ok){const b=(await h.json()).find(v=>v.name==="Sofarr");l=n&&!!b,b&&(m={onGrab:b.onGrab,onDownload:b.onDownload,onImport:b.onImport,onUpgrade:b.onUpgrade})}}catch{}let u=!1,c={requestAvailable:!1,requestApproved:!1,requestDeclined:!1,requestPending:!1,requestProcessing:!1},g=null;try{const h=await fetch("/api/ombi/webhook/status");if(h.ok){const y=await h.json();u=y.enabled||!1,c=y.triggers||{requestAvailable:!1,requestApproved:!1,requestDeclined:!1,requestPending:!1,requestProcessing:!1},g=y.stats||null}}catch{}o.webhookMetrics=await s;const r=o.webhookMetrics?Object.entries(o.webhookMetrics.instances||{}):[],d=((e=r.find(([h])=>h.includes("sonarr")))==null?void 0:e[1])||null,p=((t=r.find(([h])=>h.includes("radarr")))==null?void 0:t[1])||null;return o.sonarrWebhook={enabled:a,triggers:i,stats:d},o.radarrWebhook={enabled:l,triggers:m,stats:p},o.ombiWebhook={enabled:u,triggers:c,stats:g},{success:!0}}catch(s){return console.error("Failed to fetch webhook status:",s),{success:!1}}}async function Ge(){try{if(!(await fetch("/api/sonarr/notifications/sofarr-webhook",{method:"POST",headers:{"X-CSRF-Token":o.csrfToken||""}})).ok)throw new Error("Failed to enable");return await q(),{success:!0}}catch(e){return console.error("Failed to enable Sonarr webhook:",e),{success:!1,error:e.message}}}async function ze(){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 q(),{success:!0}}catch(e){return console.error("Failed to enable Radarr webhook:",e),{success:!1,error:e.message}}}async function Je(){try{const e=await fetch("/api/sonarr/notifications");if(!e.ok)throw new Error("Failed to fetch notifications");const s=(await e.json()).find(a=>a.name==="Sofarr");if(!s)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(s)})).ok)throw new Error("Test failed");return await q(),{success:!0}}catch(e){return console.error("Failed to test Sonarr webhook:",e),{success:!1,error:e.message}}}async function Qe(){try{const e=await fetch("/api/radarr/notifications");if(!e.ok)throw new Error("Failed to fetch notifications");const s=(await e.json()).find(a=>a.name==="Sofarr");if(!s)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(s)})).ok)throw new Error("Test failed");return await q(),{success:!0}}catch(e){return console.error("Failed to test Radarr webhook:",e),{success:!1,error:e.message}}}async function Ke(){try{if(!(await fetch("/api/ombi/webhook/enable",{method:"POST",headers:{"X-CSRF-Token":o.csrfToken||""}})).ok)throw new Error("Failed to enable");return await q(),{success:!0}}catch(e){return console.error("Failed to enable Ombi webhook:",e),{success:!1,error:e.message}}}async function Xe(){try{if(!(await fetch("/api/ombi/webhook/test",{method:"POST",headers:{"X-CSRF-Token":o.csrfToken||""}})).ok)throw new Error("Test failed");return await q(),{success:!0}}catch(e){return console.error("Failed to test Ombi webhook:",e),{success:!1,error:e.message}}}async function Ve(){try{const e=await fetch("/api/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 Ye(e){if(!e)return"N/A";if(typeof e=="string")return e;const t=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,s)*100)/100+" "+t[s]}function he(e){if(!e||e===0)return"0 B/s";const t=["B/s","KB/s","MB/s","GB/s"];let s=e,n=0;for(;s>=1024&&n<t.length-1;)s/=1024,n++;return`${s.toFixed(2)} ${t[n]}`}function Ze(e){return e?new Date(e).toLocaleString():"N/A"}function $(e){if(!e)return"Never";const t=Math.floor((Date.now()-e)/1e3);if(t<60)return t+"s ago";const s=Math.floor(t/60);if(s<60)return s+"m ago";const n=Math.floor(s/60);return n<24?n+"h ago":Math.floor(n/24)+"d ago"}function ne(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function pe(e){if(!e||e.length===0)return null;const t=document.createElement("p");if(t.className="episode-info",e.length===1){const s=e[0],n="S"+String(s.season).padStart(2,"0")+"E"+String(s.episode).padStart(2,"0");t.textContent=s.title?n+" — "+s.title:n}else{t.textContent="Multiple episodes",t.classList.add("multi-episode");const s=e.map(n=>{const a="S"+String(n.season).padStart(2,"0")+"E"+String(n.episode).padStart(2,"0");return n.title?a+" — "+n.title:a});t.setAttribute("data-tooltip",s.join(`
|
|
`))}return t}function P(e,t,s){const n=document.createDocumentFragment();if(t&&e&&e.length>0){const a=e.filter(l=>!l.matchedUser),i=e.filter(l=>l.matchedUser);for(const l of a){const m=document.createElement("span");m.className="download-user-badge unmatched",m.textContent=l.label,n.appendChild(m)}for(const l of i){const m=document.createElement("span");m.className="download-user-badge",m.textContent=l.matchedUser,n.appendChild(m)}}else if(s){const a=document.createElement("span");a.className="download-user-badge",a.textContent=s,n.appendChild(a)}return n}function fe(e){const t=document.createElement("span");t.className="download-client-logo-wrapper download-card-logo-wrapper";const s=document.createElement("img");return s.className="download-client-logo",s.src=`/images/clients/${e.client}.svg`,s.alt=`${e.instanceName||e.client} icon`,s.title=e.instanceName||e.client,s.onerror=()=>{t.textContent=e.client.charAt(0).toUpperCase(),t.classList.add("fallback")},t.appendChild(s),t}function oe(e){const t=document.createElement("span");if(t.className="service-icons-container",e.ombiLink){const s=document.createElement("img");s.className="service-icon ombi",s.src="/images/ombi.svg",s.alt="Ombi",s.title=e.ombiTooltip||"Ombi",s.href=e.ombiLink;const n=document.createElement("a");n.href=e.ombiLink,n.target="_blank",n.appendChild(s),t.appendChild(n)}if(o.isAdmin&&e.arrLink){const s=document.createElement("img");e.arrType==="sonarr"?(s.className="service-icon sonarr",s.src="/images/sonarr.svg",s.alt="Sonarr"):e.arrType==="radarr"&&(s.className="service-icon radarr",s.src="/images/radarr.svg",s.alt="Radarr"),s.title=e.arrType==="sonarr"?"Sonarr":"Radarr";const n=document.createElement("a");n.href=e.arrLink,n.target="_blank",n.appendChild(s),t.appendChild(n)}return t}function j(){const e=document.getElementById("downloads-list"),t=document.getElementById("no-downloads");let s=o.downloads;if(o.selectedDownloadClients.length>0){const i=o.selectedDownloadClients.map(l=>o.downloadClients[l]).filter(Boolean);s=o.downloads.filter(l=>i.some(m=>m.type===l.client&&m.id===l.instanceId))}if(o.downloadClients.length>0){const i=new Map(o.downloadClients.map((l,m)=>[l.id,m]));s=[...s].sort((l,m)=>{const u=i.get(l.instanceId)??1/0,c=i.get(m.instanceId)??1/0;return u-c})}if(s.length===0){t.classList.remove("hidden"),e.innerHTML="";return}t.classList.add("hidden");const n=new Map;e.querySelectorAll(".download-card").forEach(i=>{n.set(i.dataset.id,i)});const a=new Set;s.forEach(i=>{const l=i.title;a.add(l);const m=n.get(l);if(m)et(m,i);else{const u=st(i);e.appendChild(u)}}),n.forEach((i,l)=>{a.has(l)||i.remove()})}function et(e,t){const s=e.querySelector(".download-header-right");s&&s.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 i=e.querySelector(".download-card-logo-wrapper");i&&i.remove();const l=e.querySelector(".download-header");if(l&&!l.querySelector(".download-header-right")){const r=document.createElement("div");r.className="download-header-right";const d=P(t.tagBadges,o.showAll,t.matchedUserTag);r.appendChild(d),l.appendChild(r)}t.client&&!e.querySelector(".download-card-logo-wrapper")&&e.appendChild(fe(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 h=r.querySelector(".downloaded");h&&(h.style.width=t.progress+"%")}if(d&&(d.textContent=t.progress+"%"),p){const h=parseFloat(t.mb)||parseFloat(t.size),y=parseFloat(t.mbmissing)||0;y>0&&h>0?p.textContent=`(missing ${y.toFixed(1)} of ${h.toFixed(1)} MB)`:p.textContent=""}}const c=e.querySelector('.detail-item[data-label="Speed"] .detail-value');c&&t.speed!==void 0&&(c.textContent=he(t.speed));const g=e.querySelector('.detail-item[data-label="ETA"] .detail-value');if(g&&t.eta!==void 0&&(g.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 tt(e,t){if(console.log("[Blocklist] Clicked, download:",t),console.log("[Blocklist] Required fields:",{arrQueueId:t.arrQueueId,arrType:t.arrType,arrInstanceUrl:t.arrInstanceUrl,arrInstanceKey:t.arrInstanceKey,arrContentId:t.arrContentId,arrContentIds:t.arrContentIds,arrSeriesId:t.arrSeriesId,arrContentType:t.arrContentType,isAdmin:o.isAdmin,canBlocklist:t.canBlocklist}),!!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(s){console.error("[Blocklist] Error:",s),e.disabled=!1,e.textContent="⛔ Blocklist & Search",e.className="blocklist-search-btn error",e.title=`Failed: ${s.message}`,setTimeout(()=>{e.className="blocklist-search-btn",e.title="Remove this release from the download client, add it to the blocklist, and trigger an automatic search"},4e3)}}}function st(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 s=document.createElement("div");s.className="download-info";const n=document.createElement("div");n.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 i=document.createElement("span");if(i.className=`download-status ${e.status}`,i.textContent=e.status,n.appendChild(a),n.appendChild(i),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(`
|
|
`)),n.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",()=>tt(r,e)),n.appendChild(r)}const l=document.createElement("div");l.className="download-header-right";const m=P(e.tagBadges,o.showAll,e.matchedUserTag);l.appendChild(m),n.appendChild(l),e.client&&t.appendChild(fe(e));const u=document.createElement("h3");if(u.className="download-title",u.textContent=e.title,s.appendChild(n),s.appendChild(u),e.seriesName){const r=document.createElement("p");r.className="download-series";const d=oe(e);d.hasChildNodes()&&(r.appendChild(d),r.appendChild(document.createTextNode(" ")));const p=document.createElement("span");p.textContent=`Series: ${e.seriesName}`,r.appendChild(p),s.appendChild(r);const h=pe(e.episodes);h&&s.appendChild(h)}if(e.movieName){const r=document.createElement("p");r.className="download-movie";const d=oe(e);d.hasChildNodes()&&(r.appendChild(d),r.appendChild(document.createTextNode(" ")));const p=document.createElement("span");p.textContent=`Movie: ${e.movieName}`,r.appendChild(p),s.appendChild(r)}const c=document.createElement("div");c.className="download-details";const g=L("Size",Ye(e.size));if(c.appendChild(g),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 h=parseFloat(e.mb)||parseFloat(e.size),y=parseFloat(e.mbmissing)||0,b=parseFloat(e.progress)||0,v=document.createElement("div");if(v.className="progress-bar",b>0){const k=document.createElement("div");k.className="progress-segment downloaded",k.style.width=b+"%",v.appendChild(k)}p.appendChild(v);const x=document.createElement("span");if(x.className="progress-text",x.textContent=e.progress+"%",p.appendChild(x),e.client&&(e.client==="qbittorrent"||e.client==="rtorrent")&&y>0&&h>0){const k=document.createElement("span");k.className="missing-text",k.textContent=`(missing ${y.toFixed(1)} of ${h.toFixed(1)} MB)`,p.appendChild(k)}r.appendChild(d),r.appendChild(p),c.appendChild(r)}if(e.speed&&e.speed>0){const r=L("Speed",he(e.speed));c.appendChild(r)}if(e.eta){const r=L("ETA",e.eta);c.appendChild(r)}if(e.qbittorrent){if(e.seeds!==void 0){const r=L("Seeds",e.seeds);c.appendChild(r)}if(e.peers!==void 0){const r=L("Peers",e.peers);c.appendChild(r)}if(e.availability!==void 0){const r=L("Availability",`${e.availability}%`);parseFloat(e.availability)<100&&r.classList.add("availability-warning"),c.appendChild(r)}}if(e.completedAt){const r=L("Completed",nt(e.completedAt));c.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='<span class="path-label">Download:</span> <span class="path-value">'+ne(e.downloadPath)+"</span>",r.appendChild(d)}if(e.targetPath){const d=document.createElement("div");d.className="path-item",d.innerHTML='<span class="path-label">Target:</span> <span class="path-value">'+ne(e.targetPath)+"</span>",r.appendChild(d)}c.appendChild(r)}return s.appendChild(c),t.appendChild(s),t}function L(e,t){const s=document.createElement("div");s.className="detail-item",s.dataset.label=e;const n=document.createElement("span");n.className="detail-label",n.textContent=e;const a=document.createElement("span");return a.className="detail-value",a.textContent=t,s.appendChild(n),s.appendChild(a),s}function nt(e){return e?new Date(e).toLocaleString():"N/A"}(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(s){console.error("[Migration] Failed to migrate download client filter:",s)}else try{const s=localStorage.getItem("sofarr-download-clients");o.selectedDownloadClients=s?JSON.parse(s):[]}catch(s){console.error("[Migration] Failed to load download client filter:",s),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(){try{const t=localStorage.getItem("sofarr-request-types");t&&(o.selectedRequestTypes=JSON.parse(t))}catch(t){console.error("[Storage] Failed to load request types:",t),o.selectedRequestTypes=["movie","tv"]}try{const t=localStorage.getItem("sofarr-request-statuses");t&&(o.selectedRequestStatuses=JSON.parse(t))}catch(t){console.error("[Storage] Failed to load request statuses:",t),o.selectedRequestStatuses=[]}try{const t=localStorage.getItem("sofarr-request-sort");t&&(o.requestSortMode=t)}catch(t){console.error("[Storage] Failed to load request sort:",t),o.requestSortMode="requestedDate_desc"}try{const t=localStorage.getItem("sofarr-request-search");t!==null&&(o.requestSearchQuery=t)}catch(t){console.error("[Storage] Failed to load request search:",t),o.requestSearchQuery=""}})();function ot(e){localStorage.setItem("sofarr-history-days",e)}function at(e){localStorage.setItem("sofarr-ignore-available",e)}function ge(e){localStorage.setItem("sofarr-download-clients",JSON.stringify(e))}function be(){return localStorage.getItem("sofarr-theme")||"light"}function rt(e){localStorage.setItem("sofarr-theme",e)}function it(){return localStorage.getItem("sofarr-active-tab")||"downloads"}function M(e){localStorage.setItem("sofarr-active-tab",e)}function ye(e){localStorage.setItem("sofarr-request-types",JSON.stringify(e))}function ve(e){localStorage.setItem("sofarr-request-statuses",JSON.stringify(e))}function lt(e){localStorage.setItem("sofarr-request-sort",e)}function ct(e){localStorage.setItem("sofarr-request-search",e)}function ae(e){const t=document.createElement("span");if(t.className="service-icons-container",e.ombiLink){const s=document.createElement("img");s.className="service-icon ombi",s.src="/images/ombi.svg",s.alt="Ombi",s.title=e.ombiTooltip||"Ombi";const n=document.createElement("a");n.href=e.ombiLink,n.target="_blank",n.appendChild(s),t.appendChild(n)}if(o.isAdmin&&e.arrLink){const s=document.createElement("img");e.arrType==="sonarr"?(s.className="service-icon sonarr",s.src="/images/sonarr.svg",s.alt="Sonarr"):e.arrType==="radarr"&&(s.className="service-icon radarr",s.src="/images/radarr.svg",s.alt="Radarr"),s.title=e.arrType==="sonarr"?"Sonarr":"Radarr";const n=document.createElement("a");n.href=e.arrLink,n.target="_blank",n.appendChild(s),t.appendChild(n)}return t}function dt(){const e=document.getElementById("history-days"),t=document.getElementById("history-refresh-btn"),s=document.getElementById("ignore-available-toggle");e&&e.addEventListener("change",()=>{const n=parseInt(e.value,10);n>0&&n<=90&&(historyDays=n,ot(n),N(!0))}),t&&t.addEventListener("click",()=>N(!0)),s&&(s.checked=o.ignoreAvailable,s.addEventListener("change",()=>{o.ignoreAvailable=s.checked,at(o.ignoreAvailable),ke(o.lastHistoryItems)})),document.addEventListener("historyReload",()=>{N(!0)})}function ut(){Ee(),o.historyRefreshHandle=setInterval(()=>N(),$e)}function Ee(){o.historyRefreshHandle&&(clearInterval(o.historyRefreshHandle),o.historyRefreshHandle=null)}function mt(){o.lastHistoryItems=[],document.getElementById("history-list").innerHTML="",document.getElementById("no-history").classList.add("hidden"),document.getElementById("history-error").classList.add("hidden")}async function N(e=!1){document.getElementById("history-list");const t=document.getElementById("history-loading"),s=document.getElementById("history-error"),n=document.getElementById("no-history");t.classList.remove("hidden"),s.classList.add("hidden"),n.classList.add("hidden");try{const a=await Oe(e);t.classList.add("hidden"),a.success?(o.lastHistoryItems=a.history,ke(o.lastHistoryItems)):(s.textContent=a.error||"Failed to load history.",s.classList.remove("hidden"))}catch(a){t.classList.add("hidden"),s.textContent="Failed to load history.",s.classList.remove("hidden"),console.error("[History] Load error:",a)}}function ke(e){const t=document.getElementById("history-list"),s=document.getElementById("no-history");t.innerHTML="";const n=o.ignoreAvailable?e.filter(a=>!(a.outcome==="failed"&&a.availableForUpgrade)):e;if(!n.length){s.classList.remove("hidden");return}s.classList.add("hidden"),n.forEach(a=>t.appendChild(ht(a)))}function ht(e){const t=document.createElement("div");if(t.className=`history-card ${e.type} ${e.outcome}`,e.coverArt){const c=document.createElement("div");c.className="history-cover";const g=document.createElement("img");g.src="/api/dashboard/cover-art?url="+encodeURIComponent(e.coverArt),g.alt=e.movieName||e.seriesName||e.title,g.loading="lazy",c.appendChild(g),t.appendChild(c)}const s=document.createElement("div");s.className="history-info";const n=document.createElement("div");n.className="history-card-header";const a=document.createElement("span");a.className=`history-type-badge ${e.type}`,a.textContent=e.type==="series"?"📺 Series":"🎬 Movie",n.appendChild(a);const i=document.createElement("span");if(i.className=`history-outcome-badge ${e.outcome}`,i.textContent=e.outcome==="imported"?"✓ Imported":"✗ Failed",n.appendChild(i),e.availableForUpgrade){const c=document.createElement("span");c.className="history-upgrade-badge",c.title="A previous version of this item is available. An upgrade download has failed.",c.textContent="⬆ Available",n.appendChild(c)}if(e.instanceName){const c=document.createElement("span");c.className="history-instance-badge",c.textContent=e.instanceName,n.appendChild(c)}const l=P(e.tagBadges,o.showAll,e.matchedUserTag);n.appendChild(l),s.appendChild(n);const m=document.createElement("h3");if(m.className="history-title",m.textContent=e.title,s.appendChild(m),e.seriesName){const c=document.createElement("p");c.className="history-media-name";const g=ae(e);g.hasChildNodes()&&(c.appendChild(g),c.appendChild(document.createTextNode(" ")));const r=document.createElement("span");r.textContent="Series: "+e.seriesName,c.appendChild(r),s.appendChild(c);const d=pe(e.episodes);d&&s.appendChild(d)}if(e.movieName){const c=document.createElement("p");c.className="history-media-name";const g=ae(e);g.hasChildNodes()&&(c.appendChild(g),c.appendChild(document.createTextNode(" ")));const r=document.createElement("span");r.textContent="Movie: "+e.movieName,c.appendChild(r),s.appendChild(c)}const u=document.createElement("div");if(u.className="history-details",e.completedAt&&u.appendChild(re("Completed",Ze(e.completedAt))),e.quality&&u.appendChild(re("Quality",e.quality)),e.outcome==="failed"&&e.failureMessage){const c=document.createElement("div");c.className="history-failure-message",c.textContent=e.failureMessage,u.appendChild(c)}return s.appendChild(u),t.appendChild(s),t}function re(e,t){const s=document.createElement("div");s.className="detail-item",s.dataset.label=e;const n=document.createElement("span");n.className="detail-label",n.textContent=e;const a=document.createElement("span");return a.className="detail-value",a.textContent=t,s.appendChild(n),s.appendChild(a),s}function _(){Se();const e=o.showAll?"?showAll=true":"",t=new EventSource("/api/dashboard/stream"+e);o.sseSource=t;let s=!0;t.onmessage=n=>{try{const a=JSON.parse(n.data);if(o.currentUser=a.user,o.isAdmin=!!a.isAdmin,o.downloads=a.downloads,a.downloadClients){o.downloadClients=a.downloadClients;const i=new CustomEvent("downloadClientsUpdated");document.dispatchEvent(i)}if(a.ombiRequests){o.ombiRequests=a.ombiRequests;const i=new CustomEvent("ombiRequestsUpdated");document.dispatchEvent(i)}a.ombiBaseUrl&&(o.ombiBaseUrl=a.ombiBaseUrl),document.getElementById("currentUser").textContent=o.currentUser||"-",j(),Dt(),s&&(s=!1,At())}catch(a){console.error("[SSE] Failed to parse message:",a)}},t.addEventListener("history-update",n=>{try{const a=JSON.parse(n.data);console.log("[SSE] History update received:",a.type);const i=new CustomEvent("historyReload");document.dispatchEvent(i)}catch(a){console.error("[SSE] Failed to parse history-update message:",a)}}),t.onerror=()=>{console.warn("[SSE] Connection lost, browser will retry...")},console.log("[SSE] Stream connected")}function Se(){o.sseSource&&(o.sseSource.close(),o.sseSource=null,console.log("[SSE] Stream closed"))}function pt(e){o.showAll=e,_();const t=new CustomEvent("historyReload");document.dispatchEvent(t)}function ft(){document.getElementById("webhooks-section")&&(document.getElementById("webhooks-header").addEventListener("click",gt),document.getElementById("enable-sonarr-webhook").addEventListener("click",yt),document.getElementById("enable-radarr-webhook").addEventListener("click",vt),document.getElementById("enable-ombi-webhook").addEventListener("click",St),document.getElementById("test-sonarr-webhook").addEventListener("click",Et),document.getElementById("test-radarr-webhook").addEventListener("click",kt),document.getElementById("test-ombi-webhook").addEventListener("click",wt))}function gt(){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&&we()}async function we(){const e=document.getElementById("webhook-loading");e.classList.remove("hidden");try{(await q()).success&&bt()}catch(t){console.error("Failed to fetch webhook status:",t)}finally{e.classList.add("hidden")}}function bt(){const e=document.getElementById("sonarr-status"),t=document.getElementById("enable-sonarr-webhook"),s=document.getElementById("test-sonarr-webhook"),n=document.getElementById("sonarr-triggers"),a=document.getElementById("sonarr-stats");e.textContent=o.sonarrWebhook.enabled?"● Enabled":"○ Disabled",e.className="status-indicator "+(o.sonarrWebhook.enabled?"enabled":"disabled"),o.sonarrWebhook.enabled?(t.classList.add("hidden"),s.classList.remove("hidden"),n.classList.remove("hidden")):(t.classList.remove("hidden"),s.classList.add("hidden"),n.classList.add("hidden")),o.sonarrWebhook.enabled&&(document.getElementById("sonarr-onGrab").textContent=o.sonarrWebhook.triggers.onGrab?"✓":"✗",document.getElementById("sonarr-onGrab").className="trigger-value "+(o.sonarrWebhook.triggers.onGrab?"active":"inactive"),document.getElementById("sonarr-onDownload").textContent=o.sonarrWebhook.triggers.onDownload?"✓":"✗",document.getElementById("sonarr-onDownload").className="trigger-value "+(o.sonarrWebhook.triggers.onDownload?"active":"inactive"),document.getElementById("sonarr-onImport").textContent=o.sonarrWebhook.triggers.onImport?"✓":"✗",document.getElementById("sonarr-onImport").className="trigger-value "+(o.sonarrWebhook.triggers.onImport?"active":"inactive"),document.getElementById("sonarr-onUpgrade").textContent=o.sonarrWebhook.triggers.onUpgrade?"✓":"✗",document.getElementById("sonarr-onUpgrade").className="trigger-value "+(o.sonarrWebhook.triggers.onUpgrade?"active":"inactive")),o.sonarrWebhook.stats?(a.classList.remove("hidden"),document.getElementById("sonarr-events").textContent=o.sonarrWebhook.stats.eventsReceived??0,document.getElementById("sonarr-polls").textContent=o.sonarrWebhook.stats.pollsSkipped??0,document.getElementById("sonarr-last").textContent=$(o.sonarrWebhook.stats.lastWebhookTimestamp)):a.classList.add("hidden");const i=document.getElementById("radarr-status"),l=document.getElementById("enable-radarr-webhook"),m=document.getElementById("test-radarr-webhook"),u=document.getElementById("radarr-triggers"),c=document.getElementById("radarr-stats");i.textContent=o.radarrWebhook.enabled?"● Enabled":"○ Disabled",i.className="status-indicator "+(o.radarrWebhook.enabled?"enabled":"disabled"),o.radarrWebhook.enabled?(l.classList.add("hidden"),m.classList.remove("hidden"),u.classList.remove("hidden")):(l.classList.remove("hidden"),m.classList.add("hidden"),u.classList.add("hidden")),o.radarrWebhook.enabled&&(document.getElementById("radarr-onGrab").textContent=o.radarrWebhook.triggers.onGrab?"✓":"✗",document.getElementById("radarr-onGrab").className="trigger-value "+(o.radarrWebhook.triggers.onGrab?"active":"inactive"),document.getElementById("radarr-onDownload").textContent=o.radarrWebhook.triggers.onDownload?"✓":"✗",document.getElementById("radarr-onDownload").className="trigger-value "+(o.radarrWebhook.triggers.onDownload?"active":"inactive"),document.getElementById("radarr-onImport").textContent=o.radarrWebhook.triggers.onImport?"✓":"✗",document.getElementById("radarr-onImport").className="trigger-value "+(o.radarrWebhook.triggers.onImport?"active":"inactive"),document.getElementById("radarr-onUpgrade").textContent=o.radarrWebhook.triggers.onUpgrade?"✓":"✗",document.getElementById("radarr-onUpgrade").className="trigger-value "+(o.radarrWebhook.triggers.onUpgrade?"active":"inactive")),o.radarrWebhook.stats?(c.classList.remove("hidden"),document.getElementById("radarr-events").textContent=o.radarrWebhook.stats.eventsReceived??0,document.getElementById("radarr-polls").textContent=o.radarrWebhook.stats.pollsSkipped??0,document.getElementById("radarr-last").textContent=$(o.radarrWebhook.stats.lastWebhookTimestamp)):c.classList.add("hidden");const g=document.getElementById("ombi-status"),r=document.getElementById("enable-ombi-webhook"),d=document.getElementById("test-ombi-webhook"),p=document.getElementById("ombi-triggers"),h=document.getElementById("ombi-stats");g.textContent=o.ombiWebhook.enabled?"● Enabled":"○ Disabled",g.className="status-indicator "+(o.ombiWebhook.enabled?"enabled":"disabled"),o.ombiWebhook.enabled?(r.classList.add("hidden"),d.classList.remove("hidden"),p.classList.remove("hidden")):(r.classList.remove("hidden"),d.classList.add("hidden"),p.classList.add("hidden")),o.ombiWebhook.enabled&&(document.getElementById("ombi-requestAvailable").textContent=o.ombiWebhook.triggers.requestAvailable?"✓":"✗",document.getElementById("ombi-requestAvailable").className="trigger-value "+(o.ombiWebhook.triggers.requestAvailable?"active":"inactive"),document.getElementById("ombi-requestApproved").textContent=o.ombiWebhook.triggers.requestApproved?"✓":"✗",document.getElementById("ombi-requestApproved").className="trigger-value "+(o.ombiWebhook.triggers.requestApproved?"active":"inactive"),document.getElementById("ombi-requestDeclined").textContent=o.ombiWebhook.triggers.requestDeclined?"✓":"✗",document.getElementById("ombi-requestDeclined").className="trigger-value "+(o.ombiWebhook.triggers.requestDeclined?"active":"inactive"),document.getElementById("ombi-requestPending").textContent=o.ombiWebhook.triggers.requestPending?"✓":"✗",document.getElementById("ombi-requestPending").className="trigger-value "+(o.ombiWebhook.triggers.requestPending?"active":"inactive"),document.getElementById("ombi-requestProcessing").textContent=o.ombiWebhook.triggers.requestProcessing?"✓":"✗",document.getElementById("ombi-requestProcessing").className="trigger-value "+(o.ombiWebhook.triggers.requestProcessing?"active":"inactive")),o.ombiWebhook.stats?(h.classList.remove("hidden"),document.getElementById("ombi-events").textContent=o.ombiWebhook.stats.eventsReceived??0,document.getElementById("ombi-polls").textContent=o.ombiWebhook.stats.pollsSkipped??0,document.getElementById("ombi-last").textContent=$(o.ombiWebhook.stats.lastWebhookTimestamp)):h.classList.add("hidden")}async function yt(){E(!0);try{const e=await Ge();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{E(!1)}}async function vt(){E(!0);try{const e=await ze();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{E(!1)}}async function Et(){E(!0);try{const e=await Je();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{E(!1)}}async function kt(){E(!0);try{const e=await Qe();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{E(!1)}}async function St(){E(!0);try{const e=await Ke();e.success||(console.error("Failed to enable Ombi webhook:",e.error),alert("Failed to enable Ombi webhook. Check console for details."))}catch(e){console.error("Failed to enable Ombi webhook:",e),alert("Failed to enable Ombi webhook. Check console for details.")}finally{E(!1)}}async function wt(){E(!0);try{const e=await Xe();e.success?alert("Ombi webhook test sent successfully!"):(console.error("Failed to test Ombi webhook:",e.error),alert("Failed to test Ombi webhook. Check console for details."))}catch(e){console.error("Failed to test Ombi webhook:",e),alert("Failed to test Ombi webhook. Check console for details.")}finally{E(!1)}}function E(e){o.webhookLoading=e,document.getElementById("enable-sonarr-webhook").disabled=e,document.getElementById("enable-radarr-webhook").disabled=e,document.getElementById("enable-ombi-webhook").disabled=e,document.getElementById("test-sonarr-webhook").disabled=e,document.getElementById("test-radarr-webhook").disabled=e,document.getElementById("test-ombi-webhook").disabled=e;const t=document.getElementById("webhook-loading");e?t.classList.remove("hidden"):t.classList.add("hidden")}async function Ct(){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 we()):t&&t.classList.add("hidden"),ie(),o.statusRefreshHandle&&clearInterval(o.statusRefreshHandle),o.statusRefreshHandle=setInterval(ie,Me)}function It(){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 ie(){var s;const e=document.getElementById("status-panel"),t=document.getElementById("status-content");if(console.log("[Status] panel found:",!!e,"contentDiv found:",!!t,"panel display:",(s=e==null?void 0:e.style)==null?void 0:s.display),!(!e||e.classList.contains("hidden"))){console.log("[Status] Refreshing status panel...");try{const n=await Ve();n.success?(console.log("[Status] Got status data, rendering..."),Bt(n.data,e)):(console.error("[Status] API returned error:",n.error),t&&(!t.innerHTML||t.innerHTML.includes("status-loading"))&&(t.innerHTML='<p class="status-error">Failed to load status: '+n.error+"</p>"))}catch(n){console.error("[Status] Error fetching status:",n),t&&(!t.innerHTML||t.innerHTML.includes("status-loading"))&&(t.innerHTML='<p class="status-error">Failed to load status: '+n.message+"</p>")}}}function Bt(e,t){var v,x,k,J,Q,K,X,V,Y,Z,ee,te,se;console.log("[Status] renderStatusPanel called with data:",e?"yes":"no","keys:",e?Object.keys(e):"none");const s=e.server,n=Math.floor(s.uptimeSeconds/3600),a=Math.floor(s.uptimeSeconds%3600/60),i=s.uptimeSeconds%60,l=`${n}h ${a}m ${i}s`,m=(e.cache.totalSizeBytes/1024).toFixed(1);let u=`
|
|
<div class="status-header">
|
|
<h3>Server Status</h3>
|
|
<button class="status-close" id="status-close-btn">×</button>
|
|
</div>
|
|
<div class="status-grid">
|
|
<div class="status-card">
|
|
<div class="status-card-title">Server</div>
|
|
<div class="status-row"><span>Uptime</span><span>${l}</span></div>
|
|
<div class="status-row"><span>Node</span><span>${R(s.nodeVersion)}</span></div>
|
|
<div class="status-row"><span>Memory (RSS)</span><span>${s.memoryUsageMB} MB</span></div>
|
|
<div class="status-row"><span>Heap</span><span>${s.heapUsedMB} / ${s.heapTotalMB} MB</span></div>
|
|
</div>
|
|
<div class="status-card">
|
|
<div class="status-card-title">Data Refresh</div>`;const c=e.polling.intervalMs,r=(e.clients||[]).filter(f=>f.type==="sse");e.polling.enabled?u+=`<div class="status-row"><span>Background poll</span><span>${c/1e3}s</span></div>`:u+='<div class="status-row"><span>Background poll</span><span>Disabled</span></div>';const d=r.length>0?'<span class="status-fg-badge">SSE push</span>':e.polling.enabled?"Background":"On-demand (idle)";u+=`<div class="status-row"><span>Delivery mode</span><span>${d}</span></div>`,u+=`<div class="status-row"><span>SSE clients</span><span>${r.length}</span></div>`;for(const f of r){const I=Math.round((Date.now()-f.connectedAt)/1e3);u+=`<div class="status-row status-row-sub"><span>${R(f.user)}</span><span>connected ${I}s ago</span></div>`}if(u+="</div>",o.isAdmin&&e.webhooks){const f=e.webhooks,I=(v=f.sonarr)!=null&&v.enabled?"●":"○",S=(x=f.radarr)!=null&&x.enabled?"●":"○",B=(k=f.ombi)!=null&&k.enabled?"●":"○",qe=((J=f.sonarr)==null?void 0:J.eventsReceived)||0,xe=((Q=f.radarr)==null?void 0:Q.eventsReceived)||0,Ne=((K=f.ombi)==null?void 0:K.eventsReceived)||0,Re=((X=f.sonarr)==null?void 0:X.pollsSkipped)||0,De=((V=f.radarr)==null?void 0:V.pollsSkipped)||0,Ae=((Y=f.ombi)==null?void 0:Y.pollsSkipped)||0;u+=`
|
|
<div class="status-card">
|
|
<div class="status-card-title">Webhooks</div>
|
|
<div class="status-row"><span>Sonarr</span><span>${I} ${(Z=f.sonarr)!=null&&Z.enabled?"Enabled":"Disabled"}</span></div>
|
|
<div class="status-row"><span>Radarr</span><span>${S} ${(ee=f.radarr)!=null&&ee.enabled?"Enabled":"Disabled"}</span></div>
|
|
<div class="status-row"><span>Ombi</span><span>${B} ${(te=f.ombi)!=null&&te.enabled?"Enabled":"Disabled"}</span></div>
|
|
<div class="status-row status-row-sub"><span>Events</span><span>S:${qe} R:${xe} O:${Ne}</span></div>
|
|
<div class="status-row status-row-sub"><span>Polls skipped</span><span>S:${Re} R:${De} O:${Ae}</span></div>
|
|
</div>`}const p=e.polling.lastPoll;if(p){const f=Math.round((Date.now()-new Date(p.timestamp).getTime())/1e3);u+=`
|
|
<div class="status-card status-card-wide">
|
|
<div class="status-card-title">Last Poll (${p.totalMs}ms total, ${f}s ago)</div>
|
|
<div class="status-timings">`;const I=p.tasks.reduce((S,B)=>Math.max(S,B.ms),1);for(const S of p.tasks){const B=Math.max(2,S.ms/I*100);u+=`
|
|
<div class="timing-row">
|
|
<span class="timing-label">${R(S.label)}</span>
|
|
<div class="timing-bar-bg"><div class="timing-bar" data-w="${B.toFixed(1)}"></div></div>
|
|
<span class="timing-value">${S.ms}ms</span>
|
|
</div>`}u+="</div></div>"}u+=`
|
|
<div class="status-card status-card-wide">
|
|
<div class="status-card-title">Cache (${e.cache.entryCount} entries, ${m} KB)</div>
|
|
<table class="status-table">
|
|
<thead><tr><th>Key</th><th>Items</th><th>Size</th><th>TTL</th></tr></thead>
|
|
<tbody>`;for(const f of e.cache.entries){const I=f.sizeBytes>1024?(f.sizeBytes/1024).toFixed(1)+" KB":f.sizeBytes+" B",S=f.expired?'<span class="status-expired">expired</span>':(f.ttlRemainingMs/1e3).toFixed(0)+"s",B=f.itemCount!==null?f.itemCount:"—";u+=`<tr><td><code>${R(f.key)}</code></td><td>${B}</td><td>${I}</td><td>${S}</td></tr>`}u+="</tbody></table></div></div>";const h=document.getElementById("status-content"),y=document.getElementById("status-panel");console.log("[Status] contentDiv found:",!!h,"panel children:",(se=y==null?void 0:y.children)==null?void 0:se.length,"HTML length:",u.length),y&&console.log("[Status] panel innerHTML preview:",y.innerHTML.substring(0,200)),h?(h.innerHTML=u,console.log("[Status] HTML rendered, contentDiv innerHTML length:",h.innerHTML.length)):console.error("[Status] contentDiv not found!");const b=document.getElementById("status-close-btn");b&&b.addEventListener("click",It),t.querySelectorAll(".timing-bar[data-w]").forEach(f=>{f.style.width=f.dataset.w+"%"})}function R(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function Lt(){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 Tt(){const e=document.getElementById("splash-screen");e.classList.remove("hidden"),e.style.opacity="1",e.classList.remove("fade-out")}function D(e){return new Promise(t=>{const s=Date.now()-(e||0),n=Math.max(0,Fe-s);setTimeout(()=>{const a=document.getElementById("splash-screen");a.classList.add("fade-out");const l=setTimeout(()=>{a.classList.add("hidden"),t()},400+100);a.addEventListener("transitionend",()=>{clearTimeout(l),a.classList.add("hidden"),t()},{once:!0})},n)})}async function qt(){const e=Date.now();try{(await Ue()).authenticated?(Ce(),Ie(),_(),await D(e)):(await D(e),W())}catch(t){console.error("Authentication check failed:",t),await D(e),W()}}async function xt(e){e.preventDefault();const t=document.getElementById("username").value,s=document.getElementById("password").value,n=document.getElementById("remember-me").checked;try{const a=await We(t,s,n);if(a.success){await Lt(),Tt(),await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(l))),Ce(),Ie();const i=Date.now();_(),await D(i)}else le(a.error||"Login failed")}catch(a){le("Login failed. Please try again."),console.error(a)}}async function Nt(){try{Se(),Ee(),o.statusRefreshHandle&&(clearInterval(o.statusRefreshHandle),o.statusRefreshHandle=null),await He(),o.currentUser=null,mt(),W()}catch(e){console.error("Logout failed:",e)}}function W(){document.getElementById("login-container").classList.remove("hidden"),document.getElementById("dashboard-container").classList.add("hidden"),Rt()}function Ce(){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 s=document.getElementById("admin-controls");o.isAdmin?s.classList.remove("hidden"):s.classList.add("hidden");const n=document.getElementById("history-days");n&&(n.value=o.historyDays),ut()}function le(e){const t=document.getElementById("login-error");t.textContent=e,t.classList.remove("hidden")}function Rt(){document.getElementById("login-error").classList.add("hidden")}function Dt(){document.getElementById("error-message").classList.add("hidden")}function Ie(){document.getElementById("loading").classList.remove("hidden")}function At(){document.getElementById("loading").classList.add("hidden")}function Ft(){const e=document.getElementById("download-client-dropdown-btn"),t=document.getElementById("download-client-dropdown"),s=document.getElementById("download-client-select-all"),n=document.getElementById("download-client-deselect-all");!e||!t||(e.addEventListener("click",a=>{a.stopPropagation(),t.classList.toggle("open")}),s&&s.addEventListener("click",()=>ce(!0)),n&&n.addEventListener("click",()=>ce(!1)),document.addEventListener("click",a=>{!t.contains(a.target)&&a.target!==e&&!e.contains(a.target)&&t.classList.remove("open")}),document.addEventListener("downloadClientsUpdated",H),H())}function H(){const e=document.getElementById("download-client-options");e&&(e.innerHTML="",o.downloadClients.forEach((t,s)=>{const n=document.createElement("div");n.className="download-client-option",n.dataset.index=s;const a=document.createElement("input");a.type="checkbox",a.className="download-client-checkbox",a.id=`client-${s}`,a.checked=o.selectedDownloadClients.includes(s),a.addEventListener("change",()=>$t(s));const i=document.createElement("span");i.className="download-client-icon";const l=document.createElement("img");l.src=`/images/clients/${t.type}.svg`,l.alt=`${t.name||t.type} icon`,l.onerror=()=>{i.textContent=t.type.charAt(0).toUpperCase(),i.classList.add("fallback")},i.appendChild(l);const m=document.createElement("label");m.className="download-client-option-label",m.htmlFor=`client-${s}`,m.textContent=t.name||`${t.type} (${t.id})`;const u=document.createElement("span");u.className="download-client-type",u.textContent=t.type,n.appendChild(a),n.appendChild(i),n.appendChild(m),n.appendChild(u),e.appendChild(n)}),Be())}function $t(e){const t=o.selectedDownloadClients.indexOf(e);t>-1?o.selectedDownloadClients.splice(t,1):o.selectedDownloadClients.push(e),ge(o.selectedDownloadClients),Be(),j()}function ce(e){e?o.selectedDownloadClients=o.downloadClients.map((t,s)=>s):o.selectedDownloadClients=[],ge(o.selectedDownloadClients),H(),j()}function Be(){const e=document.getElementById("download-client-selected-text");if(e)if(o.selectedDownloadClients.length===0)e.textContent="All clients";else if(o.selectedDownloadClients.length===o.downloadClients.length)e.textContent="All clients";else{const t=o.selectedDownloadClients.map(s=>{var n,a;return((n=o.downloadClients[s])==null?void 0:n.name)||((a=o.downloadClients[s])==null?void 0:a.type)||""}).filter(Boolean);t.length===1?e.textContent=t[0]:e.textContent=`${o.selectedDownloadClients.length} clients`}}function Le(e){return e?e.available?"available":e.denied?"denied":e.approved?"approved":e.requested?"pending":"unknown":"unknown"}function Mt(e,t){if(!t||t.length===0)return e;const s=t.map(n=>n.toLowerCase());return s.includes("all")?e:e.filter(n=>s.includes(n.mediaType))}function Ut(e,t){if(!t||t.length===0)return e;const s=t.map(n=>n.toLowerCase());return e.filter(n=>s.includes(Le(n)))}function Wt(e,t){if(!t||t.trim()==="")return e;const s=t.trim().toLowerCase();return e.filter(n=>(n.title||"").toLowerCase().includes(s))}function Ht(e,t){const s=[...e];switch(t){case"requestedDate_asc":return s.sort((n,a)=>{const i=n.requestedDate?new Date(n.requestedDate).getTime():0,l=a.requestedDate?new Date(a.requestedDate).getTime():0;return i-l});case"title_asc":return s.sort((n,a)=>(n.title||"").localeCompare(a.title||""));case"title_desc":return s.sort((n,a)=>(a.title||"").localeCompare(n.title||""));case"requestedDate_desc":default:return s.sort((n,a)=>{const i=n.requestedDate?new Date(n.requestedDate).getTime():0;return(a.requestedDate?new Date(a.requestedDate).getTime():0)-i})}}function Ot(e,{types:t,statuses:s,sort:n,search:a}={}){let i=[...e];return i=Mt(i,t),i=Ut(i,s),i=Wt(i,a),i=Ht(i,n),i}function O(e){if(!e)return"";const t=e.requestedUser||e.RequestedUser||e.user||e.User||e.requestedBy||e.RequestedBy||e.ombiUser||e.OmbiUser||e.requestedByUser||e.RequestedByUser;if(t&&typeof t=="object"){const n=t.alias||t.Alias||t.userAlias||t.UserAlias||t.userName||t.UserName||t.normalizedUserName||t.NormalizedUserName||t.displayName||t.DisplayName||t.email||t.Email;if(n)return n}if(t&&typeof t=="string")return t;const s=e.requestedByAlias||e.RequestedByAlias||e.requestedByUsername||e.RequestedByUsername||e.requester||e.Requester||e.requestedByEmail||e.RequestedByEmail;if(s)return s;if(Array.isArray(e.seasons))for(const n of e.seasons){const a=O(n);if(a)return a}if(Array.isArray(e.childRequests))for(const n of e.childRequests){const a=O(n);if(a)return a}return""}function C(){const e=document.getElementById("requests-list"),t=document.getElementById("no-requests");if(!e)return;const s=o.ombiRequests||{movie:[],tv:[]},n=[...s.movie.map(i=>({...i,mediaType:"movie"})),...s.tv.map(i=>({...i,mediaType:"tv"}))],a=Ot(n,{types:o.selectedRequestTypes,statuses:o.selectedRequestStatuses,sort:o.requestSortMode,search:o.requestSearchQuery});if(e.innerHTML="",a.length===0){if(t){t.style.display="block";const i=t.querySelector("p");if(i){const l=n.length>0;i.textContent=l?"No requests match your filters.":"No requests found."}}return}t&&(t.style.display="none"),a.forEach(i=>{const l=Pt(i);e.appendChild(l)})}function Pt(e){if(!e){const r=document.createElement("div");return r.className="request-card",r.textContent="Invalid request data",r}const t=document.createElement("div");t.className="request-card";const s=document.createElement("span");s.className=`request-type-icon ${e.mediaType||""}`,s.textContent=e.mediaType==="movie"?"🎬":"📺";const n=document.createElement("div");n.className="request-content";const a=document.createElement("div");a.className="request-title",a.textContent=e.title||"Unknown Title";const i=document.createElement("div");i.className="request-meta";const l=jt(e);if(i.appendChild(l),e.year){const r=document.createElement("span");r.className="request-year",r.textContent=e.year,i.appendChild(r)}const m=O(e),u=document.createElement("span");u.className="request-user",m?u.textContent=`Requested by: ${m}`:(u.textContent="Requested by: Unknown (Ombi)",u.title="No user information received from Ombi",u.style.cursor="help",u.style.textDecoration="underline dotted"),i.appendChild(u);const c=e.requestedDate||e.RequestedDate||e.date||e.Date;if(c){const r=document.createElement("span");r.className="request-date";try{const d=new Date(c);if(isNaN(d.getTime()))r.textContent=`Date: ${c}`;else{const p=d.getFullYear(),h=String(d.getMonth()+1).padStart(2,"0"),y=String(d.getDate()).padStart(2,"0"),b=String(d.getHours()).padStart(2,"0"),v=String(d.getMinutes()).padStart(2,"0");r.textContent=`Date: ${p}-${h}-${y} ${b}:${v}`}}catch{r.textContent=`Date: ${c}`}i.appendChild(r)}if(e.quality){const r=document.createElement("span");r.className="request-quality",r.textContent=e.quality,i.appendChild(r)}n.appendChild(a),n.appendChild(i);const g=document.createElement("span");if(g.className="service-icons-container",o.ombiBaseUrl&&e.theMovieDbId){const r=document.createElement("a");r.className="ombi-link",r.href=`${o.ombiBaseUrl}/details/${e.mediaType||"movie"}/${e.theMovieDbId}`,r.target="_blank",r.title="View in Ombi";const d=document.createElement("img");d.className="service-icon ombi",d.src="/images/ombi.svg",d.alt="Ombi",r.appendChild(d),g.appendChild(r)}if(o.isAdmin&&e.arrLink){const r=document.createElement("a");r.className=`${e.arrType}-link`,r.href=e.arrLink,r.target="_blank",r.title=`View in ${e.arrType==="sonarr"?"Sonarr":"Radarr"}`;const d=document.createElement("img");d.className=`service-icon ${e.arrType}`,d.src=e.arrType==="sonarr"?"/images/sonarr.svg":"/images/radarr.svg",d.alt=e.arrType==="sonarr"?"Sonarr":"Radarr",r.appendChild(d),g.appendChild(r)}return t.appendChild(s),t.appendChild(n),t.appendChild(g),t}function jt(e){const t=document.createElement("span");t.className="request-status-badge";const s=Le(e),n={available:"Available",denied:`Denied: ${e.deniedReason||"No reason"}`,approved:"Approved",pending:"Pending",unknown:"Unknown"};return t.classList.add(s),t.textContent=n[s]||"Unknown",t}function _t(){const e=document.getElementById("request-type-filter-btn"),t=document.getElementById("request-type-filter-dropdown"),s=document.getElementById("request-type-select-all"),n=document.getElementById("request-type-deselect-all");if(!e||!t)return;e.addEventListener("click",i=>{i.stopPropagation(),t.classList.toggle("open")}),s==null||s.addEventListener("click",()=>de(!0)),n==null||n.addEventListener("click",()=>de(!1)),t.querySelectorAll(".request-filter-checkbox").forEach(i=>{i.addEventListener("change",()=>{const l=i.closest(".request-filter-option").dataset.value;Gt(l,i.checked)})}),G()}function de(e){const s=document.getElementById("request-type-filter-dropdown").querySelectorAll(".request-filter-checkbox"),n=[];s.forEach(a=>{a.checked=e,e&&n.push(a.closest(".request-filter-option").dataset.value)}),o.selectedRequestTypes=e?n:[],ye(o.selectedRequestTypes),G(),C()}function Gt(e,t){const s=o.selectedRequestTypes.indexOf(e);t&&s===-1?o.selectedRequestTypes.push(e):!t&&s>-1&&o.selectedRequestTypes.splice(s,1),ye(o.selectedRequestTypes),G(),C()}function G(){const e=document.getElementById("request-type-selected-text");if(!e)return;const s=document.getElementById("request-type-filter-dropdown").querySelectorAll(".request-filter-checkbox");s.forEach(n=>{const a=n.closest(".request-filter-option").dataset.value;n.checked=o.selectedRequestTypes.includes(a)}),o.selectedRequestTypes.length===0||o.selectedRequestTypes.length===s.length?e.textContent="All":e.textContent=o.selectedRequestTypes.length}function zt(){const e=document.getElementById("request-status-filter-btn"),t=document.getElementById("request-status-filter-dropdown"),s=document.getElementById("request-status-select-all"),n=document.getElementById("request-status-deselect-all");if(!e||!t)return;e.addEventListener("click",i=>{i.stopPropagation(),t.classList.toggle("open")}),s==null||s.addEventListener("click",()=>ue(!0)),n==null||n.addEventListener("click",()=>ue(!1)),t.querySelectorAll(".request-filter-checkbox").forEach(i=>{i.addEventListener("change",()=>{const l=i.closest(".request-filter-option").dataset.value;Jt(l,i.checked)})}),z()}function ue(e){const s=document.getElementById("request-status-filter-dropdown").querySelectorAll(".request-filter-checkbox"),n=[];s.forEach(a=>{a.checked=e,e&&n.push(a.closest(".request-filter-option").dataset.value)}),o.selectedRequestStatuses=e?n:[],ve(o.selectedRequestStatuses),z(),C()}function Jt(e,t){const s=o.selectedRequestStatuses.indexOf(e);t&&s===-1?o.selectedRequestStatuses.push(e):!t&&s>-1&&o.selectedRequestStatuses.splice(s,1),ve(o.selectedRequestStatuses),z(),C()}function z(){const e=document.getElementById("request-status-selected-text");if(!e)return;const s=document.getElementById("request-status-filter-dropdown").querySelectorAll(".request-filter-checkbox");s.forEach(n=>{const a=n.closest(".request-filter-option").dataset.value;n.checked=o.selectedRequestStatuses.includes(a)}),o.selectedRequestStatuses.length===0||o.selectedRequestStatuses.length===s.length?e.textContent="All":e.textContent=o.selectedRequestStatuses.length}function Qt(){const e=document.getElementById("request-sort-select");e&&(e.value=o.requestSortMode,e.addEventListener("change",t=>{o.requestSortMode=t.target.value,lt(o.requestSortMode),C()}))}function Kt(){const e=document.getElementById("request-search-input");if(!e)return;e.value=o.requestSearchQuery;let t;e.addEventListener("input",s=>{clearTimeout(t),t=setTimeout(()=>{o.requestSearchQuery=s.target.value,ct(o.requestSearchQuery),C()},200)})}function Xt(){document.addEventListener("click",e=>{const t=document.getElementById("request-type-filter-dropdown"),s=document.getElementById("request-type-filter-btn"),n=document.getElementById("request-status-filter-dropdown"),a=document.getElementById("request-status-filter-btn");t&&!t.contains(e.target)&&e.target!==s&&!(s!=null&&s.contains(e.target))&&t.classList.remove("open"),n&&!n.contains(e.target)&&e.target!==a&&!(a!=null&&a.contains(e.target))&&n.classList.remove("open")})}function Vt(){_t(),zt(),Qt(),Kt(),Xt(),document.addEventListener("ombiRequestsUpdated",()=>{C()})}(function(){const t=be()||"light";document.documentElement.setAttribute("data-theme",t)})();function Yt(){const e=document.querySelectorAll(".theme-btn"),t=be()||"light";e.forEach(s=>{s.getAttribute("data-theme")===t?s.classList.add("active"):s.classList.remove("active"),s.addEventListener("click",()=>{const n=s.getAttribute("data-theme");n&&Zt(n)})})}function Zt(e){document.documentElement.setAttribute("data-theme",e),rt(e),document.querySelectorAll(".theme-btn").forEach(s=>{s.getAttribute("data-theme")===e?s.classList.add("active"):s.classList.remove("active")})}function es(){const e=document.querySelector('[data-tab="downloads"]'),t=document.querySelector('[data-tab="requests"]'),s=document.querySelector('[data-tab="history"]');if(!e||!s)return;const n=it();T(n==="requests"?"requests":n==="history"?"history":"downloads"),e.addEventListener("click",()=>T("downloads")),t&&t.addEventListener("click",()=>T("requests")),s.addEventListener("click",()=>T("history"))}function T(e){const t=document.querySelector('[data-tab="downloads"]'),s=document.querySelector('[data-tab="requests"]'),n=document.querySelector('[data-tab="history"]'),a=document.getElementById("tab-downloads"),i=document.getElementById("tab-requests"),l=document.getElementById("tab-history");t&&t.classList.remove("active"),s&&s.classList.remove("active"),n&&n.classList.remove("active"),a&&a.classList.add("hidden"),i&&i.classList.add("hidden"),l&&l.classList.add("hidden"),e==="downloads"?(t&&t.classList.add("active"),a&&a.classList.remove("hidden"),M("downloads")):e==="requests"?(s&&s.classList.add("active"),i&&i.classList.remove("hidden"),M("requests"),C()):e==="history"&&(n&&n.classList.add("active"),l&&l.classList.remove("hidden"),M("history"),N())}function ts(){T("downloads")}const w=[],ss=20,ns=2e3,os=console.log,as=console.warn,F=console.error;let A=!1,me=!1,rs=null;function is(e){return e.map(t=>{if(t===null)return"null";if(t===void 0)return"undefined";if(t instanceof Error)return`${t.name}: ${t.message}
|
|
${t.stack||""}`;if(typeof t=="object")try{return JSON.stringify(t)}catch{return String(t)}return String(t)}).join(" ")}function U(e,t){const s=is(t);e==="info"?os.apply(console,t):e==="warn"?as.apply(console,t):e==="error"&&F.apply(console,t),!A&&(w.push({timestamp:new Date().toISOString(),level:e,message:s}),w.length>=ss&&Te())}async function Te(){if(w.length===0||A)return;A=!0;const e=[...w];w.length=0;try{const t=await fetch("/api/debug/client-logs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0});t.ok||F.call(console,"[clientLogCapture] Ingestion server returned error status:",t.status)}catch(t){F.call(console,"[clientLogCapture] Ingestion post request failed:",t.message)}finally{A=!1}}function ls(){if(w.length===0)return;const e=[...w];w.length=0;try{const t=new Blob([JSON.stringify(e)],{type:"application/json"});navigator.sendBeacon("/api/debug/client-logs",t)}catch{try{fetch("/api/debug/client-logs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch{}}}async function cs(){if(!me)try{const e=await fetch("/api/debug/status");if(!e.ok)return;const t=await e.json();t&&t.enabled===!0&&(console.log=(...s)=>U("info",s),console.warn=(...s)=>U("warn",s),console.error=(...s)=>U("error",s),rs=setInterval(Te,ns),window.addEventListener("beforeunload",ls),me=!0,console.log("[clientLogCapture] Browser console logging interceptor initialized successfully."))}catch(e){F.call(console,"[clientLogCapture] Check failed to start interceptor:",e.message)}}document.addEventListener("DOMContentLoaded",()=>{cs();const e=document.getElementById("login-form");e&&e.addEventListener("submit",xt);const t=document.getElementById("logout-btn");t&&t.addEventListener("click",Nt);const s=document.getElementById("show-all-toggle");s&&s.addEventListener("change",i=>pt(i.target.checked));const n=document.getElementById("status-btn");n&&n.addEventListener("click",Ct);const a=document.getElementById("home-btn");a&&a.addEventListener("click",ts),Yt(),es(),Ft(),Vt(),dt(),ft(),je().then(i=>{const l=document.getElementById("app-version");l&&i&&(l.textContent="v"+i)}),qt()});
|