// Media volume starts at 50% (then remembers the viewer's own choice). (function(){ const KEY='kronic-media-volume', DEFAULT=0.5; const read=()=>{try{const v=parseFloat(localStorage.getItem(KEY));return Number.isFinite(v)?Math.min(1,Math.max(0,v)):DEFAULT;}catch(_){return DEFAULT;}}; const init=e=>{const el=e.target; if(!(el instanceof HTMLMediaElement)||el.dataset.kronicVolume)return; el.dataset.kronicVolume='1'; el.volume=read();}; document.addEventListener('loadstart',init,true); document.addEventListener('play',init,true); document.addEventListener('volumechange',e=>{const el=e.target; if(!(el instanceof HTMLMediaElement)||!el.dataset.kronicVolume)return; try{localStorage.setItem(KEY,String(el.volume));}catch(_){}},true); })(); let currentSourceId = null; let currentSourceName = null; let currentSourceType = null; let currentShowName = null; let currentSeasonName = null; let scanPollTimer = null; let metadataSources = []; let youtubePollTimer = null; let cacheJobPollTimer = null; let musicImportJobPollTimer = null; const musicImportCompletedSeen = new Set(); let musicImportJobsInitialized = false; let twitchPollTimer = null; let twitchPlayerOverlay = null; let twitchVideoElement = null; let twitchActiveChannel = null; let twitchPlayerDragBound = false; let mediaAuthContext = null; const librarySortStates = new Map(); function getSortState(key) { if (!librarySortStates.has(key)) { librarySortStates.set(key, {mode:"alpha", direction:"asc"}); } return librarySortStates.get(key); } function dateAddedValue(item) { const parsed = Date.parse(item?.added_at || ""); return Number.isFinite(parsed) ? parsed : 0; } function durationValue(item) { return Math.max(0, Number(item?.duration_seconds) || 0); } function compareText(a,b) { return String(a||"").localeCompare( String(b||""), undefined, {numeric:true,sensitivity:"base"} ); } function sortedMediaItems(items,key,titleGetter) { const state=getSortState(key); const direction=state.direction==="desc"?-1:1; return [...items].sort((a,b)=>{ let result=0; if(state.mode==="date") result=dateAddedValue(a)-dateAddedValue(b); else if(state.mode==="length") result=durationValue(a)-durationValue(b); else result=compareText(titleGetter(a),titleGetter(b)); if(result===0) result=compareText(titleGetter(a),titleGetter(b)); return result*direction; }); } function sortedGroups(entries,key) { const state=getSortState(key); const direction=state.direction==="desc"?-1:1; return [...entries].sort((a,b)=>{ const [aName,aItems]=a; const [bName,bItems]=b; let result=0; if(state.mode==="date"){ result=Math.max(0,...aItems.map(dateAddedValue))-Math.max(0,...bItems.map(dateAddedValue)); }else if(state.mode==="length"){ result=aItems.reduce((sum,item)=>sum+durationValue(item),0)-bItems.reduce((sum,item)=>sum+durationValue(item),0); }else result=compareText(aName,bName); if(result===0) result=compareText(aName,bName); return result*direction; }); } function formatDurationShort(seconds) { seconds=Math.max(0,Math.round(Number(seconds)||0)); if(!seconds)return"Unknown"; const hours=Math.floor(seconds/3600); const minutes=Math.floor((seconds%3600)/60); return hours>0?`${hours}h ${minutes}m`:`${minutes}m`; } function librarySortControls(key,rerender) { const state=getSortState(key); const wrapper=document.createElement("span"); wrapper.className="library-sort-controls"; wrapper.innerHTML=` `; const mode=wrapper.querySelector(".library-sort-mode"); const direction=wrapper.querySelector(".library-sort-direction"); mode.value=state.mode; direction.value=state.direction; mode.addEventListener("change",()=>{state.mode=mode.value;rerender();}); direction.addEventListener("change",()=>{state.direction=direction.value;rerender();}); return wrapper; } function canManageMedia() { return !!mediaAuthContext?.canManageMedia; } function isPlatformAdmin() { return !!mediaAuthContext?.isPlatformAdmin; } const content = document.getElementById("content"); const toolbar = document.getElementById("toolbar"); const breadcrumb = document.getElementById("breadcrumb"); const searchForm = document.getElementById("searchForm"); const searchInput = document.getElementById("searchInput"); const playerOverlay = document.getElementById("playerOverlay"); const playerWindow = document.getElementById("playerWindow"); const playerTitle = document.getElementById("playerTitle"); const playerCloseButton = document.getElementById("playerCloseButton"); const playerFullscreenButton = document.getElementById("playerFullscreenButton"); let mediaPlayer = null; let activeMediaId = null; let activeMediaTitle = null; let playbackBaseOffset = 0; let playbackSeekMode = "client"; let playbackKnownDuration = null; let playbackSaveTimer = null; let pendingClientSeek = null; let activePlaybackPlan = null; let activePlaybackQuality = "original"; let activePlaybackAudio = null; let playbackFallbackUsed = false; let playerHealthTimer = null; let lastObservedPlayerTime = 0; let lastPlayerAdvanceAt = 0; let playerStatusElement = null; let activeIptvChannel = null; let iptvOverviewCache = null; let playerMinimized = false; let playerRestoreGeometry = null; let playerPreFullscreenGeometry = null; let playerMinimizeButton = null; let playerResizeHandles = []; // Native media and image requests cannot attach fetch headers. function roomMediaUrl(value) { if (!value || !document.body.dataset.roomId) return value; let url; try { url = new URL(value, location.origin); } catch (_) { return value; } if (url.origin !== location.origin || !/^\/(api\/|thumbnail\/|play\/|stream\/|external\/)/.test(url.pathname)) return value; url.searchParams.set("kronic_room", document.body.dataset.roomId); return url.pathname + url.search + url.hash; } async function api(url, options = {}) { options.credentials = "same-origin"; if (document.body.dataset.roomId && String(url).startsWith("/api/")) { options.headers = new Headers(options.headers || {}); options.headers.set("X-Kronic-Room", document.body.dataset.roomId || ""); } const response = await fetch(url, options); let data = null; try { data = await response.json(); } catch { data = null; } if (response.status === 401) { window.location.replace("/login"); throw new Error("Login required"); } if (!response.ok) throw new Error(data?.detail || data?.error || `HTTP ${response.status}`); return data; } function escapeHtml(value) { if (value === null || value === undefined) return ""; return String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'"); } const escapeAttribute = escapeHtml; function clearScanPolling() { if (scanPollTimer) { clearInterval(scanPollTimer); scanPollTimer = null; } } function resetLibraryContext() { currentSourceId = currentSourceName = currentSourceType = currentShowName = currentSeasonName = null; updateSearchPlaceholder(); } function showError(error) { content.innerHTML = `
Error

