45 lines
63 KiB
JavaScript
45 lines
63 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:""},$e=1200,Fe=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 x(){var e,t;try{const s=_e();let n=!1;try{const d=await fetch("/api/webhook/config");d.ok&&(n=(await d.json()).valid||!1)}catch{}let a=!1,r={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const d=await fetch("/api/sonarr/notifications");if(d.ok){const b=(await d.json()).find(v=>v.name==="Sofarr");a=n&&!!b,b&&(r={onGrab:b.onGrab,onDownload:b.onDownload,onImport:b.onImport,onUpgrade:b.onUpgrade})}}catch{}let l=!1,h={onGrab:!1,onDownload:!1,onImport:!1,onUpgrade:!1};try{const d=await fetch("/api/radarr/notifications");if(d.ok){const b=(await d.json()).find(v=>v.name==="Sofarr");l=n&&!!b,b&&(h={onGrab:b.onGrab,onDownload:b.onDownload,onImport:b.onImport,onUpgrade:b.onUpgrade})}}catch{}let m=!1,u={requestAvailable:!1,requestApproved:!1,requestDeclined:!1,requestPending:!1,requestProcessing:!1},g=null;try{const d=await fetch("/api/ombi/webhook/status");if(d.ok){const y=await d.json();m=y.enabled||!1,u=y.triggers||{requestAvailable:!1,requestApproved:!1,requestDeclined:!1,requestPending:!1,requestProcessing:!1},g=y.stats||null}}catch{}o.webhookMetrics=await s;const i=o.webhookMetrics?Object.entries(o.webhookMetrics.instances||{}):[],p=((e=i.find(([d])=>d.includes("sonarr")))==null?void 0:e[1])||null,c=((t=i.find(([d])=>d.includes("radarr")))==null?void 0:t[1])||null;return o.sonarrWebhook={enabled:a,triggers:r,stats:p},o.radarrWebhook={enabled:l,triggers:h,stats:c},o.ombiWebhook={enabled:m,triggers:u,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 x(),{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 x(),{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 x(),{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 x(),{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 x(),{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 x(),{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 F(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),r=e.filter(l=>l.matchedUser);for(const l of a){const h=document.createElement("span");h.className="download-user-badge unmatched",h.textContent=l.label,n.appendChild(h)}for(const l of r){const h=document.createElement("span");h.className="download-user-badge",h.textContent=l.matchedUser,n.appendChild(h)}}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 r=o.selectedDownloadClients.map(l=>o.downloadClients[l]).filter(Boolean);s=o.downloads.filter(l=>r.some(h=>h.type===l.client&&h.id===l.instanceId))}if(o.downloadClients.length>0){const r=new Map(o.downloadClients.map((l,h)=>[l.id,h]));s=[...s].sort((l,h)=>{const m=r.get(l.instanceId)??1/0,u=r.get(h.instanceId)??1/0;return m-u})}if(s.length===0){t.classList.remove("hidden"),e.innerHTML="";return}t.classList.add("hidden");const n=new Map;e.querySelectorAll(".download-card").forEach(r=>{n.set(r.dataset.id,r)});const a=new Set;s.forEach(r=>{const l=r.title;a.add(l);const h=n.get(l);if(h)et(h,r);else{const m=st(r);e.appendChild(m)}}),n.forEach((r,l)=>{a.has(l)||r.remove()})}function et(e,t){const s=e.querySelector(".download-header-right");s&&s.remove(),e.querySelectorAll(".download-header .download-user-badge").forEach(i=>i.remove());const a=e.querySelector(".download-header .download-client-logo-wrapper");a&&a.remove();const r=e.querySelector(".download-card-logo-wrapper");r&&r.remove();const l=e.querySelector(".download-header");if(l&&!l.querySelector(".download-header-right")){const i=document.createElement("div");i.className="download-header-right";const p=P(t.tagBadges,o.showAll,t.matchedUserTag);i.appendChild(p),l.appendChild(i)}t.client&&!e.querySelector(".download-card-logo-wrapper")&&e.appendChild(fe(t));const h=e.querySelector(".download-status");h&&h.textContent!==t.status&&(h.textContent=t.status,h.className=`download-status ${t.status}`);const m=e.querySelector(".progress-container");if(m&&t.progress!==void 0){const i=m.querySelector(".progress-bar"),p=m.querySelector(".progress-text"),c=m.querySelector(".missing-text");if(i){const d=i.querySelector(".downloaded");d&&(d.style.width=t.progress+"%")}if(p&&(p.textContent=t.progress+"%"),c){const d=parseFloat(t.mb)||parseFloat(t.size),y=parseFloat(t.mbmissing)||0;y>0&&d>0?c.textContent=`(missing ${y.toFixed(1)} of ${d.toFixed(1)} MB)`:c.textContent=""}}const u=e.querySelector('.detail-item[data-label="Speed"] .detail-value');u&&t.speed!==void 0&&(u.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 i=e.querySelector('.detail-item[data-label="Seeds"] .detail-value');i&&t.seeds!==void 0&&(i.textContent=t.seeds);const p=e.querySelector('.detail-item[data-label="Peers"] .detail-value');p&&t.peers!==void 0&&(p.textContent=t.peers);const c=e.querySelector('.detail-item[data-label="Availability"]');c&&t.availability!==void 0&&(c.querySelector(".detail-value").textContent=`${t.availability}%`,c.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 i=document.createElement("div");i.className="download-cover";const p=document.createElement("img");p.src=e.coverArt?"/api/dashboard/cover-art?url="+encodeURIComponent(e.coverArt):"",p.alt=e.movieName||e.seriesName||e.title,p.loading="lazy",i.appendChild(p),t.appendChild(i)}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 i=e.instanceName?` (${e.instanceName})`:"";a.textContent=`📥 Torrent${i}`}else a.textContent=e.type;const r=document.createElement("span");if(r.className=`download-status ${e.status}`,r.textContent=e.status,n.appendChild(a),n.appendChild(r),e.importIssues&&e.importIssues.length>0){const i=document.createElement("span");i.className="import-issue-badge",i.textContent="Import Pending",i.setAttribute("data-tooltip",e.importIssues.join(`
|
|
`)),n.appendChild(i)}if((o.isAdmin||e.canBlocklist)&&e.arrQueueId){const i=document.createElement("button");i.className="blocklist-search-btn",i.textContent="⛔ Blocklist & Search",i.title="Remove this release from the download client, add it to the blocklist, and trigger a new automatic search",i.addEventListener("click",()=>tt(i,e)),n.appendChild(i)}const l=document.createElement("div");l.className="download-header-right";const h=P(e.tagBadges,o.showAll,e.matchedUserTag);l.appendChild(h),n.appendChild(l),e.client&&t.appendChild(fe(e));const m=document.createElement("h3");if(m.className="download-title",m.textContent=e.title,s.appendChild(n),s.appendChild(m),e.seriesName){const i=document.createElement("p");i.className="download-series";const p=oe(e);p.hasChildNodes()&&(i.appendChild(p),i.appendChild(document.createTextNode(" ")));const c=document.createElement("span");c.textContent=`Series: ${e.seriesName}`,i.appendChild(c),s.appendChild(i);const d=pe(e.episodes);d&&s.appendChild(d)}if(e.movieName){const i=document.createElement("p");i.className="download-movie";const p=oe(e);p.hasChildNodes()&&(i.appendChild(p),i.appendChild(document.createTextNode(" ")));const c=document.createElement("span");c.textContent=`Movie: ${e.movieName}`,i.appendChild(c),s.appendChild(i)}const u=document.createElement("div");u.className="download-details";const g=T("Size",Ye(e.size));if(u.appendChild(g),e.progress!==void 0){const i=document.createElement("div");i.className="detail-item progress-item",i.dataset.label="Progress";const p=document.createElement("span");p.className="detail-label",p.textContent="Progress";const c=document.createElement("div");c.className="progress-container";const d=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 E=document.createElement("div");E.className="progress-segment downloaded",E.style.width=b+"%",v.appendChild(E)}c.appendChild(v);const w=document.createElement("span");if(w.className="progress-text",w.textContent=e.progress+"%",c.appendChild(w),e.client&&(e.client==="qbittorrent"||e.client==="rtorrent")&&y>0&&d>0){const E=document.createElement("span");E.className="missing-text",E.textContent=`(missing ${y.toFixed(1)} of ${d.toFixed(1)} MB)`,c.appendChild(E)}i.appendChild(p),i.appendChild(c),u.appendChild(i)}if(e.speed&&e.speed>0){const i=T("Speed",he(e.speed));u.appendChild(i)}if(e.eta){const i=T("ETA",e.eta);u.appendChild(i)}if(e.qbittorrent){if(e.seeds!==void 0){const i=T("Seeds",e.seeds);u.appendChild(i)}if(e.peers!==void 0){const i=T("Peers",e.peers);u.appendChild(i)}if(e.availability!==void 0){const i=T("Availability",`${e.availability}%`);parseFloat(e.availability)<100&&i.classList.add("availability-warning"),u.appendChild(i)}}if(e.completedAt){const i=T("Completed",nt(e.completedAt));u.appendChild(i)}if(o.isAdmin&&(e.downloadPath||e.targetPath)){const i=document.createElement("div");if(i.className="download-paths",e.downloadPath){const p=document.createElement("div");p.className="path-item",p.innerHTML='<span class="path-label">Download:</span> <span class="path-value">'+ne(e.downloadPath)+"</span>",i.appendChild(p)}if(e.targetPath){const p=document.createElement("div");p.className="path-item",p.innerHTML='<span class="path-label">Target:</span> <span class="path-value">'+ne(e.targetPath)+"</span>",i.appendChild(p)}u.appendChild(i)}return s.appendChild(u),t.appendChild(s),t}function T(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(),Fe)}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 u=document.createElement("div");u.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",u.appendChild(g),t.appendChild(u)}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 r=document.createElement("span");if(r.className=`history-outcome-badge ${e.outcome}`,r.textContent=e.outcome==="imported"?"✓ Imported":"✗ Failed",n.appendChild(r),e.availableForUpgrade){const u=document.createElement("span");u.className="history-upgrade-badge",u.title="A previous version of this item is available. An upgrade download has failed.",u.textContent="⬆ Available",n.appendChild(u)}if(e.instanceName){const u=document.createElement("span");u.className="history-instance-badge",u.textContent=e.instanceName,n.appendChild(u)}const l=P(e.tagBadges,o.showAll,e.matchedUserTag);n.appendChild(l),s.appendChild(n);const h=document.createElement("h3");if(h.className="history-title",h.textContent=e.title,s.appendChild(h),e.seriesName){const u=document.createElement("p");u.className="history-media-name";const g=ae(e);g.hasChildNodes()&&(u.appendChild(g),u.appendChild(document.createTextNode(" ")));const i=document.createElement("span");i.textContent="Series: "+e.seriesName,u.appendChild(i),s.appendChild(u);const p=pe(e.episodes);p&&s.appendChild(p)}if(e.movieName){const u=document.createElement("p");u.className="history-media-name";const g=ae(e);g.hasChildNodes()&&(u.appendChild(g),u.appendChild(document.createTextNode(" ")));const i=document.createElement("span");i.textContent="Movie: "+e.movieName,u.appendChild(i),s.appendChild(u)}const m=document.createElement("div");if(m.className="history-details",e.completedAt&&m.appendChild(re("Completed",Ze(e.completedAt))),e.quality&&m.appendChild(re("Quality",e.quality)),e.outcome==="failed"&&e.failureMessage){const u=document.createElement("div");u.className="history-failure-message",u.textContent=e.failureMessage,m.appendChild(u)}return s.appendChild(m),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 r=new CustomEvent("downloadClientsUpdated");document.dispatchEvent(r)}if(a.ombiRequests){o.ombiRequests=a.ombiRequests;const r=new CustomEvent("ombiRequestsUpdated");document.dispatchEvent(r)}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 r=new CustomEvent("historyReload");document.dispatchEvent(r)}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 x()).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=F(o.sonarrWebhook.stats.lastWebhookTimestamp)):a.classList.add("hidden");const r=document.getElementById("radarr-status"),l=document.getElementById("enable-radarr-webhook"),h=document.getElementById("test-radarr-webhook"),m=document.getElementById("radarr-triggers"),u=document.getElementById("radarr-stats");r.textContent=o.radarrWebhook.enabled?"● Enabled":"○ Disabled",r.className="status-indicator "+(o.radarrWebhook.enabled?"enabled":"disabled"),o.radarrWebhook.enabled?(l.classList.add("hidden"),h.classList.remove("hidden"),m.classList.remove("hidden")):(l.classList.remove("hidden"),h.classList.add("hidden"),m.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?(u.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=F(o.radarrWebhook.stats.lastWebhookTimestamp)):u.classList.add("hidden");const g=document.getElementById("ombi-status"),i=document.getElementById("enable-ombi-webhook"),p=document.getElementById("test-ombi-webhook"),c=document.getElementById("ombi-triggers"),d=document.getElementById("ombi-stats");g.textContent=o.ombiWebhook.enabled?"● Enabled":"○ Disabled",g.className="status-indicator "+(o.ombiWebhook.enabled?"enabled":"disabled"),o.ombiWebhook.enabled?(i.classList.add("hidden"),p.classList.remove("hidden"),c.classList.remove("hidden")):(i.classList.remove("hidden"),p.classList.add("hidden"),c.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?(d.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=F(o.ombiWebhook.stats.lastWebhookTimestamp)):d.classList.add("hidden")}async function yt(){k(!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{k(!1)}}async function vt(){k(!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{k(!1)}}async function Et(){k(!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{k(!1)}}async function kt(){k(!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{k(!1)}}async function St(){k(!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{k(!1)}}async function wt(){k(!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{k(!1)}}function k(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,w,E,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),r=s.uptimeSeconds%60,l=`${n}h ${a}m ${r}s`,h=(e.cache.totalSizeBytes/1024).toFixed(1);let m=`
|
|
<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 u=e.polling.intervalMs,i=(e.clients||[]).filter(f=>f.type==="sse");e.polling.enabled?m+=`<div class="status-row"><span>Background poll</span><span>${u/1e3}s</span></div>`:m+='<div class="status-row"><span>Background poll</span><span>Disabled</span></div>';const p=i.length>0?'<span class="status-fg-badge">SSE push</span>':e.polling.enabled?"Background":"On-demand (idle)";m+=`<div class="status-row"><span>Delivery mode</span><span>${p}</span></div>`,m+=`<div class="status-row"><span>SSE clients</span><span>${i.length}</span></div>`;for(const f of i){const B=Math.round((Date.now()-f.connectedAt)/1e3);m+=`<div class="status-row status-row-sub"><span>${R(f.user)}</span><span>connected ${B}s ago</span></div>`}if(m+="</div>",o.isAdmin&&e.webhooks){const f=e.webhooks,B=(v=f.sonarr)!=null&&v.enabled?"●":"○",S=(w=f.radarr)!=null&&w.enabled?"●":"○",L=(E=f.ombi)!=null&&E.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;m+=`
|
|
<div class="status-card">
|
|
<div class="status-card-title">Webhooks</div>
|
|
<div class="status-row"><span>Sonarr</span><span>${B} ${(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>${L} ${(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 c=e.polling.lastPoll;if(c){const f=Math.round((Date.now()-new Date(c.timestamp).getTime())/1e3);m+=`
|
|
<div class="status-card status-card-wide">
|
|
<div class="status-card-title">Last Poll (${c.totalMs}ms total, ${f}s ago)</div>
|
|
<div class="status-timings">`;const B=c.tasks.reduce((S,L)=>Math.max(S,L.ms),1);for(const S of c.tasks){const L=Math.max(2,S.ms/B*100);m+=`
|
|
<div class="timing-row">
|
|
<span class="timing-label">${R(S.label)}</span>
|
|
<div class="timing-bar-bg"><div class="timing-bar" data-w="${L.toFixed(1)}"></div></div>
|
|
<span class="timing-value">${S.ms}ms</span>
|
|
</div>`}m+="</div></div>"}m+=`
|
|
<div class="status-card status-card-wide">
|
|
<div class="status-card-title">Cache (${e.cache.entryCount} entries, ${h} 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 B=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",L=f.itemCount!==null?f.itemCount:"—";m+=`<tr><td><code>${R(f.key)}</code></td><td>${L}</td><td>${B}</td><td>${S}</td></tr>`}m+="</tbody></table></div></div>";const d=document.getElementById("status-content"),y=document.getElementById("status-panel");console.log("[Status] contentDiv found:",!!d,"panel children:",(se=y==null?void 0:y.children)==null?void 0:se.length,"HTML length:",m.length),y&&console.log("[Status] panel innerHTML preview:",y.innerHTML.substring(0,200)),d?(d.innerHTML=m,console.log("[Status] HTML rendered, contentDiv innerHTML length:",d.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,$e-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 r=Date.now();_(),await D(r)}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 $t(){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",()=>Ft(s));const r=document.createElement("span");r.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=()=>{r.textContent=t.type.charAt(0).toUpperCase(),r.classList.add("fallback")},r.appendChild(l);const h=document.createElement("label");h.className="download-client-option-label",h.htmlFor=`client-${s}`,h.textContent=t.name||`${t.type} (${t.id})`;const m=document.createElement("span");m.className="download-client-type",m.textContent=t.type,n.appendChild(a),n.appendChild(r),n.appendChild(h),n.appendChild(m),e.appendChild(n)}),Be())}function Ft(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){if(!e)return"unknown";if(e.available)return"available";if(e.denied)return"denied";if(e.approved)return"approved";if(e.requested)return"pending";if(Array.isArray(e.childRequests)&&e.childRequests.length>0){for(const t of e.childRequests)if(t&&t.available)return"available";for(const t of e.childRequests)if(t&&t.denied)return"denied";for(const t of e.childRequests)if(t&&t.approved)return"approved";for(const t of e.childRequests)if(t&&t.requested)return"pending"}return"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 r=n.requestedDate?new Date(n.requestedDate).getTime():0,l=a.requestedDate?new Date(a.requestedDate).getTime():0;return r-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 r=n.requestedDate?new Date(n.requestedDate).getTime():0;return(a.requestedDate?new Date(a.requestedDate).getTime():0)-r})}}function Ot(e,{types:t,statuses:s,sort:n,search:a}={}){let r=[...e];return r=Mt(r,t),r=Ut(r,s),r=Wt(r,a),r=Ht(r,n),r}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 I(){const e=document.getElementById("requests-list"),t=document.getElementById("no-requests");if(!e)return;const s=o.ombiRequests||{movie:[],tv:[]},n=[...s.movie.map(r=>({...r,mediaType:"movie"})),...s.tv.map(r=>({...r,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 r=t.querySelector("p");if(r){const l=n.length>0;r.textContent=l?"No requests match your filters.":"No requests found."}}return}t&&(t.style.display="none"),a.forEach(r=>{const l=Pt(r);e.appendChild(l)})}function Pt(e){if(!e){const c=document.createElement("div");return c.className="request-card",c.textContent="Invalid request data",c}const t=document.createElement("div");t.className=`request-card ${e.mediaType||""}`;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 r=document.createElement("div");r.className="request-meta";const l=jt(e);if(r.appendChild(l),e.year){const c=document.createElement("span");c.className="request-year",c.textContent=e.year,r.appendChild(c)}const h=O(e),m=document.createElement("span");m.className="request-user",h?m.textContent=`Requested by: ${h}`:(m.textContent="Requested by: Unknown (Ombi)",m.title="No user information received from Ombi",m.style.cursor="help",m.style.textDecoration="underline dotted"),r.appendChild(m);const u=e.childRequests&&e.childRequests[0]?e.childRequests[0].requestedDate||e.childRequests[0].RequestedDate:null,g=e.requestedDate||e.RequestedDate||e.date||e.Date||u;if(g){const c=document.createElement("span");c.className="request-date";try{const d=new Date(g);if(isNaN(d.getTime()))c.textContent=`Date: ${g}`;else{const y=d.getFullYear(),b=String(d.getMonth()+1).padStart(2,"0"),v=String(d.getDate()).padStart(2,"0"),w=String(d.getHours()).padStart(2,"0"),E=String(d.getMinutes()).padStart(2,"0");c.textContent=`Date: ${y}-${b}-${v} ${w}:${E}`}}catch{c.textContent=`Date: ${g}`}r.appendChild(c)}if(e.quality){const c=document.createElement("span");c.className="request-quality",c.textContent=e.quality,r.appendChild(c)}n.appendChild(a),n.appendChild(r);const i=document.createElement("span");i.className="service-icons-container";const p=e.theTvDbId||e.theTvdbId||e.tvDbId||e.tvdbId||e.TvDbId||e.TheTvDbId||e.theMovieDbId||e.theTmdbId||e.imdbId||e.ImdbId;if(o.ombiBaseUrl&&p){const c=document.createElement("a");c.className="ombi-link",c.href=`${o.ombiBaseUrl}/details/${e.mediaType||"movie"}/${p}`,c.target="_blank",c.title="View in Ombi";const d=document.createElement("img");d.className="service-icon ombi",d.src="/images/ombi.svg",d.alt="Ombi",c.appendChild(d),i.appendChild(c)}if(o.isAdmin&&e.arrLink){const c=document.createElement("a");c.className=`${e.arrType}-link`,c.href=e.arrLink,c.target="_blank",c.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",c.appendChild(d),i.appendChild(c)}return t.appendChild(s),t.appendChild(n),t.appendChild(i),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",r=>{r.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(r=>{r.addEventListener("change",()=>{const l=r.closest(".request-filter-option").dataset.value;Gt(l,r.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(),I()}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(),I()}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",r=>{r.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(r=>{r.addEventListener("change",()=>{const l=r.closest(".request-filter-option").dataset.value;Jt(l,r.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(),I()}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(),I()}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),I()}))}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),I()},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",()=>{I()})}(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();q(n==="requests"?"requests":n==="history"?"history":"downloads"),e.addEventListener("click",()=>q("downloads")),t&&t.addEventListener("click",()=>q("requests")),s.addEventListener("click",()=>q("history"))}function q(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"),r=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"),r&&r.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"),r&&r.classList.remove("hidden"),M("requests"),I()):e==="history"&&(n&&n.classList.add("active"),l&&l.classList.remove("hidden"),M("history"),N())}function ts(){q("downloads")}const C=[],ss=20,ns=2e3,os=console.log,as=console.warn,$=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"&&$.apply(console,t),!A&&(C.push({timestamp:new Date().toISOString(),level:e,message:s}),C.length>=ss&&Te())}async function Te(){if(C.length===0||A)return;A=!0;const e=[...C];C.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||$.call(console,"[clientLogCapture] Ingestion server returned error status:",t.status)}catch(t){$.call(console,"[clientLogCapture] Ingestion post request failed:",t.message)}finally{A=!1}}function ls(){if(C.length===0)return;const e=[...C];C.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){$.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",r=>pt(r.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(),$t(),Vt(),dt(),ft(),je().then(r=>{const l=document.getElementById("app-version");l&&r&&(l.textContent="v"+r)}),qt()});
|