${escapeHtml(error?.message || error)}
`; } function nullableNumber(value) { const t = String(value ?? "").trim(); if (!t) return null; const n = Number(t); return Number.isFinite(n) ? n : null; } function mediaPathParts(item) { return String(item.relative_path || "").split(/[\\/]+/).filter(Boolean); } function updateSearchPlaceholder() { searchInput.placeholder = currentSourceId === null ? "Search all media..." : `Search ${currentSourceName}...`; } function ensureInterfaceRefreshStyles() { if (document.getElementById("interfaceRefreshStyles")) return; const link = document.createElement("link"); link.id = "interfaceRefreshStyles"; link.rel = "stylesheet"; link.href = "/CSS/interface_refresh.css?v=20261103-2"; document.head.appendChild(link); } function closeTopNavMenus() { document.querySelectorAll("#mediaPrimaryNav details[open]").forEach(menu => { menu.removeAttribute("open"); }); } function navAction(label, action, options={}) { const button = document.createElement("button"); button.type = "button"; button.className = `top-nav-action${options.primary ? " primary" : ""}`; button.textContent = label; button.addEventListener("click", async event => { event.preventDefault(); closeTopNavMenus(); await action(); }); return button; } function navDropdown(label, items, active=false) { const details = document.createElement("details"); details.className = `top-nav-dropdown${active ? " active" : ""}`; const summary = document.createElement("summary"); summary.textContent = label; details.appendChild(summary); // Keep only one main navigation dropdown open at a time. details.addEventListener("toggle", () => { if (!details.open) return; document.querySelectorAll("#mediaPrimaryNav details[open]").forEach(other => { if (other !== details) other.open = false; }); }); const menu = document.createElement("div"); menu.className = "top-nav-menu"; for (const item of items) { if (!item || item.hidden) continue; const button = document.createElement("button"); button.type = "button"; button.textContent = item.label; if (item.muted) button.classList.add("muted-action"); button.addEventListener("click", async event => { event.preventDefault(); details.removeAttribute("open"); await item.action(); }); menu.appendChild(button); } details.appendChild(menu); return details; } function getTopNavHost() { const existing = document.getElementById("mediaPrimaryNav"); if (existing?.parentElement) return existing.parentElement; const anchor = document.getElementById("librariesButton") || document.getElementById("manageButton") || document.getElementById("addLibraryButton") || document.getElementById("searchForm"); return anchor?.parentElement || document.querySelector("header"); } function cleanLegacyTopNav() { ["librariesButton","manageButton","metadataButton","addLibraryButton","mediaAccountNav","mediaPrimaryNav"] .forEach(id => document.getElementById(id)?.remove()); } // Browser-local preference; the server selects the frontend on the next request. function getInterfacePreference() { const entry = document.cookie.split(';').map(v => v.trim()).find(v => v.startsWith('kronic_interface=')); const mode = entry ? entry.slice('kronic_interface='.length) : 'auto'; return ['auto', 'desktop', 'mobile'].includes(mode) ? mode : 'auto'; } function setInterfacePreference(mode) { if (!['auto', 'desktop', 'mobile'].includes(mode)) return false; if (!window.confirm('Switch interface? This reloads Kronic and may disconnect your voice room or interrupt playback.')) return false; document.cookie = 'kronic_interface=' + mode + '; Path=/; Max-Age=31536000; SameSite=Lax' + (location.protocol === 'https:' ? '; Secure' : ''); if (getInterfacePreference() !== mode) { alert('Could not save the interface preference. Check browser cookie settings.'); return false; } window.location.assign('/' + location.search); return true; } function buildAccountNav() { const wrap = document.createElement("span"); wrap.id = "mediaAccountNav"; wrap.className = "media-account-nav"; const name = document.createElement("span"); name.className = "media-account-name"; name.textContent = mediaAuthContext?.user?.username || "Account"; wrap.appendChild(name); const identity = String(mediaAuthContext?.user?.username || 'guest').toLowerCase(); const homeKey = 'kronic.start-view.v1.' + identity; const groupRoles = (mediaAuthContext?.groups || []).map(group => String(group.role || '').toLowerCase()); const canModerate = groupRoles.some(role => ['owner', 'admin', 'moderator'].includes(role)); wrap.appendChild(navDropdown("Account", [ {label: "Switch room", action: switchAssignedRoom}, {label: "Rename room title", action: renameSelectedRoom, hidden: !isPlatformAdmin() && document.body.dataset.roomOwner !== 'true'}, {label: "Start in Room", action: () => { localStorage.setItem(homeKey, 'room'); window.location.reload(); }}, {label: "Start in Media Library", hidden: !mediaAuthContext?.hasMediaAccess, action: () => { localStorage.setItem(homeKey, 'libraries'); window.location.reload(); }}, ...[['auto', 'Automatic'], ['desktop', 'Desktop'], ['mobile', 'Mobile']].map(([mode, label]) => ({ label: (getInterfacePreference() === mode ? '✓ ' : '') + 'Interface: ' + label, action: () => setInterfacePreference(mode) })), {label: "Admin", hidden: !isPlatformAdmin(), action: () => {window.location.href="/admin";}}, {label: "Logout", action: async () => { try {await fetch("/api/auth/logout",{method:"POST",credentials:"same-origin"});} catch {} window.location.replace("/login"); }} ])); return wrap; } function installTopNav(mode="home", options={}) { const host = getTopNavHost(); if (!host) return; cleanLegacyTopNav(); const nav = document.createElement("nav"); nav.id = "mediaPrimaryNav"; nav.className = `media-primary-nav media-primary-nav-${mode}`; if (!mediaAuthContext?.hasMediaAccess) { /* Communication-only account: keep Account navigation. */ } else if (mode === "library") { // Compact library actions live in one menu, rather than spanning the header. const title = document.createElement("span"); title.className = "top-nav-context-title"; title.textContent = currentSourceName || "Library"; nav.appendChild(title); if (canManageMedia()) { nav.appendChild(navDropdown("Library actions", [ {label:"Scan library",action:()=>scanOneLibrary(currentSourceId)}, {label:"Edit metadata",action:()=>showMetadataEditor(currentSourceId)}, {label:"Manage library",action:()=>showManageLibraries(currentSourceId)}, {label:"Back to libraries",action:options.backHandler || showLibraries} ])); } if (options.sortKey && options.rerender) { const sortWrap = document.createElement("span"); sortWrap.className = "top-nav-sort"; sortWrap.appendChild(librarySortControls(options.sortKey, options.rerender)); nav.appendChild(sortWrap); } } else { nav.appendChild(navDropdown("Libraries", [ {label:"Local", action:showLibraries}, {label:"Manage", action:showManageLibraries, hidden:!canManageMedia()}, {label:"Add Library", action:()=>showFolderBrowser("/"), hidden:!canManageMedia()}, {label:"Scan", action:showScanDialog, hidden:!canManageMedia()}, ], mode === "home")); nav.appendChild(navDropdown("Metadata", [ {label:"Edit Metadata", action:()=>showMetadataEditor()}, {label:"Add / Override Metadata", action:()=>showMetadataEditor()}, {label:"New / Re-analyze Metadata", action:()=>showMetadataEditor()}, ], mode === "metadata")); nav.appendChild(navDropdown("Live", [ {label:"Tube", action:showTubeSettings}, {label:"Twitch", action:showTwitchSettings}, {label:"IPTV", action:showIptvSettings}, ], mode === "tube" || mode === "twitch" || mode === "iptv")); } // Only expose administrative entry points when the authenticated role allows them. if (isPlatformAdmin()) { nav.appendChild(navAction('⚙ Admin', () => { window.location.href = '/admin'; })); } nav.appendChild(buildAccountNav()); // Preserve the native per-view back handler without a redundant topbar button. ensureKronicBackButton(options); document.getElementById("kronicSiteBack").hidden = true; ensureKronicSearchToggle(); const search = document.getElementById("searchForm"); if (search && search.parentElement === host) host.insertBefore(nav, search); else host.appendChild(nav); } // Keep search/back together in a dedicated header utility area instead of floating over menus. function ensureKronicHeaderTools() { const host = document.querySelector("header .topbar-left") || document.querySelector("header"); if (!host) return null; let tools = document.getElementById("kronicHeaderTools"); if (!tools) { tools = document.createElement("div"); tools.id = "kronicHeaderTools"; tools.className = "kronic-header-tools"; } const title = host.querySelector(".site-title"); if (title && title.parentElement === host) title.insertAdjacentElement("afterend", tools); else if (tools.parentElement !== host) host.prepend(tools); return tools; } // Compact, shared search for desktop and mobile. Keep the original form/API intact. function ensureKronicSearchToggle() { const form = document.getElementById("searchForm"); if (!form) return; form.classList.add("kronic-search-popover"); let toggle = document.getElementById("kronicSiteSearch"); if (!toggle) { toggle = document.createElement("button"); toggle.id = "kronicSiteSearch"; toggle.type = "button"; toggle.textContent = "⌕"; toggle.title = "Search media"; toggle.setAttribute("aria-label", "Open search"); toggle.setAttribute("aria-expanded", "false"); (ensureKronicHeaderTools() || document.body).appendChild(toggle); } ensureKronicHeaderTools()?.appendChild(toggle); const submit = form.querySelector('button[type="submit"],button:not([type])'); if (submit) { submit.textContent = "➜"; submit.title = "Submit search"; submit.setAttribute("aria-label", "Submit search"); } function closeSearch() { form.classList.remove("kronic-search-open"); toggle.setAttribute("aria-expanded", "false"); } toggle.onclick = () => { const open = form.classList.toggle("kronic-search-open"); toggle.setAttribute("aria-expanded", String(open)); if (open) { closeTopNavMenus(); searchInput.focus(); } }; if (!form.dataset.kronicSearchBound) { form.dataset.kronicSearchBound = "1"; form.addEventListener("submit", closeSearch); document.addEventListener("keydown", event => { if (event.key === "Escape") closeSearch(); }); document.addEventListener("pointerdown", event => { if (!form.contains(event.target) && !document.getElementById("kronicSiteSearch")?.contains(event.target)) closeSearch(); }); } } // Back control is independent of rebuilt navigation elements. // The app is a single-page renderer, so prefer the library-provided back handler. function ensureKronicBackButton(options={}) { let button=document.getElementById("kronicSiteBack"); if(!button){ button=document.createElement("button"); button.id="kronicSiteBack"; button.type="button"; button.textContent="←"; button.title="Back"; button.setAttribute("aria-label","Go back"); (ensureKronicHeaderTools() || document.body).appendChild(button); } ensureKronicHeaderTools()?.appendChild(button); button.onclick=async()=>{ if(document.getElementById("youtubePlayerOverlay")?.classList.contains("active")) { await closeYouTubePlayer();return; } if(document.getElementById("playerOverlay")?.classList.contains("active")) { await closePlayer();return; } const handler=options.backHandler || showLibraries; await handler(); }; } function installMobileVideoBack(win, close) { if(!win || win.querySelector(".kronic-video-back"))return; const header=win.querySelector(".player-header,.youtube-player-header"); if(!header)return; const btn=document.createElement("button"); btn.type="button"; btn.className="kronic-video-back"; btn.textContent="←"; btn.setAttribute("aria-label","Back to library"); btn.title="Back to library"; btn.onclick=(event)=>{event.stopPropagation();close();}; header.appendChild(btn); } function setupNavigation() { document.getElementById("homeButton")?.addEventListener("click", event => { event.preventDefault(); if (mediaAuthContext?.hasMediaAccess) showLibraries(); }); installTopNav("home"); } async function showTubeSettings() { await showYouTubeLibrary(); installTopNav("tube"); } async function showTwitchSettings() { await showTwitchLibrary(); installTopNav("twitch"); } async function showIptvSettings() { await showIptvLibrary("settings"); } function detectPlaybackBrowser() { const ua = navigator.userAgent || ""; if (/Firefox\//i.test(ua)) return "firefox"; if (/Edg\//i.test(ua)) return "edge"; if (/Chrome\//i.test(ua) || /Chromium\//i.test(ua)) return "chrome"; if (/Safari\//i.test(ua) && !/Chrome|Chromium|Edg/i.test(ua)) return "safari"; return "unknown"; } function canPlayMime(mime) { const probe = document.createElement("video"); const result = probe.canPlayType(mime); return result === "probably" || result === "maybe"; } function getPlaybackCapabilities() { return { browser: detectPlaybackBrowser(), h264: canPlayMime('video/mp4; codecs="avc1.640028, mp4a.40.2"'), av1: canPlayMime('video/mp4; codecs="av01.0.08M.08, mp4a.40.2"'), hevc: canPlayMime('video/mp4; codecs="hvc1.1.6.L120.B0, mp4a.40.2"'), webm_vp9: canPlayMime('video/webm; codecs="vp9,opus"'), webm_av1: canPlayMime('video/webm; codecs="av01.0.08M.08,opus"'), }; } function playbackCapabilityQuery(forceCompat=false, quality=activePlaybackQuality, audio=activePlaybackAudio) { const caps = getPlaybackCapabilities(); return new URLSearchParams({ browser: caps.browser, h264: caps.h264 ? "1" : "0", av1: caps.av1 ? "1" : "0", hevc: caps.hevc ? "1" : "0", webm_vp9: caps.webm_vp9 ? "1" : "0", webm_av1: caps.webm_av1 ? "1" : "0", force_compat: forceCompat ? "1" : "0", quality: quality || "original", audio: audio === null || audio === undefined ? "" : String(audio), }); } async function getPlaybackPlan(mediaId, forceCompat=false) { const params = playbackCapabilityQuery(forceCompat); return await api(`/api/media/${mediaId}/playback-plan?${params.toString()}`); } function ensurePlayerStatusElement() { if (playerStatusElement?.isConnected) return playerStatusElement; if (!playerWindow) return null; playerStatusElement = document.createElement("div"); playerStatusElement.id = "playerPlaybackStatus"; playerStatusElement.className = "player-playback-status"; playerStatusElement.hidden = true; const video = document.getElementById("mediaPlayerFrame"); if (video?.parentElement) video.parentElement.insertBefore(playerStatusElement, video); else playerWindow.appendChild(playerStatusElement); return playerStatusElement; } function showPlayerStatus(message, kind="info") { const status = ensurePlayerStatusElement(); if (!status) return; status.textContent = message || ""; status.dataset.kind = kind; status.hidden = !message; } function hidePlayerStatus() { if (!playerStatusElement) return; playerStatusElement.hidden = true; playerStatusElement.textContent = ""; playerStatusElement.dataset.kind = ""; } function playbackModeDescription(plan) { if (!plan) return "Preparing playback…"; if (plan.mode === "direct") return "Direct browser playback"; if (plan.mode === "remux_stream") return "Browser compatibility remux: video copy + AAC audio"; if (plan.mode === "remux_cache") return plan.cache?.cached ? "Using cached browser-compatible MP4" : "Preparing browser-compatible playback…"; if (plan.mode === "transcode_stream") return "Live compatibility transcode: H.264 + AAC"; return "Preparing playback…"; } function resetPlayerHealth() { if (playerHealthTimer) clearTimeout(playerHealthTimer); playerHealthTimer = null; lastObservedPlayerTime = Number(mediaPlayer?.currentTime) || 0; lastPlayerAdvanceAt = performance.now(); } function observePlayerProgress() { const current = Number(mediaPlayer?.currentTime) || 0; if (current > lastObservedPlayerTime + 0.15) { lastObservedPlayerTime = current; lastPlayerAdvanceAt = performance.now(); hidePlayerStatus(); } } function schedulePlaybackHealthCheck(reason) { if (!mediaPlayer || (!activeMediaId && !activeIptvChannel)) return; if (playerHealthTimer) clearTimeout(playerHealthTimer); const snapshot = Number(mediaPlayer.currentTime) || 0; const mediaError = mediaPlayer.error; const errorDetail = mediaError ? ` (code ${mediaError.code}${mediaError.message ? `: ${mediaError.message}` : ""})` : ""; showPlayerStatus( reason === "error" ? `Browser reported a media error${errorDetail}; checking whether playback actually stopped…` : "Buffering…" ); playerHealthTimer = setTimeout(async () => { playerHealthTimer = null; if (!mediaPlayer || (!activeMediaId && !activeIptvChannel)) return; const current = Number(mediaPlayer.currentTime) || 0; const advanced = current > snapshot + 0.25; if (advanced || (!mediaPlayer.paused && performance.now() - lastPlayerAdvanceAt < 5000)) { hidePlayerStatus(); return; } if (!playbackFallbackUsed) { playbackFallbackUsed = true; showPlayerStatus("Playback stopped. Retrying compatibility playback…", "warning"); try { if (activeIptvChannel) { await beginIptvPlayback(activeIptvChannel, true); return; } const resumeAt = getAbsolutePlaybackPosition(); activePlaybackPlan = await getPlaybackPlan(activeMediaId, true); playbackSeekMode = activePlaybackPlan.seek_mode || "client"; await beginPlayback(resumeAt, true); return; } catch (error) { console.warn("Compatibility playback retry failed:", error); } } showPlayerStatus( activeIptvChannel ? "Live channel stopped. Try the channel again; the upstream stream may be offline." : "Browser playback stopped. Try External to open this item in VLC or mpv.", "error" ); }, 10000); } function setupVideoPlayer() { const oldFrame = document.getElementById("mediaPlayerFrame"); if (!oldFrame) return; mediaPlayer = document.createElement("video"); mediaPlayer.id = "mediaPlayerFrame"; mediaPlayer.className = oldFrame.className || "media-player-frame"; mediaPlayer.controls = true; mediaPlayer.autoplay = true; mediaPlayer.playsInline = true; mediaPlayer.preload = "metadata"; oldFrame.replaceWith(mediaPlayer); ensurePlayerStatusElement(); mediaPlayer.addEventListener("loadedmetadata", handlePlayerLoadedMetadata); mediaPlayer.addEventListener("play", () => { startPlaybackSaveTimer(); resetPlayerHealth(); }); mediaPlayer.addEventListener("playing", () => { resetPlayerHealth(); hidePlayerStatus(); }); mediaPlayer.addEventListener("timeupdate", observePlayerProgress); mediaPlayer.addEventListener("waiting", () => schedulePlaybackHealthCheck("waiting")); mediaPlayer.addEventListener("stalled", () => schedulePlaybackHealthCheck("stalled")); mediaPlayer.addEventListener("error", () => schedulePlaybackHealthCheck("error")); mediaPlayer.addEventListener("pause", saveCurrentPlaybackProgress); mediaPlayer.addEventListener("ended", handlePlaybackEnded); } async function getSavedPlaybackProgress(mediaId) { try { return await api(`/api/media/${mediaId}/progress`); } catch { return {position_seconds:0, duration_seconds:null, completed:false, seek_mode:"client"}; } } async function openPlayer(mediaId, title, options={}) { if (!mediaPlayer) return; await saveCurrentPlaybackProgress(); stopPlaybackSaveTimer(); resetPlayerHealth(); mediaPlayer.pause(); mediaPlayer.removeAttribute("src"); mediaPlayer.load(); activeMediaId = Number(mediaId); activeMediaTitle = title || "Media Player"; activePlaybackQuality = options.quality || "original"; activePlaybackAudio = options.audio === "" || options.audio === undefined ? null : Number(options.audio); playbackBaseOffset = 0; pendingClientSeek = null; playbackFallbackUsed = false; activePlaybackPlan = null; playerTitle.textContent = activeMediaTitle; installMobileVideoBack(playerWindow,()=>closePlayer()); playerOverlay.classList.add("active"); playerOverlay.setAttribute("aria-hidden", "false"); document.body.classList.add("player-open"); playerWindow?.classList.remove("player-minimized"); playerMinimized=false; updateMinimizeButton(); prepareFloatingPlayerPosition(); showPlayerStatus("Selecting the best playback mode for this browser…"); const [progress, plan] = await Promise.all([ options.roomSync ? Promise.resolve({position_seconds:0,completed:true,seek_mode:"client"}) : getSavedPlaybackProgress(activeMediaId), getPlaybackPlan(activeMediaId, false), ]); activePlaybackPlan = plan; playbackSeekMode = plan.seek_mode || progress.seek_mode || "client"; playbackKnownDuration = Number(progress.duration_seconds) || null; showPlayerStatus(playbackModeDescription(plan)); const saved = Number(progress.position_seconds) || 0; const duration = Number(progress.duration_seconds) || 0; let offer = !progress.completed && saved >= 30; if (duration > 0 && (duration - saved <= 300 || saved / duration >= 0.95)) offer = false; let resume = 0; if (offer) { const ok = window.confirm(`Resume "${activeMediaTitle}" from ${formatPlaybackTime(saved)}?\n\nOK = Resume\nCancel = Start Over`); if (ok) resume = saved; else await resetPlaybackProgress(activeMediaId); } if (options.roomSync) resume = Math.max(0, Number(options.startPosition) || 0); await beginPlayback(resume, false); } async function beginPlayback(startSeconds, forceCompat=false) { startSeconds = Math.max(0, Number(startSeconds) || 0); playbackBaseOffset = 0; pendingClientSeek = null; if (forceCompat || !activePlaybackPlan) { activePlaybackPlan = await getPlaybackPlan(activeMediaId, forceCompat); playbackSeekMode = activePlaybackPlan.seek_mode || "client"; } showPlayerStatus(playbackModeDescription(activePlaybackPlan)); const params = playbackCapabilityQuery(forceCompat); if (playbackSeekMode === "server" && startSeconds > 0) { playbackBaseOffset = startSeconds; params.set("start", String(startSeconds)); } else if (startSeconds > 0) { pendingClientSeek = startSeconds; } mediaPlayer.src = roomMediaUrl(`/play/${activeMediaId}?${params.toString()}`); mediaPlayer.load(); mediaPlayer.play().catch(error => console.debug("mediaPlayer.play() did not start immediately:", error)); } function handlePlayerLoadedMetadata() { if ((!playbackKnownDuration || playbackKnownDuration <= 0) && Number.isFinite(mediaPlayer.duration) && mediaPlayer.duration > 0) playbackKnownDuration = mediaPlayer.duration; if (pendingClientSeek !== null && playbackSeekMode === "client") { try { mediaPlayer.currentTime = pendingClientSeek; } catch {} pendingClientSeek = null; } } function getAbsolutePlaybackPosition() { const local = Number(mediaPlayer?.currentTime) || 0; return playbackSeekMode === "server" ? playbackBaseOffset + local : local; } function startPlaybackSaveTimer() { stopPlaybackSaveTimer(); playbackSaveTimer = setInterval(saveCurrentPlaybackProgress, 10000); } function stopPlaybackSaveTimer() { if (playbackSaveTimer) { clearInterval(playbackSaveTimer); playbackSaveTimer = null; } } async function saveCurrentPlaybackProgress() { if (!activeMediaId || !mediaPlayer) return; const position = getAbsolutePlaybackPosition(); if (position < 2) return; let duration = playbackKnownDuration; if ((!duration || duration <= 0) && Number.isFinite(mediaPlayer.duration) && mediaPlayer.duration > 0) duration = mediaPlayer.duration; const completed = !!(duration && duration > 0 && ((duration - position) <= 300 || position / duration >= 0.95)); try { await api(`/api/media/${activeMediaId}/progress`, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({position_seconds:position, duration_seconds:duration, completed})}); } catch {} } async function handlePlaybackEnded() { stopPlaybackSaveTimer(); if (!activeMediaId) return; const duration = playbackKnownDuration || (Number.isFinite(mediaPlayer.duration) ? mediaPlayer.duration : null); try { await api(`/api/media/${activeMediaId}/progress`, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({position_seconds:duration || getAbsolutePlaybackPosition(), duration_seconds:duration, completed:true})}); } catch {} } async function resetPlaybackProgress(mediaId) { try { await api(`/api/media/${mediaId}/progress`, {method:"DELETE"}); } catch {} } async function closePlayer() { stopPlaybackSaveTimer(); await saveCurrentPlaybackProgress(); if (document.fullscreenElement === playerWindow) { try { await document.exitFullscreen(); } catch {} } mediaPlayer?.pause(); mediaPlayer?.removeAttribute("src"); mediaPlayer?.load(); playerOverlay.classList.remove("active"); playerOverlay.setAttribute("aria-hidden", "true"); document.body.classList.remove("player-open"); activeMediaId = activeMediaTitle = null; activeIptvChannel = null; playbackBaseOffset = 0; playbackKnownDuration = null; pendingClientSeek = null; activePlaybackPlan = null; playbackFallbackUsed = false; playerMinimized = false; playerRestoreGeometry = null; playerPreFullscreenGeometry = null; playerWindow?.classList.remove("player-minimized"); updateMinimizeButton(); resetPlayerHealth(); hidePlayerStatus(); // Only a real Close/Stop destroys the media element. setupVideoPlayer(); } function capturePlayerGeometry() { if (!playerWindow || window.innerWidth <= 760) return null; const r = playerWindow.getBoundingClientRect(); return {left:r.left, top:r.top, width:r.width, height:r.height}; } function applyPlayerGeometry(g) { if (!playerWindow || !g || window.innerWidth <= 760) return; const w=Math.max(360,Math.min(window.innerWidth-12,Number(g.width)||720)); const h=Math.max(220,Math.min(window.innerHeight-12,Number(g.height)||440)); playerWindow.style.width=`${w}px`; playerWindow.style.height=`${h}px`; playerWindow.style.left=`${Math.max(0,Math.min(Number(g.left)||0,window.innerWidth-80))}px`; playerWindow.style.top=`${Math.max(0,Math.min(Number(g.top)||0,window.innerHeight-50))}px`; playerWindow.classList.add("floating-player-positioned"); } function updateMinimizeButton() { if (!playerMinimizeButton) return; playerMinimizeButton.textContent=playerMinimized?"Restore":"Minimize"; } function minimizePlayer() { if (!playerWindow || playerMinimized) return; playerRestoreGeometry=capturePlayerGeometry(); playerMinimized=true; playerWindow.classList.add("player-minimized"); updateMinimizeButton(); if (window.innerWidth>760) { const w=Math.min(520,Math.max(320,playerRestoreGeometry?.width||420)); playerWindow.style.width=`${w}px`; playerWindow.style.height=""; playerWindow.style.left=`${Math.max(8,window.innerWidth-w-18)}px`; playerWindow.style.top=`${Math.max(8,window.innerHeight-66)}px`; playerWindow.classList.add("floating-player-positioned"); } } function restorePlayer() { if (!playerWindow || !playerMinimized) return; playerMinimized=false; playerWindow.classList.remove("player-minimized"); updateMinimizeButton(); if (window.innerWidth>760 && playerRestoreGeometry) applyPlayerGeometry(playerRestoreGeometry); } function togglePlayerMinimized(){ playerMinimized?restorePlayer():minimizePlayer(); } async function togglePlayerFullscreen() { if (!playerWindow) return; try { if (document.fullscreenElement===playerWindow) return await document.exitFullscreen(); if (playerMinimized) restorePlayer(); playerPreFullscreenGeometry=capturePlayerGeometry(); await playerWindow.requestFullscreen(); } catch(e){ console.debug("Fullscreen request failed:",e); } } function updateFullscreenButton() { const fs=document.fullscreenElement===playerWindow; if (playerFullscreenButton) playerFullscreenButton.textContent=fs?"Exit Fullscreen":"Fullscreen"; if (!fs && playerPreFullscreenGeometry && !playerMinimized) { applyPlayerGeometry(playerPreFullscreenGeometry); playerPreFullscreenGeometry=null; } } function formatPlaybackTime(seconds) { seconds = Math.max(0, Math.floor(Number(seconds)||0)); const h=Math.floor(seconds/3600), m=Math.floor((seconds%3600)/60), s=seconds%60; return h>0 ? `${h}:${String(m).padStart(2,"0")}:${String(s).padStart(2,"0")}` : `${m}:${String(s).padStart(2,"0")}`; } playerCloseButton?.addEventListener("click", closePlayer); playerFullscreenButton?.addEventListener("click", togglePlayerFullscreen); document.addEventListener("fullscreenchange", updateFullscreenButton); document.addEventListener("keydown", e => { if (e.key !== "Escape") return; if (document.getElementById("metadataInfoOverlay")) return closeMetadataInfo(); if (document.getElementById("scanDialogOverlay")) return closeScanDialog(); }); searchForm.addEventListener("submit", async e => { e.preventDefault(); const q = searchInput.value.trim(); if (!q) return currentSourceId !== null ? showLibrary(currentSourceId,currentSourceName,currentSourceType) : showLibraries(); await performSearch(q); }); function mosaicHtml(urls, fallback="MEDIA") { const safe = (urls || []).filter(Boolean).slice(0, 6); if (!safe.length) { return `
${escapeHtml(fallback)}
`; } return `
${safe.map(url => `
`).join("")}
`; } function homeModuleCard({id, title, badge, subtitle, count, urls, extraClass="", actionName=""}) { return `
${mosaicHtml(urls, badge || title)}

${escapeHtml(title)}

${badge ? `${escapeHtml(badge)}` : ""}
${escapeHtml(subtitle || "")}
${escapeHtml(count || "")}
`; } function bindHomeModule(id, action) { const node = document.getElementById(id); if (!node) return; node.addEventListener("click", action); node.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); action(); } }); } async function showLibraries() { clearScanPolling(); resetLibraryContext(); breadcrumb.innerHTML = ""; toolbar.innerHTML = ""; installTopNav("home"); content.innerHTML = `
Loading your media…
`; try { const sources = await api("/api/sources"); const sampleResults = await Promise.all( sources.map(async source => { try { return await api(`/api/sources/${source.id}/samples?limit=6`); } catch { return []; } }) ); const [youtubeHistory, musicOverview, twitchOverview, iptvOverview] = await Promise.all([ api("/api/youtube/history?limit=6").catch(() => ({items:[]})), api("/api/music/overview?limit=6").catch(() => ({tracks:[]})), api("/api/twitch/overview").catch(() => ({channels:[],recordings:[]})), api("/api/iptv/overview").catch(() => ({channels:[]})), ]); const localCards = sources.map((source, index) => { const samples = sampleResults[index] || []; return homeModuleCard({ id:`library-card-${source.id}`, title:source.name, badge:source.library_type === "shows" ? "TV Shows" : "Movies", subtitle:`${source.paths?.length || 0} folder${(source.paths?.length || 0) === 1 ? "" : "s"}`, count:`${source.media_count || 0} items`, urls:samples.map(item => roomMediaUrl(`/thumbnail/${item.id}`)), extraClass:"local-library-module", actionName:`Open ${source.name}`, }); }).join(""); const tubeItems = youtubeHistory?.items || []; const tubeCard = homeModuleCard({ id:"homeTubeModule", title:"Tube", badge:"Stream", subtitle:"Search, watch and cached history", count:tubeItems.length ? `${tubeItems.length} recent items` : "YouTube streaming", urls:tubeItems.map(item => item.thumbnail_url || item.thumbnail), extraClass:"tube-module", actionName:"Open Tube", }); const musicTracks = musicOverview?.tracks || []; const musicCard = homeModuleCard({ id:"homeMusicModule", title:"Music", badge:"Audio", subtitle:"Spotify catalog + Kronic audio", count:musicTracks.length ? `${musicTracks.length} track${musicTracks.length === 1 ? "" : "s"}` : "Import Spotify music", urls:musicTracks.map(item => item.cover_url).filter(Boolean), extraClass:"music-module", actionName:"Open Music", }); const twitchChannels = twitchOverview?.channels || []; const twitchLive = twitchChannels.filter(channel => Boolean(Number(channel.live || 0))); const twitchCard = homeModuleCard({ id:"homeTwitchModule", title:"Twitch", badge:twitchLive.length ? "LIVE" : "Stream", subtitle:"Saved Twitch channels and DVR", count:twitchChannels.length ? `${twitchChannels.length} channel${twitchChannels.length === 1 ? "" : "s"} · ${twitchLive.length} live` : "Add Twitch channels", urls:[], extraClass:"twitch-module", actionName:"Open Twitch", }); const iptvChannels = iptvOverview?.channels || []; const iptvCard = homeModuleCard({ id:"homeIptvModule", title:"IPTV", badge:"LIVE", subtitle:"Curated live channels and playlists", count:`${iptvChannels.length} channel${iptvChannels.length === 1 ? "" : "s"}`, urls:iptvChannels.map(item => item.tvg_logo).filter(Boolean), extraClass:"iptv-module", actionName:"Open IPTV", }); content.innerHTML = `

Media

Libraries, Tube and live TV in one place.
${localCards}${tubeCard}${musicCard}${twitchCard}${iptvCard}
`; sources.forEach(source => { bindHomeModule(`library-card-${source.id}`, () => showLibrary(source.id, source.name, source.library_type)); }); bindHomeModule("homeTubeModule", showYouTubeLibrary); bindHomeModule("homeMusicModule", showMusicLibrary); bindHomeModule("homeTwitchModule", showTwitchLibrary); bindHomeModule("homeIptvModule", showIptvLibrary); startScanPolling(); } catch (error) { showError(error); } } async function showScanDialog(){ try{ const st=await api("/api/scan/status"); if(st.running) return alert("A library scan is already running."); const sources=(await api("/api/sources")).filter(s=>s.enabled); if(!sources.length) return alert("There are no enabled libraries to scan."); closeScanDialog(); const overlay=document.createElement("div"); overlay.id="scanDialogOverlay"; overlay.className="scan-dialog-overlay"; overlay.innerHTML=`

Scan Libraries

${sources.map(s=>``).join("")}
`; document.body.appendChild(overlay); overlay.onclick=e=>{if(e.target===overlay)closeScanDialog();}; document.getElementById("closeScanDialogButton").onclick=closeScanDialog; document.getElementById("cancelScanButton").onclick=closeScanDialog; document.getElementById("selectAllScanButton").onclick=()=>setAllScanSelections(true); document.getElementById("clearAllScanButton").onclick=()=>setAllScanSelections(false); document.getElementById("startSelectedScanButton").onclick=startSelectedLibraryScan; }catch(e){alert(e.message);} } function closeScanDialog(){document.getElementById("scanDialogOverlay")?.remove();} function setAllScanSelections(v){document.querySelectorAll(".scan-library-checkbox").forEach(c=>c.checked=v);} async function startSelectedLibraryScan(){const ids=[...document.querySelectorAll(".scan-library-checkbox:checked")].map(c=>Number(c.value)); if(!ids.length)return alert("Select at least one library."); const mode=document.getElementById("scanMode")?.value||"quick"; closeScanDialog(); await startLibraryScan(ids,mode);} async function scanOneLibrary(id,mode="quick"){await startLibraryScan([Number(id)],mode);} // Standalone scan monitor: remains visible regardless of the selected media window. let activeScanMonitorTimer = null; let scanMonitorWasRunning = false; function ensureScanMonitor(){ if(document.getElementById("kronicScanMonitor"))return document.getElementById("kronicScanMonitor"); if(!document.getElementById("kronicScanMonitorStyles")){ const style=document.createElement("style");style.id="kronicScanMonitorStyles"; style.textContent=`#kronicScanMonitor{position:fixed;right:16px;bottom:76px;width:min(440px,calc(100vw - 24px));max-height:60vh;overflow:auto;z-index:2147483000;color:#e7edf7;background:#172332;border:1px solid #46627d;border-radius:12px;box-shadow:0 10px 35px #0009;padding:14px;font:14px system-ui,sans-serif}#kronicScanMonitor .scan-monitor-top{display:flex;justify-content:space-between;align-items:center;gap:10px}#kronicScanMonitor button{border:1px solid #536980;color:#e7edf7;background:#273b50;border-radius:6px;padding:5px 9px;cursor:pointer}#kronicScanMonitor .scan-monitor-item{border-top:1px solid #354659;margin-top:10px;padding-top:10px}#kronicScanMonitor .scan-monitor-track{height:9px;background:#303e50;border-radius:12px;overflow:hidden;margin-top:6px}#kronicScanMonitor .scan-monitor-fill{height:100%;background:#5a89ff;transition:width .3s}#kronicScanMonitor .scan-monitor-muted{color:#acbad0;font-size:12px;overflow-wrap:anywhere}#kronicScanMonitor .scan-monitor-warning{color:#ffc375;overflow-wrap:anywhere;margin-top:6px}@media(max-width:760px){#kronicScanMonitor{bottom:86px;right:8px;width:calc(100vw - 16px);max-height:45vh}}`; document.head.appendChild(style); } const panel=document.createElement("aside");panel.id="kronicScanMonitor";panel.setAttribute("role","status");panel.setAttribute("aria-live","polite"); panel.innerHTML='
Library scan
Checking scan status…
'; document.body.appendChild(panel); panel.querySelector("#kronicScanMonitorClose").onclick=()=>{panel.remove();if(activeScanMonitorTimer){clearInterval(activeScanMonitorTimer);activeScanMonitorTimer=null;}}; return panel; } function renderScanMonitor(state){ const panel=document.getElementById("kronicScanMonitor");if(!panel)return; const items=Object.values(state.libraries||{}); const stage=state.running?"Scanning in background…":(state.completed_at?"Scan finished":"Scan starting…"); const lines=items.map(st=>{ const percent=Math.max(0,Math.min(100,Number(st.percent)||0)); const warnings=(st.unavailable_paths||[]).map(path=>`
Unavailable: ${escapeHtml(path)}
`).join(""); const errors=Number(st.errors||0); return `
${escapeHtml(st.name||"Library")} — ${escapeHtml(st.status||"waiting")}
${escapeHtml(st.stage||"")} · ${Number(st.processed||0)}/${Number(st.total||0)} (${percent}%)
New: ${Number(st.new||0)} · Changed: ${Number(st.changed||0)} · Unchanged: ${Number(st.unchanged||0)} · Removed: ${Number(st.removed||0)}${errors?` · Errors: ${errors}`:""}
${escapeHtml(st.current_path||"")}
${warnings}${errors?`
${errors} file(s) failed. Check server journal for [SCAN] errors.
`:""}
`; }).join(""); panel.querySelector("#kronicScanMonitorBody").innerHTML=`

${escapeHtml(stage)}

${lines||'

Waiting for the first library…

'}${!state.running&&state.completed_at?'

Reopen the library to see newly indexed items.

':''}`; if(scanMonitorWasRunning&&!state.running){ clearInterval(activeScanMonitorTimer);activeScanMonitorTimer=null; } scanMonitorWasRunning=Boolean(state.running); } async function pollScanMonitor(){ try{renderScanMonitor(await api("/api/scan/status"));} catch(e){const body=document.getElementById("kronicScanMonitorBody");if(body)body.textContent=`Unable to read scan status: ${e.message}`;} } function openScanMonitor(){ ensureScanMonitor();scanMonitorWasRunning=true;pollScanMonitor(); if(activeScanMonitorTimer)clearInterval(activeScanMonitorTimer); activeScanMonitorTimer=setInterval(pollScanMonitor,1000); } async function startLibraryScan(ids,mode="quick"){ try{ const result=await api("/api/scan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source_ids:ids,mode})}); if(result?.started===false||result?.success===false)throw Error(result?.error||"Scan not started"); openScanMonitor(); // Do NOT navigate to the main Libraries screen. }catch(e){alert(`Library scan could not start: ${e.message}`);} } function startScanPolling(){clearScanPolling();updateScanStatus();scanPollTimer=setInterval(updateScanStatus,1000);} async function updateScanStatus(){ try{ const s=await api("/api/scan/status"); if(s.running&&!document.getElementById("kronicScanMonitor"))openScanMonitor(); if(document.getElementById("kronicScanMonitor"))renderScanMonitor(s); if(!s.running)clearScanPolling(); }catch(e){console.warn("Scan status unavailable",e);} } // Recover a running scan after refreshing a page without showing an idle popup. document.addEventListener("DOMContentLoaded",async()=>{ try{const status=await api("/api/scan/status");if(status.running)openScanMonitor();}catch(_){/* page may not be authenticated */} },{once:true}); async function showManageLibraries(focusSourceId=null){clearScanPolling();resetLibraryContext();installTopNav("home");toolbar.innerHTML='';document.getElementById("manageBack").onclick=showLibraries;document.getElementById("newLib").onclick=()=>showFolderBrowser("/");const sources=await api("/api/sources");content.innerHTML=`

Manage Libraries

${sources.map(s=>`

${escapeHtml(s.name)}

${s.media_count||0} indexed items
${(s.paths||[]).map(p=>`
${escapeHtml(p.path)}
`).join("")}
`).join("")}`;document.querySelectorAll("[data-library-type]").forEach(x=>x.onchange=()=>changeLibraryType(Number(x.dataset.libraryType),x.value));document.querySelectorAll("[data-library-artwork]").forEach(x=>x.onchange=async()=>{const id=Number(x.dataset.libraryArtwork);try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({artwork_preference:x.value})});}catch(e){alert(e.message);showManageLibraries(id);}});document.querySelectorAll("[data-manage-quick-scan]").forEach(x=>x.onclick=()=>scanOneLibrary(Number(x.dataset.manageQuickScan),"quick"));document.querySelectorAll("[data-manage-deep-scan]").forEach(x=>x.onclick=()=>scanOneLibrary(Number(x.dataset.manageDeepScan),"deep"));document.querySelectorAll("[data-toggle-library]").forEach(x=>x.onclick=()=>toggleLibrary(Number(x.dataset.toggleLibrary),Number(x.dataset.enableValue)));document.querySelectorAll("[data-remove-library-path]").forEach(x=>x.onclick=()=>removeLibraryPath(Number(x.dataset.removeLibraryPath)));document.querySelectorAll("[data-remove-library]").forEach(x=>{const s=sources.find(v=>v.id===Number(x.dataset.removeLibrary));x.onclick=()=>removeLibrary(s.id,s.name)});document.querySelectorAll("[data-add-path]").forEach(x=>{const s=sources.find(v=>v.id===Number(x.dataset.addPath));x.onclick=()=>showAddPathBrowser(s.id,s.name,"/")});if(focusSourceId){document.querySelector(`[data-manage-library-card="${Number(focusSourceId)}"]`)?.scrollIntoView({behavior:"smooth",block:"center"});}} async function showFolderBrowser(path){clearScanPolling();const d=await api(`/api/browse?path=${encodeURIComponent(path)}`);toolbar.innerHTML='';document.getElementById("folderBack").onclick=showManageLibraries;content.innerHTML=`

Add Library

Current Folder

${escapeHtml(d.path)}
${d.parent?`
📁 ..
`:""}${d.folders.map(f=>`
📁 ${escapeHtml(f.name)}
`).join("")}
`;document.querySelectorAll("[data-folder-path]").forEach(x=>x.onclick=()=>showFolderBrowser(x.dataset.folderPath));document.getElementById("createLibraryButton").onclick=()=>addLibrary(d.path);} async function showAddPathBrowser(id,name,path){const d=await api(`/api/browse?path=${encodeURIComponent(path)}`);content.innerHTML=`

Add Folder to ${escapeHtml(name)}

${escapeHtml(d.path)}
${d.parent?`
📁 ..
`:""}${d.folders.map(f=>`
📁 ${escapeHtml(f.name)}
`).join("")}
`;document.querySelectorAll("[data-add-folder-path]").forEach(x=>x.onclick=()=>showAddPathBrowser(id,name,x.dataset.addFolderPath));document.getElementById("addCurrentFolderButton").onclick=()=>addPathToLibrary(id,d.path);} async function addLibrary(path){const name=document.getElementById("newLibraryName").value.trim(),type=document.getElementById("newLibraryType").value;if(!name)return alert("Library name is required.");try{await api("/api/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name,path,library_type:type})});showManageLibraries();}catch(e){alert(e.message);}} async function addPathToLibrary(id,path){try{await api(`/api/sources/${id}/paths`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path})});showManageLibraries();}catch(e){alert(e.message);}} async function removeLibraryPath(id){if(!confirm("Remove this folder from the library?\n\nNo files will be deleted."))return;try{await api(`/api/source-paths/${id}`,{method:"DELETE"});showManageLibraries();}catch(e){alert(e.message);}} async function changeLibraryType(id,t){try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({library_type:t})});}catch(e){alert(e.message);}} async function toggleLibrary(id,en){try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:Boolean(en)})});showManageLibraries();}catch(e){alert(e.message);}} async function removeLibrary(id,name){if(!confirm(`Remove "${name}"?\n\nNo media files will be deleted.`))return;try{await api(`/api/sources/${id}`,{method:"DELETE"});showManageLibraries();}catch(e){alert(e.message);}} async function showMoveDialog(mediaId,currentLibraryId){const sources=await api("/api/sources");const a=sources.filter(s=>s.enabled&&s.id!==currentLibraryId);if(!a.length)return alert("No other enabled libraries.");const selected=prompt(`Move to which library?\n\n${a.map(s=>`${s.id}: ${s.name}`).join("\n")}`);if(!selected)return;const target=Number(selected);if(!a.some(s=>s.id===target))return alert("Invalid library ID.");await api("/api/media/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({media_id:mediaId,target_source_id:target})});showLibrary(currentSourceId,currentSourceName,currentSourceType);} function getDisplayTitle(i,episodeView=false){ const t=i.effective_title||i.title_override||i.title||"Unknown"; if(!episodeView)return t; const s=Number(getSeasonNumber(i)); const e=Number(getEpisodeNumber(i)); const et=getEpisodeTitle(i); let prefix=""; if(Number.isFinite(s)&&s>0&&Number.isFinite(e)&&e>0){ prefix=`S${String(s).padStart(2,"0")}E${String(e).padStart(2,"0")}`; }else if(Number.isFinite(e)&&e>0){ prefix=`Episode ${e}`; } return prefix&&et ?`${prefix} — ${et}` :prefix||et||t; } async function performSearch(q){ let url=`/api/search?q=${encodeURIComponent(q)}`; if(currentSourceId!==null){ url+=`&source_id=${currentSourceId}`; } try{ const results=await api(url); if(currentSourceType==="shows"&¤tSourceId!==null){ renderMediaGrid( results, `Search: ${q}`, "", true ); }else{ renderMediaGrid( results, `Search: ${q}` ); } }catch(error){ showError(error); } } function setLibraryToolbar(backLabel,backHandler,sortKey=null,rerender=null){ toolbar.innerHTML=""; installTopNav("library", { backLabel, backHandler, sortKey, rerender, }); } async function showLibrary(id,name,type){ clearScanPolling(); currentSourceId=Number(id); currentSourceName=name; currentSourceType=type||"movies"; currentShowName=null; updateSearchPlaceholder(); const sortKey=`library:${currentSourceId}`; breadcrumb.innerHTML=`Libraries › ${escapeHtml(name)}`; try{ const media=await api(`/api/media?source_id=${id}`); if(type==="shows"){renderShows(media);return;} const rerender=()=>{ setLibraryToolbar("Libraries",showLibraries,sortKey,rerender); renderMediaGrid( sortedMediaItems(media,sortKey,item=>getDisplayTitle(item,false)), name ); }; rerender(); }catch(e){showError(e);} } function getShowName(i){return i.effective_series_title||i.series_title_override||i.series_title||(mediaPathParts(i).length>=2?mediaPathParts(i)[0]:(i.effective_title||i.title||"Unknown Show"));} function getSeasonNumber(i){return i.effective_season??i.season_override??i.season??null;} function getEpisodeNumber(i){return i.effective_episode??i.episode_override??i.episode??null;} function getEpisodeTitle(i){return i.effective_episode_title??i.episode_title_override??i.episode_title??null;} function getSeasonName(i){const n=getSeasonNumber(i);if(n!==null&&n!=="")return`Season ${Number(n)}`;const p=mediaPathParts(i);return p.length>=3?p[1]:"Episodes";} function renderShows(media){ const sortKey=`library:${currentSourceId}`; breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)}`; const shows=new Map(); media.forEach(i=>{const n=getShowName(i);if(!shows.has(n))shows.set(n,[]);shows.get(n).push(i);}); const rerender=()=>{ setLibraryToolbar("Libraries",showLibraries,sortKey,rerender); const entries=sortedGroups([...shows.entries()],sortKey); content.innerHTML=`

${escapeHtml(currentSourceName)}

${entries.map(([n,items])=>{ const totalLength=items.reduce((sum,item)=>sum+durationValue(item),0); return`
${escapeHtml(n)}
${new Set(items.map(getSeasonName)).size} seasons
${items.length} episodes
${escapeHtml(formatDurationShort(totalLength))}
`; }).join("")}
`; document.querySelectorAll(".show-card").forEach(c=>c.onclick=()=>openShow(c.dataset.showName)); }; rerender(); } async function openShow(name){ currentShowName=name; const sortKey=`show:${currentSourceId}:${name}`; breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)} › ${escapeHtml(name)}`; const media=await api(`/api/media?source_id=${currentSourceId}`); const items=media.filter(i=>getShowName(i)===name); const seasons=new Map(); items.forEach(i=>{const n=getSeasonName(i);if(!seasons.has(n))seasons.set(n,[]);seasons.get(n).push(i);}); const rerender=()=>{ setLibraryToolbar(currentSourceName,()=>showLibrary(currentSourceId,currentSourceName,currentSourceType),sortKey,rerender); const entries=sortedGroups([...seasons.entries()],sortKey); content.innerHTML=`

${escapeHtml(name)}

${entries.map(([seasonName,seasonItems])=>{ const totalLength=seasonItems.reduce((sum,item)=>sum+durationValue(item),0); return`
${escapeHtml(seasonName)}
${seasonItems.length} episodes
${escapeHtml(formatDurationShort(totalLength))}
`; }).join("")}
`; document.querySelectorAll(".season-card").forEach(c=>c.onclick=()=>openSeason(name,c.dataset.seasonName)); }; rerender(); } async function openSeason(show,season){ currentShowName=show; const sortKey=`season:${currentSourceId}:${show}:${season}`; breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)} › ${escapeHtml(show)} › ${escapeHtml(season)}`; const media=await api(`/api/media?source_id=${currentSourceId}`); const eps=media.filter(i=>getShowName(i)===show&&getSeasonName(i)===season); const rerender=()=>{ setLibraryToolbar(show,()=>openShow(show),sortKey,rerender); renderMediaGrid( sortedMediaItems(eps,sortKey,item=>getDisplayTitle(item,true)), `${show} — ${season}`, "", true ); }; rerender(); } function normalizeAudioLanguage(value){ const code=String(value||"").toLowerCase(); const names={eng:"English",en:"English",fra:"French",fre:"French",fr:"French",spa:"Spanish",es:"Spanish",deu:"German",ger:"German",de:"German",jpn:"Japanese",ja:"Japanese",ita:"Italian",it:"Italian"}; return names[code]||code.toUpperCase()||"Audio"; } function audioTrackLabel(track){ const parts=[]; if(track.title)parts.push(track.title); else parts.push(normalizeAudioLanguage(track.language)); if(track.codec)parts.push(String(track.codec).toUpperCase()); const channels=Number(track.channels)||0; if(channels)parts.push(channels===1?"1.0":channels===2?"2.0":channels===6?"5.1":channels===8?"7.1":`${channels}ch`); return parts.join(" · "); } function qualityChoices(item){ const h=Number(item.video_height)||(()=>{const m=String(item.resolution||"").match(/x(\d+)$/);return m?Number(m[1]):0;})(); const choices=[{value:"original",label:h?`Original ${h}p`:"Original"}]; [720,480,360].forEach(v=>{if(h>v)choices.push({value:String(v),label:`${v}p`});}); return choices; } function playbackSelectorMarkup(item){ const q=qualityChoices(item); const tracks=Array.isArray(item.audio_tracks)?item.audio_tracks:[]; const qHtml=q.length>1 ?`` :`
Quality${escapeHtml(q[0].label)}
`; let aHtml=""; if(tracks.length>1){ aHtml=``; }else if(tracks.length===1){ aHtml=`
Audio${escapeHtml(audioTrackLabel(tracks[0]))}
`; }else{ aHtml=`
AudioDetecting…
`; } return `
${qHtml}${aHtml}
`; } function playbackOptionsForMedia(id){ return { quality:document.querySelector(`[data-quality-for="${id}"]`)?.value||"original", audio:document.querySelector(`[data-audio-for="${id}"]`)?.value??null, }; } async function hydratePlaybackOptionsForCard(mediaId){ const pending=document.querySelector(`[data-audio-pending="${mediaId}"]`); if(!pending) return; try{ const data=await api(`/api/media/${mediaId}/playback-options`); const tracks=Array.isArray(data.audio_tracks)?data.audio_tracks:[]; let replacement=""; if(tracks.length>1){ replacement=``; }else if(tracks.length===1){ replacement=`
Audio${escapeHtml(audioTrackLabel(tracks[0]))}
`; }else{ replacement=`
AudioNo audio stream
`; } pending.outerHTML=replacement; const select=document.querySelector(`[data-audio-for="${mediaId}"]`); if(select) select.onclick=event=>event.stopPropagation(); }catch(error){ const target=document.querySelector(`[data-audio-pending="${mediaId}"] strong`); if(target) target.textContent="Unavailable"; } } function hydrateVisiblePlaybackOptions(){ const cards=[...document.querySelectorAll("[data-audio-pending]")]; if(!cards.length) return; if(!("IntersectionObserver" in window)){ cards.forEach(node=>hydratePlaybackOptionsForCard(Number(node.dataset.audioPending))); return; } const observer=new IntersectionObserver(entries=>{ for(const entry of entries){ if(!entry.isIntersecting) continue; const node=entry.target; observer.unobserve(node); hydratePlaybackOptionsForCard(Number(node.dataset.audioPending)); } },{rootMargin:"180px"}); cards.forEach(node=>observer.observe(node)); } function launchTileMedia(id,title){ return openPlayer(Number(id),title,playbackOptionsForMedia(id)); } function renderMediaGrid(media,title,extra="",episodeView=false){ content.innerHTML=`

${escapeHtml(title)}

${extra}
${media.map(i=>{ const t=getDisplayTitle(i,episodeView); return`
▶
▶
${escapeHtml(t)}${escapeHtml(i.effective_year??i.year??"")} ${i.duration_seconds?`· ${escapeHtml(formatDurationShort(i.duration_seconds))}`:""}
${escapeHtml(i.resolution||"Unknown")}${escapeHtml(i.source_name||"Uncategorized")}
${playbackSelectorMarkup(i)}
External${canManageMedia()?``:""}
`; }).join("")}
`; document.querySelectorAll("[data-play-id]").forEach(e=>e.onclick=()=>launchTileMedia(Number(e.dataset.playId),e.dataset.playTitle)); document.querySelectorAll("[data-play-button]").forEach(e=>e.onclick=()=>launchTileMedia(Number(e.dataset.playButton),e.dataset.playTitle)); document.querySelectorAll("[data-quality-for],[data-audio-for]").forEach(e=>{e.onclick=ev=>ev.stopPropagation();}); document.querySelectorAll("[data-move-id]").forEach(e=>e.onclick=()=>showMoveDialog(Number(e.dataset.moveId),Number(e.dataset.currentLibrary))); hydrateVisiblePlaybackOptions(); } async function showMoveDialog(mediaId,currentLibraryId){const sources=await api("/api/sources");const a=sources.filter(s=>s.enabled&&s.id!==currentLibraryId);if(!a.length)return alert("No other enabled libraries.");const selected=prompt(`Move to which library?\n\n${a.map(s=>`${s.id}: ${s.name}`).join("\n")}`);if(!selected)return;const target=Number(selected);if(!a.some(s=>s.id===target))return alert("Invalid library ID.");await api("/api/media/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({media_id:mediaId,target_source_id:target})});showLibrary(currentSourceId,currentSourceName,currentSourceType);} async function showMetadataEditor(initialSourceId=null) { clearScanPolling(); installTopNav("metadata"); resetLibraryContext(); stopYouTubePolling(); const sources = await api("/api/sources"); metadataSources = sources; const selectedId = Number(initialSourceId) || 0; content.innerHTML = `

Metadata

YouTube Metadata

Read the YouTube video ID from filenames, preview the real YouTube title, then update this media server. Rename mode is optional and never deletes a media file.
Choose a library and click Preview.
`; document.getElementById("metadataLoadButton").onclick = loadMetadataTable; document.getElementById("metadataLibraryFilter").onchange = loadMetadataTable; document.getElementById("metadataSearchInput").onkeydown = e => { if (e.key === "Enter") loadMetadataTable(); }; document.getElementById("youtubePreviewButton").onclick = startYouTubePreview; document.getElementById("youtubeApplyButton").onclick = applyYouTubeChanges; document.getElementById("youtubeLibrarySelect").onchange = () => { document.getElementById("youtubeApplyButton").disabled = true; document.getElementById("youtubePreviewResults").innerHTML = ""; document.getElementById("youtubeStatus").textContent = "Click Preview to inspect this library."; }; loadMetadataTable(); refreshYouTubeStatus(); } async function loadMetadataTable(){const target=document.getElementById("metadataTableContainer");const sid=document.getElementById("metadataLibraryFilter")?.value||"";const q=document.getElementById("metadataSearchInput")?.value.trim()||"";let url=q?`/api/search?q=${encodeURIComponent(q)}`:"/api/media";if(sid)url+=`${url.includes("?")?"&":"?"}source_id=${sid}`;try{renderMetadataTable(await api(url));}catch(e){target.innerHTML=`
${escapeHtml(e.message)}
`;}} function renderMetadataTable(media){const target=document.getElementById("metadataTableContainer");if(!media.length){target.innerHTML='
No media found.
';return;}target.innerHTML=`
${media.map(i=>``).join("")}
PreviewTitleSeriesEpisode TitleYearSeasonEpisodeResolutionLibraryActions
`;document.querySelectorAll("[data-metadata-save]").forEach(b=>b.onclick=()=>saveMetadataRow(Number(b.dataset.metadataSave)));document.querySelectorAll("[data-metadata-reset]").forEach(b=>b.onclick=()=>resetMetadataRow(Number(b.dataset.metadataReset)));document.querySelectorAll("[data-metadata-reanalyze]").forEach(b=>b.onclick=()=>reanalyzeMedia(Number(b.dataset.metadataReanalyze)));document.querySelectorAll("[data-metadata-info]").forEach(b=>b.onclick=()=>showMediaInfo(Number(b.dataset.metadataInfo)));} async function saveMetadataRow(id){const r=document.querySelector(`.metadata-row[data-media-id="${id}"]`);const p={title:r.querySelector(".metadata-title-input").value.trim(),series_title:r.querySelector(".metadata-series-input").value.trim(),episode_title:r.querySelector(".metadata-episode-title-input").value.trim(),year:nullableNumber(r.querySelector(".metadata-year-input").value),season:nullableNumber(r.querySelector(".metadata-season-input").value),episode:nullableNumber(r.querySelector(".metadata-episode-input").value)};try{await api(`/api/media/${id}/metadata`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});r.classList.add("metadata-row-saved");setTimeout(()=>r.classList.remove("metadata-row-saved"),1000);}catch(e){alert(e.message);}} async function resetMetadataRow(id){if(!confirm("Reset manual metadata overrides for this item?"))return;await api(`/api/media/${id}/metadata-overrides`,{method:"DELETE"});loadMetadataTable();} async function reanalyzeMedia(id){const r=await api(`/api/media/${id}/reanalyze`,{method:"POST"});if(r.removed_short)alert("This item is under the minimum duration and was removed from the media index.");loadMetadataTable();} async function showMediaInfo(id){const d=await api(`/api/media/${id}/mediainfo`);closeMetadataInfo();const o=document.createElement("div");o.id="metadataInfoOverlay";o.className="metadata-info-overlay";o.innerHTML=`

MediaInfo

${escapeHtml(d.file||"")}

Normalized Metadata

${escapeHtml(JSON.stringify(d.normalized||{},null,2))}

GuessIt

${escapeHtml(JSON.stringify(d.guessit||{},null,2))}

MediaInfo

${escapeHtml(JSON.stringify(d.mediainfo||{},null,2))}
`;document.body.appendChild(o);document.getElementById("closeMetadataInfoButton").onclick=closeMetadataInfo;o.onclick=e=>{if(e.target===o)closeMetadataInfo();};} function closeMetadataInfo(){document.getElementById("metadataInfoOverlay")?.remove();} function injectYouTubeMetadataStyles() { if (document.getElementById("youtubeMetadataStyles")) return; const style = document.createElement("style"); style.id = "youtubeMetadataStyles"; style.textContent = ` .youtube-metadata-panel { margin-bottom: 24px; } .youtube-metadata-heading { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:16px; } .youtube-metadata-heading h3 { margin:0 0 6px 0; } .youtube-controls { display:flex; flex-wrap:wrap; gap:12px; align-items:end; margin-bottom:14px; } .youtube-controls .metadata-filter-group { min-width:220px; } .youtube-force-refresh { display:flex; gap:8px; align-items:center; min-height:38px; } .youtube-status { margin:8px 0; } .youtube-progress-wrap { margin:10px 0 16px; } .youtube-preview-table { width:100%; border-collapse:collapse; margin-top:14px; } .youtube-preview-table th, .youtube-preview-table td { padding:9px 10px; border-bottom:1px solid rgba(255,255,255,.1); text-align:left; vertical-align:top; } .youtube-preview-table th { position:sticky; top:0; background:#171717; z-index:1; } .youtube-preview-table code { white-space:normal; overflow-wrap:anywhere; } .youtube-preview-scroll { overflow:auto; max-height:520px; border:1px solid rgba(255,255,255,.08); border-radius:6px; } .youtube-status-ready { opacity:.95; } .youtube-status-error { color:#ff8a8a; } .youtube-status-applied { color:#9be29b; } .youtube-summary { margin:10px 0; display:flex; flex-wrap:wrap; gap:14px; } .youtube-title-arrow { opacity:.55; padding:0 5px; } `; document.head.appendChild(style); } function stopYouTubePolling() { if (youtubePollTimer) { clearInterval(youtubePollTimer); youtubePollTimer = null; } } function startYouTubePolling() { stopYouTubePolling(); youtubePollTimer = setInterval(refreshYouTubeStatus, 750); } async function startYouTubePreview() { const sourceId = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); if (!sourceId) return alert("Choose the library you want to inspect first."); const forceRefresh = !!document.getElementById("youtubeForceRefresh")?.checked; const applyButton = document.getElementById("youtubeApplyButton"); if (applyButton) applyButton.disabled = true; try { await api("/api/youtube/preview", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({source_id: sourceId, force_refresh: forceRefresh}) }); startYouTubePolling(); await refreshYouTubeStatus(); } catch (error) { alert(error.message); } } async function applyYouTubeChanges() { const sourceId = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); const mode = document.getElementById("youtubeModeSelect")?.value || "metadata"; if (!sourceId) return alert("Choose a library first."); if (mode === "rename") { const ok = confirm( "Rename the matching media files using their YouTube titles?\n\n" + "The YouTube ID will be kept in [brackets]. Existing files are never overwritten." ); if (!ok) return; } try { await api("/api/youtube/apply", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({source_id: sourceId, mode}) }); document.getElementById("youtubeApplyButton").disabled = true; startYouTubePolling(); await refreshYouTubeStatus(); } catch (error) { alert(error.message); } } async function refreshYouTubeStatus() { const statusElement = document.getElementById("youtubeStatus"); if (!statusElement) { stopYouTubePolling(); return; } try { const state = await api("/api/youtube/status"); renderYouTubeStatus(state); if (state.running) startYouTubePolling(); else stopYouTubePolling(); } catch (error) { statusElement.textContent = `YouTube metadata status error: ${error.message}`; stopYouTubePolling(); } } function renderYouTubeStatus(state) { const statusElement = document.getElementById("youtubeStatus"); const progressWrap = document.getElementById("youtubeProgressWrap"); const progressBar = document.getElementById("youtubeProgressBar"); const progressText = document.getElementById("youtubeProgressText"); const resultsElement = document.getElementById("youtubePreviewResults"); const applyButton = document.getElementById("youtubeApplyButton"); const selectedLibrary = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); if (!statusElement || !resultsElement) return; const belongsToSelection = !selectedLibrary || Number(state.source_id || 0) === selectedLibrary; if (!belongsToSelection && state.phase !== "idle") return; statusElement.textContent = state.message || (state.running ? "Working..." : "Choose a library and click Preview."); if (state.running || state.phase === "preview_complete" || state.phase === "apply_complete") { progressWrap.hidden = false; progressBar.style.width = `${Number(state.percent || 0)}%`; progressText.textContent = `${state.processed || 0} / ${state.total || 0} — ${state.percent || 0}%`; } else { progressWrap.hidden = true; } if (Array.isArray(state.results) && state.results.length) { renderYouTubePreviewResults(state.results, state); } else if (!state.running) { resultsElement.innerHTML = ""; } if (applyButton) { const ready = Array.isArray(state.results) && state.results.some(item => item.status === "ready"); applyButton.disabled = state.running || state.phase !== "preview_complete" || !ready || !belongsToSelection; } if (state.phase === "apply_complete") { loadMetadataTable(); } } function renderYouTubePreviewResults(results, state) { const target = document.getElementById("youtubePreviewResults"); if (!target) return; const readyCount = results.filter(item => item.status === "ready").length; const errorCount = results.filter(item => item.status === "error" || item.apply_status === "error").length; const cachedCount = results.filter(item => item.cached).length; target.innerHTML = `
${readyCount} matched YouTube videos ${state.skipped || 0} files without an ID ${cachedCount} cache hits ${errorCount} errors
${results.map(item => { const statusClass = item.apply_status === "applied" ? "youtube-status-applied" : (item.error ? "youtube-status-error" : "youtube-status-ready"); const statusText = item.apply_status === "applied" ? "Applied" : (item.error || (item.cached ? "Ready (cached)" : "Ready")); return ` `; }).join("")}
ID Current title YouTube title Channel Filename Status
${escapeHtml(item.video_id || "-")} ${escapeHtml(item.current_title || "-")} ${escapeHtml(item.proposed_title || "-")} ${escapeHtml(item.channel_name || "-")} ${escapeHtml(item.current_filename || "-")}${item.proposed_filename ? `→${escapeHtml(item.proposed_filename)}` : ""} ${escapeHtml(statusText)}
`; } // ============================================================ // YOUTUBE LIBRARY TAB / SEARCH / WATCHED CACHE // ============================================================ let youtubeItemRegistry = new Map(); let youtubePlayerOverlay = null; let youtubeVideoElement = null; let youtubeActiveItem = null; // Kronic Cast receiver bridge. One open/authenticated Kronic browser is the // active "screen"; commands arrive by long-poll from the Python receiver. let kronicCastClientId = null; let kronicCastSeq = 0; let kronicCastRunning = false; let kronicCastLastStateSent = 0; let kronicCastStateTimer = null; let youtubeProgressTimer = null; let youtubePlaybackBaseOffset = 0; let youtubeKnownDuration = null; let youtubePendingClientSeek = null; let youtubeSeekMode = "server"; let musicTrackRegistry = new Map(); let musicQueue = []; let musicQueueIndex = -1; let musicPlayer = null; function ensureTwitchPlayer(){ if(twitchPlayerOverlay)return; twitchPlayerOverlay=document.createElement("div"); twitchPlayerOverlay.className="youtube-player-overlay twitch-player-overlay"; twitchPlayerOverlay.style.display="none"; twitchPlayerOverlay.innerHTML=`
Twitch
`; document.body.appendChild(twitchPlayerOverlay); twitchVideoElement=document.getElementById("twitchVideoElement"); document.getElementById("twitchPlayerClose").onclick=closeTwitchPlayer; document.getElementById("twitchPlayerMinimize").onclick=()=>{ const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); const minimizing=!twitchPlayerOverlay.classList.contains("minimized"); if(minimizing && win){ win.dataset.restoreLeft=win.style.left||""; win.dataset.restoreTop=win.style.top||""; win.dataset.restoreWidth=win.style.width||""; win.dataset.restoreHeight=win.style.height||""; twitchPlayerOverlay.classList.add("minimized"); }else{ twitchPlayerOverlay.classList.remove("minimized"); if(win){ if(win.dataset.restoreLeft)win.style.left=win.dataset.restoreLeft; if(win.dataset.restoreTop)win.style.top=win.dataset.restoreTop; if(win.dataset.restoreWidth)win.style.width=win.dataset.restoreWidth; if(win.dataset.restoreHeight)win.style.height=win.dataset.restoreHeight; } } }; document.getElementById("twitchPlayerFullscreen").onclick=async()=>{ const windowElement=twitchPlayerOverlay.querySelector(".youtube-player-window"); if(!document.fullscreenElement){ try{await windowElement.requestFullscreen();}catch{} }else{ try{await document.exitFullscreen();}catch{} } }; document.getElementById("twitchPlayerRecord").onclick=()=>{ if(twitchActiveChannel) startTwitchRecording(twitchActiveChannel.id); }; bindTwitchPlayerDragResize(); } function bindTwitchPlayerDragResize(){ if(twitchPlayerDragBound || !twitchPlayerOverlay)return; const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); const header=twitchPlayerOverlay.querySelector(".youtube-player-header"); const resizeHandle=twitchPlayerOverlay.querySelector(".twitch-player-resize-handle"); if(!win || !header || !resizeHandle)return; twitchPlayerDragBound=true; // Convert from CSS inset positioning to pixel left/top sizing the first time // the user interacts with the Twitch player. const normalizeWindowRect=()=>{ const rect=win.getBoundingClientRect(); win.style.position="fixed"; win.style.transform="none"; win.style.left=`${rect.left}px`; win.style.top=`${rect.top}px`; win.style.right="auto"; win.style.bottom="auto"; win.style.width=`${rect.width}px`; win.style.height=`${rect.height}px`; return rect; }; header.style.cursor="move"; header.title="Drag player · double-click to reset position"; header.addEventListener("dblclick",event=>{ if(event.target.closest("button,select,input,a"))return; positionTwitchPlayerOnScreen(true); }); header.addEventListener("pointerdown",event=>{ if(event.button!==0)return; if(event.target.closest("button,select,input,a"))return; if(twitchPlayerOverlay.classList.contains("minimized"))return; event.preventDefault(); const rect=normalizeWindowRect(); const startX=event.clientX; const startY=event.clientY; const startLeft=rect.left; const startTop=rect.top; header.setPointerCapture?.(event.pointerId); const move=moveEvent=>{ const dx=moveEvent.clientX-startX; const dy=moveEvent.clientY-startY; const maxLeft=Math.max(0,window.innerWidth-win.offsetWidth); const maxTop=Math.max(0,window.innerHeight-win.offsetHeight); win.style.left=`${Math.max(0,Math.min(maxLeft,startLeft+dx))}px`; win.style.top=`${Math.max(0,Math.min(maxTop,startTop+dy))}px`; }; const up=upEvent=>{ header.releasePointerCapture?.(upEvent.pointerId); header.removeEventListener("pointermove",move); header.removeEventListener("pointerup",up); header.removeEventListener("pointercancel",up); }; header.addEventListener("pointermove",move); header.addEventListener("pointerup",up); header.addEventListener("pointercancel",up); }); resizeHandle.addEventListener("pointerdown",event=>{ if(event.button!==0)return; if(twitchPlayerOverlay.classList.contains("minimized"))return; event.preventDefault(); event.stopPropagation(); const rect=normalizeWindowRect(); const startX=event.clientX; const startY=event.clientY; const startWidth=rect.width; const startHeight=rect.height; resizeHandle.setPointerCapture?.(event.pointerId); const move=moveEvent=>{ const minWidth=360; const minHeight=240; const maxWidth=Math.max(minWidth,window.innerWidth-rect.left); const maxHeight=Math.max(minHeight,window.innerHeight-rect.top); const width=Math.max( minWidth, Math.min(maxWidth,startWidth+(moveEvent.clientX-startX)) ); const height=Math.max( minHeight, Math.min(maxHeight,startHeight+(moveEvent.clientY-startY)) ); win.style.width=`${width}px`; win.style.height=`${height}px`; }; const up=upEvent=>{ resizeHandle.releasePointerCapture?.(upEvent.pointerId); resizeHandle.removeEventListener("pointermove",move); resizeHandle.removeEventListener("pointerup",up); resizeHandle.removeEventListener("pointercancel",up); }; resizeHandle.addEventListener("pointermove",move); resizeHandle.addEventListener("pointerup",up); resizeHandle.addEventListener("pointercancel",up); }); // Keep the window on-screen after browser resize. window.addEventListener("resize",()=>{ if(!twitchPlayerOverlay.classList.contains("open"))return; if(twitchPlayerOverlay.classList.contains("minimized"))return; positionTwitchPlayerOnScreen(false); }); } function positionTwitchPlayerOnScreen(forceReset=false){ if(!twitchPlayerOverlay)return; const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); const header=twitchPlayerOverlay.querySelector(".youtube-player-header"); if(!win)return; const viewportW=Math.max(360,window.innerWidth); const viewportH=Math.max(260,window.innerHeight); let rect=win.getBoundingClientRect(); const headerHeight=Math.max(44,header?.getBoundingClientRect().height||44); const headerOffscreen= rect.top < 8 || rect.left < 0 || rect.top + headerHeight > viewportH || rect.left + 120 > viewportW; if(forceReset || headerOffscreen){ const width=Math.min(900,Math.max(520,Math.floor(viewportW*0.62))); const height=Math.min(620,Math.max(360,Math.floor(viewportH*0.62))); const left=Math.max(12,Math.floor((viewportW-width)/2)); const top=Math.max(70,Math.floor((viewportH-height)/2)); win.style.position="fixed"; win.style.transform="none"; win.style.left=`${left}px`; win.style.top=`${top}px`; win.style.right="auto"; win.style.bottom="auto"; win.style.width=`${Math.min(width,viewportW-left-12)}px`; win.style.height=`${Math.min(height,viewportH-top-12)}px`; }else{ // Clamp an existing user-sized window so the header always remains // reachable even after browser resize. const width=Math.min(rect.width,viewportW-24); const height=Math.min(rect.height,viewportH-24); const left=Math.max( 12, Math.min(rect.left,viewportW-width-12) ); const top=Math.max( 70, Math.min(rect.top,viewportH-headerHeight-12) ); win.style.position="fixed"; win.style.transform="none"; win.style.left=`${left}px`; win.style.top=`${top}px`; win.style.right="auto"; win.style.bottom="auto"; win.style.width=`${Math.max(360,width)}px`; win.style.height=`${Math.max(240,height)}px`; } } async function openTwitchPlayer(channel){ ensureTwitchPlayer(); twitchActiveChannel=channel; document.getElementById("twitchPlayerTitle").textContent= channel.title || channel.channel_name || "Twitch"; twitchPlayerOverlay.classList.add("open"); twitchPlayerOverlay.classList.remove("minimized"); twitchPlayerOverlay.style.display="block"; twitchPlayerOverlay.style.visibility="visible"; twitchPlayerOverlay.style.opacity="1"; twitchPlayerOverlay.style.pointerEvents="auto"; twitchPlayerOverlay.style.zIndex="9999"; // The Twitch player must never open with its drag header above the // viewport. Older inline geometry can otherwise pin the video at 0,0. positionTwitchPlayerOnScreen(false); const quality=channel.quality||"best"; twitchVideoElement.controls=true; twitchVideoElement.autoplay=true; twitchVideoElement.playsInline=true; twitchVideoElement.src=roomMediaUrl( channel.roomSyncLive ? `/api/twitch/live/${encodeURIComponent(channel.channel_name)}/play?quality=${encodeURIComponent(quality)}` : `/api/twitch/channels/${encodeURIComponent(channel.id)}/play?quality=${encodeURIComponent(quality)}`); twitchVideoElement.play().catch(error => console.debug("Twitch autoplay delayed or blocked", error)); } function closeTwitchPlayer(){ if(twitchVideoElement){ try{twitchVideoElement.pause();}catch{} twitchVideoElement.removeAttribute("src"); twitchVideoElement.load(); } if(twitchPlayerOverlay){ twitchPlayerOverlay.classList.remove("open","minimized"); twitchPlayerOverlay.style.display="none"; } twitchActiveChannel=null; } async function twitchApiPost(url,data={}){ return api(url,{ method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(data), }); } async function showTwitchLibrary(){ clearScanPolling(); stopYouTubePolling?.(); installTopNav("twitch"); breadcrumb.innerHTML=`Live  ›  Twitch`; content.innerHTML=`

Twitch

Streamlink resolves Twitch. Kronic handles playback and DVR recording through FFmpeg.

Channels

Watch · Record Live · Auto Record When Live
Loading Twitch channels…

Recordings

`; document.getElementById("twitchAddForm").onsubmit=async event=>{ event.preventDefault(); const input=document.getElementById("twitchChannelInput"); const status=document.getElementById("twitchStatus"); const value=input.value.trim(); if(!value)return; status.textContent="Resolving Twitch channel…"; try{ const channel=await twitchApiPost("/api/twitch/channels",{url:value}); input.value=""; status.textContent=`Added ${channel.channel_name}.`; await loadTwitchOverview(); }catch(error){ status.textContent=`Add failed: ${error.message}`; } }; document.getElementById("twitchRefreshAll").onclick=async()=>{ const data=await api("/api/twitch/overview"); for(const channel of data.channels||[]){ try{ await twitchApiPost(`/api/twitch/channels/${channel.id}/refresh`); }catch{} } await loadTwitchOverview(); }; document.getElementById("twitchClearFinished").onclick=async()=>{ await twitchApiPost("/api/twitch/recordings/clear"); await loadTwitchOverview(); }; await loadTwitchOverview(); clearInterval(twitchPollTimer); twitchPollTimer=setInterval(loadTwitchOverview,5000); } function twitchChannelCard(channel){ const live=Boolean(Number(channel.live||0)); const qualities=String(channel.available_qualities||"") .split(",") .filter(Boolean); if(!qualities.includes("best"))qualities.unshift("best"); return `
${escapeHtml(channel.author||channel.channel_name)}
${live?"LIVE":"Offline"}${channel.category?` · ${escapeHtml(channel.category)}`:""}
${live?`LIVE`:""}
${escapeHtml(channel.title || (live?"Live stream":"Channel offline"))}
`; } async function loadTwitchOverview(){ const channelArea=document.getElementById("twitchChannelArea"); const recordingArea=document.getElementById("twitchRecordingArea"); if(!channelArea||!recordingArea)return; try{ const data=await api("/api/twitch/overview"); const channels=data.channels||[]; const recordings=data.recordings||[]; api('/api/recordings/scheduled').then(jobs=>{ const host=document.getElementById('kronicScheduledRecordingList'); if(!host)return; const relevant=(jobs||[]).filter(job=>job.provider==='twitch').slice(0,12); host.replaceChildren(); if(!relevant.length)return; const label=document.createElement('h4');label.textContent='Scheduled recordings';host.append(label); relevant.forEach(job=>{ const row=document.createElement('div');row.className='kronic-scheduled-item'; const name=document.createElement('span'); name.textContent=`${job.title||job.media_key} — ${new Date(job.start_at*1000).toLocaleString()} (${job.status})`; row.append(name); if(job.status==='scheduled'){ const cancel=document.createElement('button');cancel.textContent='Cancel'; cancel.onclick=async()=>{ await api(`/api/recordings/scheduled/${job.id}`,{method:'DELETE'}); loadTwitchOverview().catch(()=>{}); }; row.append(cancel); } host.append(row); }); }).catch(error=>console.debug('Scheduled recordings unavailable',error)); const byId=new Map(channels.map(channel=>[String(channel.id),channel])); channelArea.innerHTML=channels.length ?channels.map(twitchChannelCard).join("") :`
No Twitch channels yet.
`; recordingArea.innerHTML=recordings.length ?recordings.map(job=>`
${escapeHtml(job.title||job.channel_name||"Twitch recording")}
${escapeHtml(job.channel_name||"")} · ${escapeHtml(job.status)} · ${escapeHtml(job.message||"")}
${job.output_path?`${escapeHtml(job.output_path)}`:""} ${job.error?`${escapeHtml(job.error)}`:""}
${job.status==="recording"||job.status==="queued" ?`` :""}
`).join("") :`
No Twitch recordings yet.
`; channelArea.querySelectorAll("[data-twitch-watch]").forEach(button=>{ button.onclick=()=>{ const channel=byId.get(String(button.dataset.twitchWatch)); if(channel)openTwitchPlayer(channel); }; }); channelArea.querySelectorAll("[data-twitch-record]").forEach(button=>{ button.onclick=()=>startTwitchRecording(button.dataset.twitchRecord); }); channelArea.querySelectorAll("[data-twitch-schedule]").forEach(button=>{ button.onclick=()=>{ const channel=byId.get(String(button.dataset.twitchSchedule)); if(channel) openRecordingScheduler('twitch', String(channel.id), channel.channel_name || 'Twitch'); }; }); channelArea.querySelectorAll("[data-twitch-auto]").forEach(button=>{ button.onclick=async()=>{ const channel=byId.get(String(button.dataset.twitchAuto)); if(!channel)return; await twitchApiPost( `/api/twitch/channels/${channel.id}/auto`, {enabled:!Boolean(Number(channel.auto_record))} ); await loadTwitchOverview(); }; }); channelArea.querySelectorAll("[data-twitch-refresh]").forEach(button=>{ button.onclick=async()=>{ await twitchApiPost(`/api/twitch/channels/${button.dataset.twitchRefresh}/refresh`); await loadTwitchOverview(); }; }); channelArea.querySelectorAll("[data-twitch-remove]").forEach(button=>{ button.onclick=async()=>{ try{ await api(`/api/twitch/channels/${button.dataset.twitchRemove}`,{ method:"DELETE" }); await loadTwitchOverview(); }catch(error){ alert(`Remove failed: ${error.message}`); } }; }); channelArea.querySelectorAll("[data-twitch-quality]").forEach(select=>{ select.onchange=async()=>{ await twitchApiPost( `/api/twitch/channels/${select.dataset.twitchQuality}/quality`, {quality:select.value} ); await loadTwitchOverview(); }; }); recordingArea.querySelectorAll("[data-twitch-stop]").forEach(button=>{ button.onclick=async()=>{ await twitchApiPost(`/api/twitch/recordings/${button.dataset.twitchStop}/stop`); await loadTwitchOverview(); }; }); }catch(error){ channelArea.innerHTML=`
${escapeHtml(error.message)}
`; } } // Scheduling is persisted on the server; closing this page does not cancel a job. async function openRecordingScheduler(provider, mediaKey, title){ const existing=document.getElementById('kronicRecordingScheduleDialog'); existing?.remove(); const dialog=document.createElement('dialog'); dialog.id='kronicRecordingScheduleDialog'; dialog.className='kronic-recording-dialog'; const now=new Date(Date.now()+60000); const localValue = new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().slice(0,16); dialog.innerHTML=`

Schedule ${provider==='twitch'?'Twitch':'YouTube live'} recording

${escapeHtml(title||mediaKey)} — the server starts the recording at this time, even with the browser closed.

`; document.body.append(dialog); dialog.showModal(); dialog.querySelector('#kronicScheduleConfirm').onclick=async()=>{ const input=dialog.querySelector('[name="start"]'); const date=new Date(input.value); if(!input.value || !Number.isFinite(date.valueOf())){ dialog.querySelector('#kronicRecordingError').textContent='Select a valid date and time.';return; } try{ await api('/api/recordings/scheduled',{ method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({provider,media_key:String(mediaKey),title,start_at:date.toISOString()}) }); dialog.close();dialog.remove(); if(provider==='twitch') loadTwitchOverview().catch(()=>{}); alert('Recording scheduled. The server will start at the selected time.'); }catch(error){dialog.querySelector('#kronicRecordingError').textContent=error.message;} }; dialog.addEventListener('close',()=>dialog.remove()); } async function startTwitchRecording(channelId){ try{ await twitchApiPost(`/api/twitch/channels/${channelId}/record`); await loadTwitchOverview(); }catch(error){ alert(`Record Live failed: ${error.message}`); } } function ensureYouTubeLibraryStyles() { if (document.getElementById("youtubeLibraryStyles")) return; const link = document.createElement("link"); link.id = "youtubeLibraryStyles"; link.rel = "stylesheet"; link.href = "/CSS/youtube.css"; document.head.appendChild(link); } function renderLibraryTabs(active) { return ""; } function bindLibraryTabs() {} function formatYouTubeDuration(value) { const seconds = Number(value); return Number.isFinite(seconds) && seconds > 0 ? formatPlaybackTime(seconds) : ""; } function formatByteSize(value) { let bytes = Number(value) || 0; if (bytes < 1024) return `${bytes} B`; const units = ["KB", "MB", "GB", "TB"]; let unit = -1; do { bytes /= 1024; unit += 1; } while (bytes >= 1024 && unit < units.length - 1); return `${bytes.toFixed(bytes >= 10 ? 1 : 2)} ${units[unit]}`; } async function showYouTubeLibrary() { clearScanPolling(); resetLibraryContext(); ensureYouTubeLibraryStyles(); youtubeItemRegistry.clear(); breadcrumb.innerHTML = `Live  ›  Tube`; toolbar.innerHTML = ""; installTopNav("tube"); content.innerHTML = ` ${renderLibraryTabs("youtube")}

YouTube

Search through the Kronic resolver. Videos you finish streaming are retained in the local watched-video cache.
Loading cache...

Background Cache

Video → Tube cache · Audio → Music library
Loading jobs…
Loading watched videos...
`; bindLibraryTabs(); document.getElementById("youtubeSearchForm").addEventListener("submit", async event => { event.preventDefault(); const query = document.getElementById("youtubeSearchInput").value.trim(); if (!query) return; await searchYouTube(query); }); await Promise.allSettled([ loadYouTubeHistory(), loadYouTubeCacheStatus(), loadCacheJobs(), ]); clearInterval(cacheJobPollTimer); cacheJobPollTimer = setInterval(loadCacheJobs, 1500); } async function loadYouTubeCacheStatus() { const target = document.getElementById("youtubeCacheStatus"); if (!target) return; try { const state = await api("/api/youtube/cache/status"); const maxText = state.max_gb > 0 ? `${state.max_gb} GB` : `${state.max_items} items`; target.textContent = `${state.items} cached · ${formatByteSize(state.total_bytes)} / ${maxText}`; } catch (error) { target.textContent = `Cache unavailable: ${error.message}`; } } async function loadYouTubeHistory() { const target = document.getElementById("youtubeHistoryArea"); if (!target) return; try { const data = await api("/api/youtube/history?limit=60"); const items = data.items || []; const continueItems = items.filter(item => !item.completed && Number(item.position_seconds || 0) >= 30); const recentItems = items.slice(0, 24); target.innerHTML = ` ${continueItems.length ? `
Continue Watching ${continueItems.length} items
${continueItems.map(item => youtubeCardHtml(item, true)).join("")}
` : ""} ${recentItems.length ? `
Recently Watched ${recentItems.length} items
${recentItems.map(item => youtubeCardHtml(item, true)).join("")}
` : `
No YouTube watch history yet.
`} `; registerYouTubeItems(items); bindYouTubeWatchButtons(); } catch (error) { target.innerHTML = `
${escapeHtml(error.message)}
`; } } async function searchYouTube(query, existingItems=null) { const target = document.getElementById("youtubeSearchArea"); if (!target) return; target.innerHTML = `
Search Results
Searching...
`; try { const data = existingItems === null ? await api(`/api/youtube/search?q=${encodeURIComponent(query)}&limit=24`) : {items:existingItems}; const items = data.items || []; registerYouTubeItems(items); target.innerHTML = `
Search Results ${items.length} result${items.length === 1 ? "" : "s"}
${items.map(item => youtubeCardHtml(item, false)).join("") || `
No results.
`}
`; bindYouTubeWatchButtons(); } catch (error) { target.innerHTML = `
${escapeHtml(error.message)}
`; } } function registerYouTubeItems(items) { for (const item of items || []) { const id = item.id || item.video_id; if (!id) continue; youtubeItemRegistry.set(String(id), { id: String(id), title: item.title || id, artist: item.artist || item.channel_name || "", thumbnail: item.thumbnail || item.thumbnail_url || "", duration: item.duration ?? item.duration_seconds ?? null, cached: Boolean(item.cached), position_seconds: Number(item.position_seconds || 0), completed: Boolean(item.completed), }); } } function youtubeCardHtml(item, historyMode=false) { const id = String(item.id || item.video_id || ""); const title = item.title || id; const channel = item.artist || item.channel_name || ""; const thumbnail = item.thumbnail || item.thumbnail_url || ""; const duration = item.duration ?? item.duration_seconds; const position = Number(item.position_seconds || 0); const total = Number(duration || 0); const progressPercent = total > 0 ? Math.max(0, Math.min(100, position * 100 / total)) : 0; const cached = Boolean(item.cached); return `
${escapeHtml(title)}
${escapeHtml(channel)}
${cached ? `Cached` : ""} ${historyMode && position >= 30 && !item.completed ? `Resume ${escapeHtml(formatPlaybackTime(position))}` : ""} ${historyMode && item.completed ? `Watched` : ""}
${item.is_live ? `` : ''}
`; } async function queueYouTubeCache(item, mode){ if(!item)return; const label=mode==="music" ?"Save as Music" :(item.is_live?"Record Live":"Cache Video"); try{ const job=await api("/api/youtube/cache-job",{ method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ video_id:item.id, mode, title:item.title, artist:item.artist, thumbnail:item.thumbnail, duration:item.duration, }), }); console.debug(label,"queued",job); await loadCacheJobs(); }catch(error){ alert(`${label} failed: ${error.message}`); } } async function cacheJobAction(jobId,action){ try{ await api(`/api/cache/jobs/${encodeURIComponent(jobId)}/${action}`,{ method:"POST", headers:{"Content-Type":"application/json"}, body:"{}", }); await loadCacheJobs(); }catch(error){ alert(`Cache job ${action} failed: ${error.message}`); } } async function clearCacheJobs(statuses){ try{ await api("/api/cache/jobs/clear",{ method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({statuses}), }); await loadCacheJobs(); }catch(error){ alert(`Could not clear cache jobs: ${error.message}`); } } async function loadCacheJobs(){ const target=document.getElementById("cacheJobsArea"); if(!target)return; try{ const data=await api("/api/cache/jobs?limit=50"); const jobs=data.jobs||[]; const toolbar=`
`; if(!jobs.length){ target.innerHTML=toolbar+`
No cache jobs.
`; }else{ target.innerHTML=toolbar+jobs.map(job=>{ const title=job.title||job.video_id; const live=Boolean(Number(job.is_live||0)); const mode=job.mode==="music" ?"Music audio" :(live?"Live recording":"Video"); const progress=Math.max(0,Math.min(100,Number(job.progress||0))); let actions=""; if(job.status==="queued"||job.status==="running"){ actions=``; }else if(job.status==="failed"||job.status==="cancelled"){ actions=` `; }else if(job.status==="complete"){ actions=``; } const progressDisplay=(live&&job.status==="running") ?`
LIVE
` :`
${Math.round(progress)}%`; return `
${escapeHtml(title)} ${escapeHtml(mode)} · ${escapeHtml(job.status)} ${job.error ?`${escapeHtml(job.error)}` :`${escapeHtml(job.message||"")}`}
${progressDisplay}
${actions}
`; }).join(""); } target.querySelectorAll("[data-cache-job]").forEach(button=>{ button.onclick=()=>cacheJobAction( button.dataset.cacheJob, button.dataset.cacheAction ); }); target.querySelectorAll("[data-cache-clear]").forEach(button=>{ button.onclick=()=>clearCacheJobs( String(button.dataset.cacheClear||"") .split(",") .filter(Boolean) ); }); loadYouTubeCacheStatus().catch(()=>{}); }catch(error){ target.innerHTML=`
${escapeHtml(error.message)}
`; } } function bindYouTubeWatchButtons() { document.querySelectorAll("[data-youtube-watch]").forEach(button => { button.addEventListener("click", () => { const item = youtubeItemRegistry.get(String(button.dataset.youtubeWatch)); if (item) openYouTubePlayer(item); }); }); document.querySelectorAll("[data-youtube-cache-video]").forEach(button=>{ button.onclick=event=>{ event.stopPropagation(); queueYouTubeCache( youtubeItemRegistry.get(String(button.dataset.youtubeCacheVideo)), "video" ); }; }); document.querySelectorAll('[data-youtube-schedule]').forEach(button=>{ button.onclick=event=>{ event.stopPropagation(); const item=youtubeItemRegistry.get(String(button.dataset.youtubeSchedule)); if(item) openRecordingScheduler('youtube',String(item.id),item.title||'YouTube Live'); }; }); document.querySelectorAll("[data-youtube-cache-music]").forEach(button=>{ button.onclick=event=>{ event.stopPropagation(); queueYouTubeCache( youtubeItemRegistry.get(String(button.dataset.youtubeCacheMusic)), "music" ); }; }); } function ensureYouTubePlayerOverlay() { if (youtubePlayerOverlay) return; youtubePlayerOverlay = document.createElement("div"); youtubePlayerOverlay.id = "youtubePlayerOverlay"; youtubePlayerOverlay.className = "youtube-player-overlay"; youtubePlayerOverlay.setAttribute("aria-hidden", "true"); youtubePlayerOverlay.innerHTML = `
YouTube
`; document.body.appendChild(youtubePlayerOverlay); installMobileVideoBack(document.getElementById("youtubePlayerWindow"), () => closeYouTubePlayer()); youtubeVideoElement = document.getElementById("youtubeVideoElement"); document.getElementById("youtubePlayerClose").onclick = closeYouTubePlayer; document.getElementById("youtubePlayerCacheVideo").onclick = () => queueYouTubeCache(youtubeActiveItem, "video"); document.getElementById("youtubePlayerSaveMusic").onclick = () => queueYouTubeCache(youtubeActiveItem, "music"); const tubeWindow = document.getElementById("youtubePlayerWindow"); const tubeHeader = tubeWindow.querySelector(".youtube-player-header"); const tubeMinimize = document.getElementById("youtubePlayerMinimize"); let tubeMinimized = false; let tubeRestore = null; let tubeDrag = null; function tubeGeometry(){ const r=tubeWindow.getBoundingClientRect(); return {left:r.left,top:r.top,width:r.width,height:r.height}; } function placeTube(g){ if(!g||window.innerWidth<=760)return; const width=Math.max(360,Math.min(g.width,window.innerWidth-12)); const height=Math.max(220,Math.min(g.height,window.innerHeight-12)); tubeWindow.style.left=`${Math.max(0,Math.min(g.left,window.innerWidth-80))}px`; tubeWindow.style.top=`${Math.max(0,Math.min(g.top,window.innerHeight-50))}px`; tubeWindow.style.width=`${width}px`; tubeWindow.style.height=`${height}px`; tubeWindow.classList.add("youtube-floating-positioned"); } tubeMinimize.onclick=()=>{ if(!tubeMinimized){ tubeRestore=tubeGeometry(); tubeMinimized=true; tubeWindow.classList.add("youtube-player-minimized"); tubeMinimize.textContent="Restore"; if(window.innerWidth>760){ const width=Math.min(520,Math.max(320,tubeRestore.width||420)); tubeWindow.style.width=`${width}px`; tubeWindow.style.height=""; tubeWindow.style.left=`${Math.max(8,window.innerWidth-width-18)}px`; tubeWindow.style.top=`${Math.max(8,window.innerHeight-66)}px`; tubeWindow.classList.add("youtube-floating-positioned"); } }else{ tubeMinimized=false; tubeWindow.classList.remove("youtube-player-minimized"); tubeMinimize.textContent="Minimize"; if(tubeRestore)placeTube(tubeRestore); } }; document.getElementById("youtubePlayerFullscreen").onclick = async () => { try { if (document.fullscreenElement === tubeWindow) await document.exitFullscreen(); else { if(tubeMinimized) tubeMinimize.click(); await tubeWindow.requestFullscreen(); } } catch {} }; tubeHeader.addEventListener("pointerdown",event=>{ if(window.innerWidth<=760||tubeMinimized||document.fullscreenElement===tubeWindow)return; if(event.button!==0||event.target.closest("button,input,select,a,video"))return; const r=tubeWindow.getBoundingClientRect(); tubeDrag={id:event.pointerId,x:event.clientX,y:event.clientY,left:r.left,top:r.top,width:r.width}; tubeHeader.setPointerCapture?.(event.pointerId); event.preventDefault(); }); tubeHeader.addEventListener("pointermove",event=>{ if(!tubeDrag||tubeDrag.id!==event.pointerId)return; const left=Math.max(0,Math.min(window.innerWidth-80,tubeDrag.left+event.clientX-tubeDrag.x)); const top=Math.max(0,Math.min(window.innerHeight-50,tubeDrag.top+event.clientY-tubeDrag.y)); tubeWindow.style.left=`${left}px`; tubeWindow.style.top=`${top}px`; tubeWindow.classList.add("youtube-floating-positioned"); }); const stopTubeDrag=()=>{ if(!tubeDrag)return; try{tubeHeader.releasePointerCapture?.(tubeDrag.id);}catch{} tubeDrag=null; }; tubeHeader.addEventListener("pointerup",stopTubeDrag); tubeHeader.addEventListener("pointercancel",stopTubeDrag); youtubePlayerOverlay.addEventListener("click", event => { if (event.target === youtubePlayerOverlay) event.stopPropagation(); }); youtubeVideoElement.addEventListener("play", startYouTubeProgressTimer); youtubeVideoElement.addEventListener("playing", () => clearTimeout(youtubeCacheFallbackTimer)); youtubeVideoElement.addEventListener("pause", saveYouTubeProgress); youtubeVideoElement.addEventListener("ended", async () => { stopYouTubeProgressTimer(); await saveYouTubeProgress(true); }); youtubeVideoElement.addEventListener("loadedmetadata", () => { if ((!youtubeKnownDuration || youtubeKnownDuration <= 0) && Number.isFinite(youtubeVideoElement.duration) && youtubeVideoElement.duration > 0) { youtubeKnownDuration = youtubeVideoElement.duration; } if (youtubePendingClientSeek !== null) { try { youtubeVideoElement.currentTime = youtubePendingClientSeek; } catch {} youtubePendingClientSeek = null; } }); } async function openYouTubePlayer(item, options={}) { ensureYouTubePlayerOverlay(); await closeYouTubePlayer(false); youtubeActiveItem = item; const cacheButton=document.getElementById("youtubePlayerCacheVideo"); if(cacheButton){ cacheButton.textContent=item?.is_live ? "Record Live" : "Cache Video"; } youtubeKnownDuration = Number(item.duration) || null; youtubePlaybackBaseOffset = 0; youtubePendingClientSeek = null; document.getElementById("youtubePlayerTitle").textContent = item.title || "YouTube"; youtubePlayerOverlay.classList.add("active"); youtubePlayerOverlay.setAttribute("aria-hidden", "false"); document.body.classList.add("player-open"); const tubeWindow=document.getElementById("youtubePlayerWindow"); if(tubeWindow.classList.contains("youtube-player-minimized")){ document.getElementById("youtubePlayerMinimize")?.click(); } if(window.innerWidth>760&&!tubeWindow.classList.contains("youtube-floating-positioned")){ requestAnimationFrame(()=>{ const width=Math.min(900,window.innerWidth-32); const height=Math.min(560,window.innerHeight-32); tubeWindow.style.width=`${width}px`; tubeWindow.style.height=`${height}px`; tubeWindow.style.left=`${Math.max(16,(window.innerWidth-width)/2)}px`; tubeWindow.style.top=`${Math.max(16,(window.innerHeight-height)/2)}px`; tubeWindow.classList.add("youtube-floating-positioned"); }); } try { await api("/api/youtube/watch", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ video_id: item.id, title: item.title, channel_name: item.artist, thumbnail_url: item.thumbnail, duration_seconds: item.duration, }), }); } catch (error) { console.warn("Could not record YouTube watch:", error); } let progress = {position_seconds: 0, completed: false, seek_mode: "server"}; try { progress = await api(`/api/youtube/progress/${encodeURIComponent(item.id)}`); } catch {} youtubeSeekMode = progress.seek_mode || "server"; youtubeKnownDuration = Number(progress.duration_seconds) || youtubeKnownDuration; const saved = Number(progress.position_seconds) || 0; const duration = Number(progress.duration_seconds || youtubeKnownDuration) || 0; let start = Number(options.startPosition) || 0; let offer = !options.cast && !progress.completed && saved >= 30; if (duration > 0 && (duration - saved <= 300 || saved / duration >= 0.95)) offer = false; if (offer) { const resume = window.confirm(`Resume "${item.title}" from ${formatPlaybackTime(saved)}?\n\nOK = Resume\nCancel = Start Over`); if (resume) start = saved; else { try { await api(`/api/youtube/progress/${encodeURIComponent(item.id)}`, {method: "DELETE"}); } catch {} } } if (youtubeSeekMode === "client") { youtubeVideoElement.src = roomMediaUrl(`/api/youtube/video/${encodeURIComponent(item.id)}`); if (start > 0) youtubePendingClientSeek = start; } else { youtubePlaybackBaseOffset = start; youtubeVideoElement.src = roomMediaUrl(`/api/youtube/video/${encodeURIComponent(item.id)}${start > 0 ? `?start=${encodeURIComponent(start)}` : ""}`); } youtubeVideoElement.load(); armYouTubeCacheFallback(item.id); youtubeVideoElement.play().catch(error => console.debug("YouTube autoplay delayed or blocked", error)); } // A cached YouTube MP4 can contain fragmented data from an earlier live mux. // If the cached-file HTTP path never becomes playable, request a fresh mux for // THIS browser without deleting or modifying the existing cache. let youtubeCacheFallbackTimer=null; let youtubeCacheFallbackVideoId=null; function armYouTubeCacheFallback(videoId){ clearTimeout(youtubeCacheFallbackTimer); youtubeCacheFallbackVideoId=String(videoId); if(youtubeSeekMode!=='client')return; youtubeCacheFallbackTimer=setTimeout(()=>{ if(!youtubeActiveItem || String(youtubeActiveItem.id)!==youtubeCacheFallbackVideoId || !youtubeVideoElement || youtubeVideoElement.readyState>=3) return; console.warn('[Kronic Media] Cached YouTube stream stalled; retrying uncached mux',videoId); const element=youtubeVideoElement; const wasPaused=element.paused; const lastPosition=Number(element.currentTime)||0; element.src=roomMediaUrl(`/api/youtube/video/${encodeURIComponent(videoId)}?uncached=1`); youtubeSeekMode='server'; youtubePlaybackBaseOffset=0; youtubePendingClientSeek=lastPosition > 0 ? lastPosition : null; element.load(); if(!wasPaused || lastPosition===0)element.play().catch(err=>console.warn('[Kronic Media] Uncached retry autoplay blocked',err)); },11000); } function getYouTubeAbsolutePosition() { const local = Number(youtubeVideoElement?.currentTime) || 0; return youtubeSeekMode === "server" ? youtubePlaybackBaseOffset + local : local; } function startYouTubeProgressTimer() { stopYouTubeProgressTimer(); youtubeProgressTimer = setInterval(saveYouTubeProgress, 10000); } function stopYouTubeProgressTimer() { if (youtubeProgressTimer) { clearInterval(youtubeProgressTimer); youtubeProgressTimer = null; } } async function saveYouTubeProgress(forceCompleted=false) { if (!youtubeActiveItem || !youtubeVideoElement) return; const position = getYouTubeAbsolutePosition(); if (position < 2 && !forceCompleted) return; let duration = youtubeKnownDuration; if ((!duration || duration <= 0) && Number.isFinite(youtubeVideoElement.duration) && youtubeVideoElement.duration > 0) duration = youtubeVideoElement.duration; const completed = forceCompleted || Boolean(duration && duration > 0 && ((duration - position) <= 300 || position / duration >= 0.95)); try { await api(`/api/youtube/progress/${encodeURIComponent(youtubeActiveItem.id)}`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ position_seconds: completed && duration ? duration : position, duration_seconds: duration, completed, }), }); } catch (error) { console.warn("Could not save YouTube playback progress:", error); } } async function closeYouTubePlayer(save=true) { if (!youtubePlayerOverlay || !youtubeVideoElement) return; stopYouTubeProgressTimer(); if (save) await saveYouTubeProgress(false); youtubeVideoElement.pause(); youtubeVideoElement.removeAttribute("src"); youtubeVideoElement.load(); youtubePlayerOverlay.classList.remove("active"); youtubePlayerOverlay.setAttribute("aria-hidden", "true"); document.body.classList.remove("player-open"); youtubeActiveItem = null; youtubePlaybackBaseOffset = 0; youtubeKnownDuration = null; youtubePendingClientSeek = null; } function ensureKronicCastClientId(){ if(kronicCastClientId)return kronicCastClientId; try{ kronicCastClientId=localStorage.getItem("kronicCastClientId"); if(!kronicCastClientId){ kronicCastClientId=(crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`); localStorage.setItem("kronicCastClientId",kronicCastClientId); } }catch{ kronicCastClientId=`${Date.now()}-${Math.random()}`; } return kronicCastClientId; } function kronicCastStatusFromVideo(){ if(!youtubeVideoElement || !youtubeActiveItem)return "stopped"; if(youtubeVideoElement.readyState < 3 && !youtubeVideoElement.paused)return "loading"; if(youtubeVideoElement.ended)return "stopped"; if(youtubeVideoElement.paused)return "paused"; return "playing"; } async function reportKronicCastState(force=false,statusOverride=null){ if(!kronicCastClientId)return; const now=Date.now(); if(!force && now-kronicCastLastStateSent<1000)return; kronicCastLastStateSent=now; const video=youtubeVideoElement; const volume=video ? Math.round((Number(video.volume)||0)*100) : 100; const duration=(youtubeKnownDuration&&Number(youtubeKnownDuration)>0) ? Number(youtubeKnownDuration) : (video&&Number.isFinite(video.duration)&&video.duration>0 ? Number(video.duration) : 0); try{ await api("/api/cast/player-state",{ method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ client_id:kronicCastClientId, status:statusOverride || kronicCastStatusFromVideo(), position:youtubeActiveItem ? getYouTubeAbsolutePosition() : 0, duration, volume, muted:Boolean(video?.muted), video_id:youtubeActiveItem?.id || null, }), }); }catch(error){ console.debug("Kronic Cast state report failed",error); } } async function handleKronicCastCommand(message){ if(!message?.command)return; const command=message.command; if(command==="play"){ const videoId=String(message.video_id||"").trim(); if(!videoId)return; const item={ id:videoId, title:"YouTube Cast", artist:"", thumbnail:`https://i.ytimg.com/vi/${encodeURIComponent(videoId)}/hqdefault.jpg`, duration:null, }; await openYouTubePlayer(item,{ cast:true, startPosition:Number(message.position)||0, }); await reportKronicCastState(true); return; } if(command==="pause"){ youtubeVideoElement?.pause(); await reportKronicCastState(true,"paused"); return; } if(command==="resume"){ if(youtubeVideoElement){ try{await youtubeVideoElement.play();}catch{} } await reportKronicCastState(true); return; } if(command==="seek"){ if(!youtubeActiveItem || !youtubeVideoElement)return; const target=Math.max(0,Number(message.position)||0); // Client-seekable media can seek in place. Server-seek streams (and // live/remux paths) are reopened at the requested source position. if(youtubeSeekMode==="client"){ try{ youtubeVideoElement.currentTime=target; await youtubeVideoElement.play(); }catch{} }else{ const item={...youtubeActiveItem}; await openYouTubePlayer(item,{cast:true,startPosition:target}); } await reportKronicCastState(true,"loading"); return; } if(command==="volume"){ if(youtubeVideoElement){ youtubeVideoElement.volume=Math.max(0,Math.min(1,(Number(message.volume)||0)/100)); } await reportKronicCastState(true); return; } if(command==="stop"){ await closeYouTubePlayer(false); await reportKronicCastState(true,"stopped"); } } async function kronicCastLoop(){ if(kronicCastRunning)return; kronicCastRunning=true; ensureKronicCastClientId(); while(kronicCastRunning){ try{ const response=await api( `/api/cast/command?client_id=${encodeURIComponent(kronicCastClientId)}&after=${encodeURIComponent(kronicCastSeq)}&timeout=20` ); if(Number(response?.seq)>kronicCastSeq){ kronicCastSeq=Number(response.seq); } if(response?.active && response?.command){ await handleKronicCastCommand(response); }else if(response?.standby){ await new Promise(resolve=>setTimeout(resolve,2000)); } }catch(error){ console.debug("Kronic Cast long-poll reconnect",error); await new Promise(resolve=>setTimeout(resolve,1500)); } } } function bindKronicCastPlayerState(){ ensureYouTubePlayerOverlay(); const video=youtubeVideoElement; if(!video)return; ["play","pause","waiting","seeking","seeked","loadedmetadata","volumechange"].forEach(name=>{ video.addEventListener(name,()=>reportKronicCastState(true)); }); video.addEventListener("ended",()=>reportKronicCastState(true,"stopped")); clearInterval(kronicCastStateTimer); kronicCastStateTimer=setInterval(()=>{ if(youtubeActiveItem)reportKronicCastState(false); },5000); } function startKronicCastReceiverBridge(){ ensureKronicCastClientId(); bindKronicCastPlayerState(); kronicCastLoop(); } // ============================================================ // IPTV / CURATED M3U SOURCES // ============================================================ function ensureIptvStyles() { if (document.getElementById("iptvStyles")) return; const link = document.createElement("link"); link.id = "iptvStyles"; link.rel = "stylesheet"; link.href = "/CSS/iptv.css"; document.head.appendChild(link); } async function getIptvOverview(force=false) { if (!force && iptvOverviewCache) return iptvOverviewCache; iptvOverviewCache = await api("/api/iptv/overview"); return iptvOverviewCache; } function iptvCollectionOptions(collections, selectedId=null) { const chosen = selectedId == null ? "" : String(selectedId); return ` ${(collections || []).map(item => ` `).join("")} `; } let iptvViewMode = "library"; async function showIptvLibrary(mode="library") { clearScanPolling(); resetLibraryContext(); ensureIptvStyles(); iptvViewMode = mode === "settings" ? "settings" : "library"; breadcrumb.innerHTML = iptvViewMode === "settings" ? `Live  ›  IPTV  ›  Settings` : `Live  ›  IPTV`; toolbar.innerHTML = ""; installTopNav("iptv"); content.innerHTML = `
Loading IPTV…
`; try { const overview = await getIptvOverview(true); if (iptvViewMode === "settings") renderIptvSettingsPage(overview); else renderIptvChannelPage(overview); } catch (error) { showError(error); } } function renderIptvChannelPage(overview) { const channels = overview.channels || []; content.innerHTML = `

IPTV

Live channels

Channels

${iptvSelectedChannelsHtml(channels)}
`; bindIptvChannelOnly(); } function renderIptvSettingsPage(overview) { const collections = overview.collections || []; const sources = overview.sources || []; content.innerHTML = `

IPTV Settings

Add playlists, direct channels, sharing and channel selections.

Playlists

${collections.length ? collections.map(c => `
${escapeHtml(c.name)}${c.channel_count || 0} selected channels
`).join("") : `
No named playlists yet.
`}

1. Upload M3U

2. M3U URL

3. Direct Channel URL

Sources

Choose exactly which channels from each list appear in IPTV.
${sources.length ? sources.map(source => iptvSourceRow(source, collections)).join("") : `
No IPTV sources yet.
`}
`; document.getElementById("iptvSettingsWatch")?.addEventListener("click", () => showIptvLibrary("library")); bindIptvPage(overview); } function bindIptvChannelOnly() { const search = document.getElementById("iptvChannelSearch"); if (search) search.oninput = () => filterIptvChannels(search.value); bindIptvSnapshotFallbacks(); bindIptvChannelActions(); } function iptvSourceRow(source, collections) { const error = source.last_error ? `
${escapeHtml(source.last_error)}
` : ""; const kind = source.source_type === "upload" ? "Uploaded M3U" : (source.source_type === "url" ? "Remote M3U" : "Direct channel"); return `
${escapeHtml(source.name)} ${escapeHtml(kind)} · ${source.selected_count || 0}/${source.channel_count || 0} selected ${error}
${source.source_type !== "channel" ? `` : ""}
`; } function iptvSelectedChannelsHtml(channels) { if (!channels.length) return `
No channels selected yet. Add a source, then choose the channels you want.
`; const groups = new Map(); for (const channel of channels) { const collection = channel.display_collection_name || channel.collection_name || (channel.is_shared ? "Shared Channels" : "My Channels"); const group = channel.group_name || channel.source_name || "Channels"; const key = `${collection}\u0000${group}`; if (!groups.has(key)) groups.set(key, {collection, group, channels:[]}); groups.get(key).channels.push(channel); } return [...groups.values()].map(section => `
${escapeHtml(section.collection)}${escapeHtml(section.group)}
${section.channels.length} channel${section.channels.length === 1 ? "" : "s"}
${section.channels.map(channel => iptvChannelCard(channel)).join("")}
`).join(""); } function iptvChannelCard(channel) { const fallback = channel.tvg_logo ? escapeAttribute(channel.tvg_logo) : ""; const snapshot = roomMediaUrl(`/api/iptv/channels/${channel.id}/snapshot`); const fallbackAttr = fallback ? `data-fallback="${fallback}"` : ""; return `
LIVE
${escapeHtml(channel.name)}${Number(channel.is_shared) ? ` SHARED` : ""} ${escapeHtml(channel.group_name || channel.source_name || "")} ${channel.tvg_id ? `${escapeHtml(channel.tvg_id)}` : ""}
`; } function bindIptvPage(overview) { document.getElementById("iptvCollectionForm")?.addEventListener("submit", async event => { event.preventDefault(); const name = document.getElementById("iptvCollectionName").value.trim(); if (!name) return; try { await api("/api/iptv/collections", { method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ name, is_public:document.getElementById("iptvCollectionPublic")?.checked || false, }), }); iptvOverviewCache = null; await showIptvLibrary("settings"); document.getElementById("iptvManagePanel").hidden = false; } catch (error) { alert(error.message); } }); document.getElementById("iptvUploadForm")?.addEventListener("submit", async event => { event.preventDefault(); const file = document.getElementById("iptvUploadFile").files?.[0]; if (!file) return; const text = await file.text(); await addIptvSource({ name: document.getElementById("iptvUploadName").value.trim(), source_type:"upload", source_payload:text, collection_id: document.getElementById("iptvUploadCollection").value || null, is_public:document.getElementById("iptvUploadPublic")?.checked || false, }); }); document.getElementById("iptvUrlForm")?.addEventListener("submit", async event => { event.preventDefault(); await addIptvSource({ name: document.getElementById("iptvUrlName").value.trim(), source_type:"url", source_value: document.getElementById("iptvUrlValue").value.trim(), collection_id: document.getElementById("iptvUrlCollection").value || null, is_public:document.getElementById("iptvUrlPublic")?.checked || false, }); }); document.getElementById("iptvChannelForm")?.addEventListener("submit", async event => { event.preventDefault(); const name = document.getElementById("iptvChannelName").value.trim(); await addIptvSource({ name, channel_name:name, source_type:"channel", source_value: document.getElementById("iptvChannelUrl").value.trim(), collection_id: document.getElementById("iptvChannelCollection").value || null, is_public:document.getElementById("iptvChannelPublic")?.checked || false, }); }); document.querySelectorAll("[data-iptv-choose]").forEach(button => { button.onclick = () => showIptvSourceChooser(Number(button.dataset.iptvChoose)); }); document.querySelectorAll("[data-iptv-refresh]").forEach(button => { button.onclick = async () => { button.disabled = true; button.textContent = "Refreshing…"; try { await api(`/api/iptv/sources/${button.dataset.iptvRefresh}/refresh`, {method:"POST"}); iptvOverviewCache = null; await showIptvLibrary("settings"); document.getElementById("iptvManagePanel").hidden = false; } catch (error) { alert(error.message); button.disabled = false; button.textContent = "Refresh"; } }; }); document.querySelectorAll("[data-iptv-delete-source]").forEach(button => { button.onclick = async () => { if (!confirm("Delete this IPTV source and its imported channels?")) return; await api(`/api/iptv/sources/${button.dataset.iptvDeleteSource}`, {method:"DELETE"}); iptvOverviewCache = null; await showIptvLibrary("settings"); document.getElementById("iptvManagePanel").hidden = false; }; }); document.querySelectorAll("[data-iptv-delete-collection]").forEach(button => { button.onclick = async () => { if (!confirm("Delete this playlist? Sources are kept and moved back to My Channels.")) return; await api(`/api/iptv/collections/${button.dataset.iptvDeleteCollection}`, {method:"DELETE"}); iptvOverviewCache = null; await showIptvLibrary("settings"); document.getElementById("iptvManagePanel").hidden = false; }; }); document.querySelectorAll("[data-iptv-collection-public]").forEach(box => { box.onchange = async () => { box.disabled = true; try { await api(`/api/iptv/collections/${box.dataset.iptvCollectionPublic}/public`, { method:"PATCH", headers:{"Content-Type":"application/json"}, body:JSON.stringify({is_public:box.checked}), }); iptvOverviewCache = null; } catch (error) { box.checked = !box.checked; alert(error.message); } finally { box.disabled = false; } }; }); document.querySelectorAll("[data-iptv-source-public]").forEach(box => { box.onchange = async () => { box.disabled = true; try { await api(`/api/iptv/sources/${box.dataset.iptvSourcePublic}/public`, { method:"PATCH", headers:{"Content-Type":"application/json"}, body:JSON.stringify({is_public:box.checked}), }); iptvOverviewCache = null; } catch (error) { box.checked = !box.checked; alert(error.message); } finally { box.disabled = false; } }; }); document.querySelectorAll("[data-iptv-source-collection]").forEach(select => { select.onchange = async () => { await api(`/api/iptv/sources/${select.dataset.iptvSourceCollection}/collection`, { method:"PATCH", headers:{"Content-Type":"application/json"}, body:JSON.stringify({collection_id:select.value || null}), }); iptvOverviewCache = null; }; }); bindIptvChannelActions(); document.getElementById("iptvChannelSearch")?.addEventListener("input", event => { const query = event.target.value.trim().toLowerCase(); document.querySelectorAll("[data-iptv-channel-card]").forEach(card => { card.hidden = !!query && !String(card.dataset.search || "").includes(query); }); document.querySelectorAll("[data-iptv-group]").forEach(group => { const visible = [...group.querySelectorAll("[data-iptv-channel-card]")].some(card => !card.hidden); group.hidden = !visible; }); }); } async function addIptvSource(payload) { try { const source = await api("/api/iptv/sources", { method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload), }); iptvOverviewCache = null; if (payload.source_type === "channel") { await showIptvLibrary("settings"); } else { await showIptvSourceChooser(Number(source.id)); } } catch (error) { alert(error.message); } } async function showIptvSourceChooser(sourceId) { ensureIptvStyles(); breadcrumb.innerHTML = `Libraries  ›  IPTV  ›  Choose Channels`; toolbar.innerHTML = ``; document.getElementById("iptvChooserBack").onclick = () => showIptvLibrary("settings"); content.innerHTML = `
Loading channels…
`; try { const data = await api(`/api/iptv/sources/${sourceId}/channels`); const source = data.source; const channels = data.channels || []; content.innerHTML = `

${escapeHtml(source?.name || "IPTV source")}

Check only the channels you want in your IPTV channel list.
0 / ${channels.length} selected
${channels.map(channel => ` `).join("") || `
No channels were found in this source.
`}
`; const updateCount = () => { const count = document.querySelectorAll("[data-iptv-choice]:checked").length; const target = document.getElementById("iptvCheckedCount"); if (target) target.textContent = String(count); }; document.querySelectorAll("[data-iptv-choice]").forEach(box => box.onchange = updateCount); updateCount(); document.getElementById("iptvChooserSearch").oninput = event => { const query = event.target.value.trim().toLowerCase(); document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { row.hidden = !!query && !String(row.dataset.search || "").includes(query); }); }; document.getElementById("iptvSelectVisible").onclick = () => { document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { if (!row.hidden) row.querySelector("[data-iptv-choice]").checked = true; }); updateCount(); }; document.getElementById("iptvClearVisible").onclick = () => { document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { if (!row.hidden) row.querySelector("[data-iptv-choice]").checked = false; }); updateCount(); }; document.getElementById("iptvSaveSelection").onclick = async () => { const ids = [...document.querySelectorAll("[data-iptv-choice]:checked")].map(box => Number(box.dataset.iptvChoice)); await api(`/api/iptv/sources/${sourceId}/selection`, { method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({channel_ids:ids}), }); iptvOverviewCache = null; await showIptvLibrary("settings"); }; } catch (error) { showError(error); } } function bindIptvSnapshotFallbacks() { document.querySelectorAll(".iptv-channel-snapshot").forEach(img => { img.addEventListener("error", () => { const fallback = img.dataset.fallback; if (fallback && img.src !== fallback) { img.dataset.fallback = ""; img.src = fallback; return; } img.closest(".iptv-channel-visual")?.classList.add("snapshot-missing"); img.remove(); }, {once:false}); }); } let playerFloatingInstalled = false; function ensurePlayerMinimizeButton() { if (playerMinimizeButton?.isConnected) return playerMinimizeButton; const header=playerTitle?.parentElement||playerWindow?.firstElementChild; if (!header) return null; playerMinimizeButton=document.createElement("button"); playerMinimizeButton.type="button"; playerMinimizeButton.id="playerMinimizeButton"; playerMinimizeButton.onclick=e=>{e.stopPropagation();togglePlayerMinimized();}; if (playerFullscreenButton?.parentElement===header) header.insertBefore(playerMinimizeButton,playerFullscreenButton); else if (playerCloseButton?.parentElement===header) header.insertBefore(playerMinimizeButton,playerCloseButton); else header.appendChild(playerMinimizeButton); updateMinimizeButton(); return playerMinimizeButton; } function installPlayerResizeHandles() { if (!playerWindow || playerResizeHandles.length) return; for (const d of ["n","ne","e","se","s","sw","w","nw"]) { const h=document.createElement("div"); h.className=`player-resize-handle player-resize-${d}`; h.dataset.resizeDirection=d; playerWindow.appendChild(h); playerResizeHandles.push(h); let rs=null; h.addEventListener("pointerdown",e=>{ if(window.innerWidth<=760||playerMinimized||document.fullscreenElement===playerWindow||e.button!==0)return; const r=playerWindow.getBoundingClientRect(); rs={id:e.pointerId,x:e.clientX,y:e.clientY,left:r.left,top:r.top,width:r.width,height:r.height}; h.setPointerCapture?.(e.pointerId); e.preventDefault(); e.stopPropagation(); }); h.addEventListener("pointermove",e=>{ if(!rs||rs.id!==e.pointerId)return; const dx=e.clientX-rs.x,dy=e.clientY-rs.y,minW=360,minH=220; let l=rs.left,t=rs.top,w=rs.width,hh=rs.height; if(d.includes("e"))w=Math.max(minW,rs.width+dx); if(d.includes("s"))hh=Math.max(minH,rs.height+dy); if(d.includes("w")){w=Math.max(minW,rs.width-dx);l=rs.left+(rs.width-w);} if(d.includes("n")){hh=Math.max(minH,rs.height-dy);t=rs.top+(rs.height-hh);} l=Math.max(0,l);t=Math.max(0,t); w=Math.min(w,window.innerWidth-l-4);hh=Math.min(hh,window.innerHeight-t-4); playerWindow.style.left=`${l}px`;playerWindow.style.top=`${t}px`; playerWindow.style.width=`${Math.max(minW,w)}px`;playerWindow.style.height=`${Math.max(minH,hh)}px`; playerWindow.classList.add("floating-player-positioned"); }); const stop=()=>{if(!rs)return;try{h.releasePointerCapture?.(rs.id);}catch{}rs=null;}; h.addEventListener("pointerup",stop);h.addEventListener("pointercancel",stop); } } function setupFloatingPlayer() { if(playerFloatingInstalled||!playerWindow||!playerOverlay)return; playerFloatingInstalled=true; playerOverlay.classList.add("persistent-player-overlay"); playerWindow.classList.add("floating-player-window"); ensurePlayerMinimizeButton();installPlayerResizeHandles(); const handle=playerTitle?.parentElement||playerWindow.firstElementChild; handle?.classList.add("floating-player-handle"); let drag=null; handle?.addEventListener("dblclick",e=>{if(!e.target.closest("button,a,input,select,video"))togglePlayerMinimized();}); handle?.addEventListener("pointerdown",e=>{ if(window.innerWidth<=760||playerMinimized||document.fullscreenElement===playerWindow||e.button!==0)return; if(e.target.closest("button,a,input,select,video,.player-resize-handle"))return; const r=playerWindow.getBoundingClientRect(); Object.assign(playerWindow.style,{width:`${r.width}px`,height:`${r.height}px`,left:`${r.left}px`,top:`${r.top}px`}); playerWindow.classList.add("floating-player-positioned"); drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:r.left,top:r.top,width:r.width}; handle.setPointerCapture?.(e.pointerId);e.preventDefault(); }); handle?.addEventListener("pointermove",e=>{ if(!drag||drag.id!==e.pointerId)return; const l=Math.max(0,Math.min(window.innerWidth-80,drag.left+e.clientX-drag.x)); const t=Math.max(0,Math.min(window.innerHeight-50,drag.top+e.clientY-drag.y)); playerWindow.style.left=`${l}px`;playerWindow.style.top=`${t}px`; }); const stop=()=>{if(!drag)return;try{handle.releasePointerCapture?.(drag.id);}catch{}drag=null;}; handle?.addEventListener("pointerup",stop);handle?.addEventListener("pointercancel",stop); } function prepareFloatingPlayerPosition() { setupFloatingPlayer(); if(!playerWindow||document.fullscreenElement===playerWindow)return; if(window.innerWidth<=760){ playerWindow.classList.remove("floating-player-positioned"); for(const k of ["left","top","width","height"])playerWindow.style.removeProperty(k); return; } if(playerMinimized)restorePlayer(); if(!playerWindow.classList.contains("floating-player-positioned")){ requestAnimationFrame(()=>{ const r=playerWindow.getBoundingClientRect(); const w=Math.min(Math.max(r.width||860,560),window.innerWidth-24); const h=Math.min(Math.max(r.height||540,340),window.innerHeight-24); applyPlayerGeometry({left:(window.innerWidth-w)/2,top:(window.innerHeight-h)/2,width:w,height:h}); }); } } function bindIptvChannelActions() { document.querySelectorAll("[data-iptv-play]").forEach(button => { button.onclick = () => openIptvChannel({ id:Number(button.dataset.iptvPlay), name:button.dataset.iptvTitle || "Live TV", }); }); document.querySelectorAll("[data-iptv-hide]").forEach(button => { button.onclick = async () => { await api(`/api/iptv/channels/${button.dataset.iptvHide}`, { method:"PATCH", headers:{"Content-Type":"application/json"}, body:JSON.stringify({hidden:true}), }); iptvOverviewCache = null; await showIptvLibrary(); }; }); } async function openIptvChannel(channel) { if (!mediaPlayer) return; await saveCurrentPlaybackProgress(); stopPlaybackSaveTimer(); resetPlayerHealth(); mediaPlayer.pause(); mediaPlayer.removeAttribute("src"); mediaPlayer.load(); activeMediaId = null; activeMediaTitle = channel.name; activeIptvChannel = channel; playbackFallbackUsed = false; playbackBaseOffset = 0; playbackKnownDuration = null; pendingClientSeek = null; activePlaybackPlan = null; playerTitle.textContent = `${channel.name} · LIVE`; installMobileVideoBack(playerWindow,()=>closePlayer()); playerOverlay.classList.add("active"); playerOverlay.setAttribute("aria-hidden", "false"); document.body.classList.add("player-open"); playerWindow?.classList.remove("player-minimized"); playerMinimized=false; updateMinimizeButton(); prepareFloatingPlayerPosition(); showPlayerStatus("Connecting to live stream and normalizing it for this browser…"); await beginIptvPlayback(channel, false); } async function beginIptvPlayback(channel, retry=false) { if (!channel || !mediaPlayer) return; if (retry) { mediaPlayer.pause(); mediaPlayer.removeAttribute("src"); mediaPlayer.load(); await new Promise(resolve => setTimeout(resolve, 350)); } activeIptvChannel = channel; showPlayerStatus(retry ? "Reconnecting live stream…" : "Buffering live stream…"); mediaPlayer.src = roomMediaUrl(`/api/iptv/channels/${channel.id}/play?ts=${Date.now()}`); mediaPlayer.load(); // Starting a live stream can leave play() pending for a long time. // Never hold the LiveKit room-event queue hostage to network buffering. mediaPlayer.play().catch(error => console.debug("IPTV play did not start immediately:", error)); } injectYouTubeMetadataStyles(); async function bootMediaServer() { try { mediaAuthContext = await api("/api/auth/media-context"); document.body.dataset.hasMediaAccess = String(!!mediaAuthContext.hasMediaAccess); const rooms = await api('/api/my/assigned-rooms'); const room = (rooms.rooms || []).find(r => String(r.id) === document.body.dataset.roomId); document.body.dataset.roomOwner = String(room?.role === 'owner'); const rename = document.getElementById('mobileRenameRoom'); if (rename) rename.hidden = !(room?.role === 'owner' || mediaAuthContext.isPlatformAdmin); ensureInterfaceRefreshStyles(); installTopNav(); setupVideoPlayer(); setupFloatingPlayer(); setupNavigation(); startKronicCastReceiverBridge(); const accountKey = 'kronic.start-view.v1.' + String(mediaAuthContext?.user?.username || 'guest').toLowerCase(); const startView = localStorage.getItem(accountKey) || 'room'; if (startView === 'libraries' && mediaAuthContext.hasMediaAccess) { await showLibraries(); window.dispatchEvent(new CustomEvent('kronic:preferred-start-view', {detail:{section:'libraries'}})); } else { // The room shell is the default landing screen; defer library fetch until requested. window.dispatchEvent(new CustomEvent('kronic:preferred-start-view', {detail:{section:'room'}})); } } catch (error) { if (content) showError(error); } } bootMediaServer(); function ensureMusicStyles(){ if(document.getElementById("musicLibraryStyles"))return; const link=document.createElement("link"); link.id="musicLibraryStyles"; link.rel="stylesheet"; link.href="/CSS/music.css"; document.head.appendChild(link); } // Move the persistent music player without interrupting audio. Double-click the // cover/title region to re-dock at the bottom. Positions are local per browser. function setupDraggableMusicPlayer(root) { const storageKey = "kronic.music.player.position.v1"; function setPosition(left, top) { const width = root.offsetWidth, height = root.offsetHeight; root.style.left = Math.max(0, Math.min(window.innerWidth - width, left)) + "px"; root.style.top = Math.max(0, Math.min(window.innerHeight - height, top)) + "px"; root.style.right = "auto"; root.style.bottom = "auto"; root.classList.add("music-undocked"); } function dock() { root.classList.remove("music-undocked"); for (const property of ["left", "top", "right", "bottom"]) root.style.removeProperty(property); try { localStorage.removeItem(storageKey); } catch (_) {} } let saved; try { saved = JSON.parse(localStorage.getItem(storageKey) || "null"); } catch (_) {} if (saved && Number.isFinite(saved.left) && Number.isFinite(saved.top)) { requestAnimationFrame(() => setPosition(saved.left, saved.top)); } const handles = [root.querySelector(".music-player-info"), root.querySelector(".music-player-cover")]; let drag = null; for (const handle of handles) { if (!handle) continue; handle.classList.add("music-drag-handle"); handle.title = "Drag to move · Double-click to dock"; handle.addEventListener("dblclick", dock); handle.addEventListener("pointerdown", event => { if (event.button !== 0) return; const rect = root.getBoundingClientRect(); drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: rect.left, top: rect.top }; handle.setPointerCapture(event.pointerId); event.preventDefault(); }); handle.addEventListener("pointermove", event => { if (!drag || drag.id !== event.pointerId) return; setPosition(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y); }); const finish = event => { if (!drag || drag.id !== event.pointerId) return; drag = null; if (root.classList.contains("music-undocked")) { try { localStorage.setItem(storageKey, JSON.stringify({ left: parseFloat(root.style.left), top: parseFloat(root.style.top) })); } catch (_) {} } }; handle.addEventListener("pointerup", finish); handle.addEventListener("pointercancel", finish); } window.addEventListener("resize", () => { if (root.classList.contains("music-undocked")) { setPosition(parseFloat(root.style.left) || 0, parseFloat(root.style.top) || 0); } }); } function ensureMusicPlayer(){ if(musicPlayer?.root?.isConnected)return musicPlayer; const root=document.createElement("div"); root.id="musicPersistentPlayer"; root.className="music-persistent-player"; root.innerHTML=`
Nothing playing
0:00 0:00
`; document.body.appendChild(root); const audio=root.querySelector("#musicAudio"); musicPlayer={root,audio,cover:root.querySelector("#musicPlayerCover"),title:root.querySelector("#musicPlayerTitle"),artist:root.querySelector("#musicPlayerArtist")}; root.querySelector("#musicPrev").onclick=()=>playMusicQueueOffset(-1); root.querySelector("#musicNext").onclick=()=>playMusicQueueOffset(1); root.querySelector("#musicClose").onclick=()=>{audio.pause();audio.removeAttribute("src");audio.load();root.classList.remove("active");musicQueueIndex=-1;}; const touchToggle=root.querySelector("#musicTouchToggle"); const touchSeek=root.querySelector("#musicTouchSeek"); const elapsed=root.querySelector("#musicTouchElapsed"); const duration=root.querySelector("#musicTouchDuration"); const mute=root.querySelector("#musicTouchMute"); const timeText=value=>{if(!Number.isFinite(value))return "0:00";const n=Math.floor(value);return `${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`;}; const sync=()=>{ const length=audio.duration; touchToggle.textContent=audio.paused?"▶":"❚❚"; touchToggle.setAttribute("aria-label",audio.paused?"Play":"Pause"); elapsed.textContent=timeText(audio.currentTime); duration.textContent=timeText(length); if(!touchSeek.matches(":active") && document.activeElement!==touchSeek) touchSeek.value=Number.isFinite(length)&&length>0?String(Math.round(audio.currentTime/length*1000)):"0"; touchSeek.disabled=!(Number.isFinite(length)&&length>0); mute.textContent=audio.muted?"◖×":"◖))"; mute.setAttribute("aria-label",audio.muted?"Unmute":"Mute"); }; root.querySelector("#musicTouchPrev").onclick=()=>playMusicQueueOffset(-1); root.querySelector("#musicTouchNext").onclick=()=>playMusicQueueOffset(1); root.querySelector("#musicTouchClose").onclick=()=>root.querySelector("#musicClose").click(); touchToggle.onclick=()=>{if(audio.paused)audio.play().catch(()=>{});else audio.pause();}; mute.onclick=()=>{audio.muted=!audio.muted;sync();}; touchSeek.addEventListener("input",()=>{if(Number.isFinite(audio.duration)&&audio.duration>0){audio.currentTime=audio.duration*Number(touchSeek.value)/1000;sync();}}); for(const event of ["timeupdate","loadedmetadata","durationchange","play","pause","volumechange","emptied"])audio.addEventListener(event,sync); sync(); audio.addEventListener("ended",()=>playMusicQueueOffset(1)); setupDraggableMusicPlayer(root); return musicPlayer; } function playMusicQueueOffset(delta){ if(!musicQueue.length)return; let next=musicQueueIndex+delta; if(next<0)next=musicQueue.length-1; if(next>=musicQueue.length)next=0; playMusicTrack(musicQueue[next], musicQueue, next); } async function playMusicTrack(track, queue=null, index=null){ const p=ensureMusicPlayer(); if(queue){musicQueue=[...queue];musicQueueIndex=index ?? musicQueue.findIndex(x=>x.id===track.id);} else if(musicQueueIndex<0){musicQueue=[track];musicQueueIndex=0;} p.title.textContent=track.title||"Unknown"; p.artist.textContent=[track.artist,track.album].filter(Boolean).join(" · "); p.cover.src=roomMediaUrl(track.cover_url||""); p.cover.style.visibility=track.cover_url?"visible":"hidden"; p.root.classList.add("active"); p.audio.src=roomMediaUrl(`/api/music/tracks/${encodeURIComponent(track.id)}/audio`); p.audio.load(); p.audio.play().catch(error=>console.debug("Music playback did not start immediately",error)); } function musicTrackCard(track,queue,index){ musicTrackRegistry.set(String(track.id),track); const cover=track.cover_url?``:`
♪
`; return `
${escapeHtml(track.title||"Unknown")} ${escapeHtml(track.artist||"")} ${escapeHtml(track.album||track.list_name||"")}
${track.cached?`Cached`:""}
`; } function bindMusicCards(tracks){ document.querySelectorAll("[data-music-play]").forEach(button=>{ button.onclick=()=>{ const id=Number(button.dataset.musicPlay); const index=tracks.findIndex(item=>Number(item.id)===id); if(index>=0)playMusicTrack(tracks[index],tracks,index); }; }); } async function loadMusicTracks(query=""){ const target=document.getElementById("musicTrackArea"); if(!target)return; target.innerHTML=`
Loading music…
`; try{ const data=await api(`/api/music/overview?limit=2000${query?`&q=${encodeURIComponent(query)}`:""}`); const tracks=data.tracks||[]; musicTrackRegistry.clear(); const groups=new Map(); tracks.forEach(track=>{ const group=track.list_name||track.album||"Music"; if(!groups.has(group))groups.set(group,[]); groups.get(group).push(track); }); target.innerHTML=tracks.length?[...groups.entries()].map(([name,items])=>`

${escapeHtml(name)}

${items.length} track${items.length===1?"":"s"}
${items.map((track,index)=>musicTrackCard(track,tracks,tracks.indexOf(track))).join("")}
`).join(""):`
No music imported yet. Paste a Spotify track, album, playlist, or artist URL above.
`; const status=document.getElementById("musicCacheStatus"); if(status&&data.cache)status.textContent=`${data.cache.items||0} cached · ${formatByteSize(data.cache.total_bytes||0)}`; bindMusicCards(tracks); }catch(error){target.innerHTML=`
${escapeHtml(error.message)}
`;} } async function loadMusicImportJobs(){ const target=document.getElementById("musicImportJobs"); if(!target)return; try{ const data=await api("/api/music/import-jobs"); const jobs=data.jobs||[]; if(!jobs.length){ target.innerHTML=""; return; } target.innerHTML=`
Spotify imports
${jobs.map(job=>`
${escapeHtml(job.query||"Spotify import")}
${escapeHtml(job.status||"")} · ${escapeHtml(job.message||"")}
${job.error?`
${escapeHtml(job.error)}
`:""}
${job.resolved||0} resolved · ${job.inserted||0} new · ${job.updated||0} updated · ${job.repaired||0} metadata repaired
`).join("")} `; const clearButton=document.getElementById("musicImportJobsClear"); if(clearButton){ clearButton.onclick=async()=>{ try{ await api("/api/music/import-jobs/clear",{ method:"POST", headers:{"Content-Type":"application/json"}, body:"{}", }); await loadMusicImportJobs(); }catch(error){ alert(`Could not clear Spotify import jobs: ${error.message}`); } }; } const completedJobs=jobs.filter(job=>job.status==="complete"); if(!musicImportJobsInitialized){ // The first status poll is just establishing current state. // Existing historical completed jobs must NOT trigger a library // reload every 2.5 seconds. completedJobs.forEach(job=>musicImportCompletedSeen.add(String(job.id))); musicImportJobsInitialized=true; }else{ const newlyCompleted=completedJobs.filter( job=>!musicImportCompletedSeen.has(String(job.id)) ); completedJobs.forEach(job=>musicImportCompletedSeen.add(String(job.id))); // Refresh the music library exactly once when an import changes // into complete while this page is open. if(newlyCompleted.length){ await loadMusicTracks( document.getElementById("musicFilterInput")?.value?.trim()||"" ); } } }catch(error){ target.innerHTML=`
${escapeHtml(error.message)}
`; } } async function showMusicLibrary(){ musicImportJobsInitialized=false; clearScanPolling();resetLibraryContext();ensureMusicStyles();ensureMusicPlayer(); breadcrumb.innerHTML=`Libraries  ›  Music`; toolbar.innerHTML=""; installTopNav("home"); content.innerHTML=`

Music

Cached audio files are discovered automatically. Spotify enriches metadata when the match is confident.
Loading cache…
Scan music folder
Add music / Spotify import
`; document.getElementById("musicImportForm").onsubmit=async event=>{ event.preventDefault(); const input=document.getElementById("musicImportInput"); const status=document.getElementById("musicImportStatus"); const url=input.value.trim(); if(!url)return; const button=event.submitter; if(button)button.disabled=true; status.textContent="Queueing Spotify import…"; try{ const job=await api("/api/music/import",{ method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({url}) }); status.textContent=`Spotify import queued (#${job.id}). It will continue in the background.`; input.value=""; try{ await loadMusicImportJobs(); }catch(refreshError){ console.error("Spotify import queued, but job panel refresh failed",refreshError); status.textContent=`Spotify import queued (#${job.id}). Background import is running; status panel refresh failed: ${refreshError.message}`; } }catch(error){ status.textContent=`Import request failed: ${error.message}`; } finally{if(button)button.disabled=false;} }; document.getElementById("musicReconcileButton").onclick=async()=>{ const button=document.getElementById("musicReconcileButton"); button.disabled=true; try{ const result=await api("/api/music/reconcile",{method:"POST"}); document.getElementById("musicImportStatus").textContent=`Folder scan: ${result.checked||0} checked, ${result.added||0} added, ${result.enriched||0} Spotify matches.`; await loadMusicTracks(); }catch(error){ document.getElementById("musicImportStatus").textContent=`Folder scan failed: ${error.message}`; }finally{button.disabled=false;} }; document.getElementById("musicFilterForm").onsubmit=event=>{event.preventDefault();loadMusicTracks(document.getElementById("musicFilterInput").value.trim());}; document.getElementById("musicFilterClear").onclick=()=>{document.getElementById("musicFilterInput").value="";loadMusicTracks();}; await loadMusicTracks(); await loadMusicImportJobs(); clearInterval(musicImportJobPollTimer); musicImportJobPollTimer=setInterval(loadMusicImportJobs,2500); } // Kronic mobile: resize the video panel by touch, without stealing gestures // from the actual HTML5 video controls. Reattached when YouTube is recreated. (function installKronicMobilePlayers(){ const MOBILE = window.matchMedia('(max-width:760px)'); const clamp=(n,lo,hi)=>Math.min(hi,Math.max(lo,n)); function attach(win,kind){ if(!win||win.dataset.mobileReady==='1')return; win.dataset.mobileReady='1'; const header=win.querySelector('.player-header,.youtube-player-header'); if(!header)return; const tools=document.createElement('div'); tools.className='kronic-mobile-player-tools'; tools.innerHTML='◢'; header.appendChild(tools); let pct=95; const key='kronic.mobile.'+kind+'.width.v1'; try{const stored=Number(localStorage.getItem(key));if(stored>=45&&stored<=100)pct=stored;}catch(_){} function update(value,save=true){ pct=clamp(Math.round(value),45,100); win.style.setProperty('--kronic-mobile-player-width',pct+'vw'); const grip=tools.querySelector('.kronic-mobile-resize-grip'); grip.setAttribute('aria-valuenow',String(pct)); if(save)try{localStorage.setItem(key,String(pct));}catch(_){} } update(pct,false); tools.addEventListener('click',event=>{ const op=event.target.closest('[data-mobile-size]')?.dataset.mobileSize; if(!op||!MOBILE.matches)return; update(op==='fit'?100:pct+(op==='plus'?10:-10)); }); const grip=tools.querySelector('.kronic-mobile-resize-grip'); let drag=null; grip.addEventListener('pointerdown',event=>{ if(!MOBILE.matches||document.fullscreenElement||event.button!==0)return; drag={id:event.pointerId,x:event.clientX,pct}; grip.setPointerCapture(event.pointerId);event.preventDefault();event.stopPropagation(); }); grip.addEventListener('pointermove',event=>{ if(!drag||event.pointerId!==drag.id)return; update(drag.pct+(event.clientX-drag.x)/window.innerWidth*100,false); }); const finish=event=>{if(!drag||event.pointerId!==drag.id)return;drag=null;update(pct);}; grip.addEventListener('pointerup',finish); grip.addEventListener('pointercancel',finish); grip.addEventListener('keydown',event=>{ if(event.key==='ArrowLeft'||event.key==='ArrowDown'){update(pct-5);event.preventDefault();} if(event.key==='ArrowRight'||event.key==='ArrowUp'){update(pct+5);event.preventDefault();} }); } let queued=false; function scan(){ queued=false; attach(document.getElementById('playerWindow'),'local'); attach(document.getElementById('youtubePlayerWindow'),'youtube'); } function schedule(){if(!queued){queued=true;requestAnimationFrame(scan);}} if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{ scan();new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true}); },{once:true}); else{scan();new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true});} })(); function switchAssignedRoom(){ if(confirm('Switch rooms? Voice and playback in this window will stop.')) location.assign(location.pathname+'?choose=1'); } async function renameSelectedRoom(){ const id=document.body.dataset.roomId; const name=prompt('Room display title (internal room ID will stay unchanged)',document.title); if(name===null)return; try{await api('/api/my/rooms/'+encodeURIComponent(id)+'/display-name',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({display_name:name})}); // Update displayed branding without disconnecting the current voice session. document.title=name.trim(); for(const el of document.querySelectorAll('[data-room-brand]'))el.textContent=name.trim(); }catch(e){alert(e.message);} }