4197 lines
207 KiB
JavaScript
4197 lines
207 KiB
JavaScript
// 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=`
|
||
<label class="library-sort-label">Sort
|
||
<select class="library-sort-mode">
|
||
<option value="alpha">Alphabetically</option>
|
||
<option value="date">Date added</option>
|
||
<option value="length">Length</option>
|
||
</select>
|
||
</label>
|
||
<select class="library-sort-direction" aria-label="Sort direction">
|
||
<option value="asc">Ascending</option>
|
||
<option value="desc">Descending</option>
|
||
</select>`;
|
||
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 = `<div class="error"><strong>Error</strong><br><br>${escapeHtml(error?.message || error)}</div>`; }
|
||
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 `<div class="library-mosaic library-mosaic-empty"><span>${escapeHtml(fallback)}</span></div>`;
|
||
}
|
||
return `<div class="library-mosaic">${safe.map(url => `<div class="library-mosaic-cell"><img src="${escapeAttribute(url)}" loading="lazy" onerror="this.parentElement.classList.add('image-failed');this.remove()"></div>`).join("")}</div>`;
|
||
}
|
||
|
||
function homeModuleCard({id, title, badge, subtitle, count, urls, extraClass="", actionName=""}) {
|
||
return `<article class="home-module-card ${escapeAttribute(extraClass)}" id="${escapeAttribute(id)}" tabindex="0" role="button" aria-label="${escapeAttribute(actionName || title)}">
|
||
${mosaicHtml(urls, badge || title)}
|
||
<div class="home-module-shade"></div>
|
||
<div class="home-module-content">
|
||
<div class="home-module-heading">
|
||
<h3>${escapeHtml(title)}</h3>
|
||
${badge ? `<span class="library-type-badge">${escapeHtml(badge)}</span>` : ""}
|
||
</div>
|
||
<div class="home-module-subtitle">${escapeHtml(subtitle || "")}</div>
|
||
<div class="home-module-count">${escapeHtml(count || "")}</div>
|
||
</div>
|
||
</article>`;
|
||
}
|
||
|
||
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 = `<div class="home-loading">Loading your media…</div>`;
|
||
|
||
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 = `
|
||
<section class="media-home">
|
||
<div class="media-home-heading">
|
||
<div>
|
||
<h2>Media</h2>
|
||
<div class="muted">Libraries, Tube and live TV in one place.</div>
|
||
</div>
|
||
</div>
|
||
<div class="home-module-grid">${localCards}${tubeCard}${musicCard}${twitchCard}${iptvCard}</div>
|
||
</section>`;
|
||
|
||
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=`<div class="scan-dialog"><div class="scan-dialog-header"><h2>Scan Libraries</h2><button id="closeScanDialogButton">✕</button></div><div class="scan-selection-tools"><button id="selectAllScanButton">Select All</button><button id="clearAllScanButton">Clear All</button><label class="scan-mode-label">Scan mode <select id="scanMode"><option value="quick" selected>Quick Scan</option><option value="deep">Deep / Full Scan</option></select></label></div><div class="scan-library-choices">${sources.map(s=>`<label class="scan-library-choice"><input type="checkbox" class="scan-library-checkbox" value="${s.id}"><span class="scan-library-choice-info"><strong>${escapeHtml(s.name)}</strong><small>${s.library_type==="shows"?"TV Shows":"Movies"} · ${s.media_count||0} items</small></span></label>`).join("")}</div><div class="scan-dialog-footer"><button id="cancelScanButton">Cancel</button><button id="startSelectedScanButton" class="primary">Scan Selected</button></div></div>`;
|
||
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='<div class="scan-monitor-top"><strong>Library scan</strong><button type="button" id="kronicScanMonitorClose">Close</button></div><div id="kronicScanMonitorBody">Checking scan status…</div>';
|
||
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=>`<div class="scan-monitor-warning">Unavailable: ${escapeHtml(path)}</div>`).join("");
|
||
const errors=Number(st.errors||0);
|
||
return `<div class="scan-monitor-item"><strong>${escapeHtml(st.name||"Library")}</strong> — ${escapeHtml(st.status||"waiting")}<div class="scan-monitor-muted">${escapeHtml(st.stage||"")} · ${Number(st.processed||0)}/${Number(st.total||0)} (${percent}%)</div><div class="scan-monitor-track"><div class="scan-monitor-fill" style="width:${percent}%"></div></div><div class="scan-monitor-muted">New: ${Number(st.new||0)} · Changed: ${Number(st.changed||0)} · Unchanged: ${Number(st.unchanged||0)} · Removed: ${Number(st.removed||0)}${errors?` · Errors: ${errors}`:""}</div><div class="scan-monitor-muted">${escapeHtml(st.current_path||"")}</div>${warnings}${errors?`<div class="scan-monitor-warning">${errors} file(s) failed. Check server journal for [SCAN] errors.</div>`:""}</div>`;
|
||
}).join("");
|
||
panel.querySelector("#kronicScanMonitorBody").innerHTML=`<p>${escapeHtml(stage)}</p>${lines||'<p>Waiting for the first library…</p>'}${!state.running&&state.completed_at?'<p class="scan-monitor-muted">Reopen the library to see newly indexed items.</p>':''}`;
|
||
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='<button id="manageBack">← Libraries</button><button id="newLib" class="primary">+ New Library</button>';document.getElementById("manageBack").onclick=showLibraries;document.getElementById("newLib").onclick=()=>showFolderBrowser("/");const sources=await api("/api/sources");content.innerHTML=`<h2>Manage Libraries</h2>${sources.map(s=>`<div class="manage-library-card" data-manage-library-card="${s.id}"><div class="manage-library-header"><div><h3>${escapeHtml(s.name)}</h3><div class="muted">${s.media_count||0} indexed items</div></div><div class="manage-library-controls"><select data-library-type="${s.id}"><option value="movies" ${s.library_type==="movies"?"selected":""}>Movies</option><option value="shows" ${s.library_type==="shows"?"selected":""}>TV Shows</option></select><label class="artwork-library-setting">Thumbnails <select data-library-artwork="${s.id}" title="Select the preferred thumbnail source for this library"><option value="generated_first" ${(s.artwork_preference||"jellyfin_first")==="generated_first"?"selected":""}>Generated frames first</option><option value="jellyfin_first" ${(s.artwork_preference||"jellyfin_first")==="jellyfin_first"?"selected":""}>Jellyfin artwork first</option></select></label><button data-manage-quick-scan="${s.id}">Quick Scan</button><button data-manage-deep-scan="${s.id}">Deep Scan</button><button data-toggle-library="${s.id}" data-enable-value="${s.enabled?0:1}">${s.enabled?"Disable":"Enable"}</button><button class="danger" data-remove-library="${s.id}">Remove Library</button></div></div><div class="library-folder-list">${(s.paths||[]).map(p=>`<div class="library-folder-row"><div class="library-folder-path">${escapeHtml(p.path)}</div><button class="danger" data-remove-library-path="${p.id}">Remove Folder</button></div>`).join("")}</div><button class="primary" data-add-path="${s.id}">+ Add Folder</button></div>`).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='<button id="folderBack">← Manage Libraries</button>';document.getElementById("folderBack").onclick=showManageLibraries;content.innerHTML=`<h2>Add Library</h2><div class="panel"><strong>Current Folder</strong><br><br>${escapeHtml(d.path)}</div><div class="folder-list">${d.parent?`<div class="folder" data-folder-path="${escapeAttribute(d.parent)}">📁 ..</div>`:""}${d.folders.map(f=>`<div class="folder" data-folder-path="${escapeAttribute(f.path)}">📁 ${escapeHtml(f.name)}</div>`).join("")}</div><div class="panel"><div class="form-row"><label>Library Name</label><input id="newLibraryName" value="${escapeAttribute(d.name)}"></div><div class="form-row"><label>Library Type</label><select id="newLibraryType"><option value="movies">Movies</option><option value="shows">TV Shows</option></select></div><button id="createLibraryButton" class="primary">Create Library Using This Folder</button></div>`;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=`<h2>Add Folder to ${escapeHtml(name)}</h2><div class="panel">${escapeHtml(d.path)}</div><div class="folder-list">${d.parent?`<div class="folder" data-add-folder-path="${escapeAttribute(d.parent)}">📁 ..</div>`:""}${d.folders.map(f=>`<div class="folder" data-add-folder-path="${escapeAttribute(f.path)}">📁 ${escapeHtml(f.name)}</div>`).join("")}</div><div class="panel"><button id="addCurrentFolderButton" class="primary">Add This Folder</button></div>`;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=`<h2>${escapeHtml(currentSourceName)}</h2><div class="show-grid">${entries.map(([n,items])=>{
|
||
const totalLength=items.reduce((sum,item)=>sum+durationValue(item),0);
|
||
return`<article class="show-card" data-show-name="${escapeAttribute(n)}"><div class="show-title">${escapeHtml(n)}</div><div class="show-thumbnail"><img src="${roomMediaUrl(`/thumbnail/${items[0].id}?art=v2`)}" loading="lazy"></div><div class="show-meta">${new Set(items.map(getSeasonName)).size} seasons<br>${items.length} episodes<br>${escapeHtml(formatDurationShort(totalLength))}</div></article>`;
|
||
}).join("")}</div>`;
|
||
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=`<h2>${escapeHtml(name)}</h2><div class="show-grid">${entries.map(([seasonName,seasonItems])=>{
|
||
const totalLength=seasonItems.reduce((sum,item)=>sum+durationValue(item),0);
|
||
return`<article class="season-card" data-season-name="${escapeAttribute(seasonName)}"><div class="show-title">${escapeHtml(seasonName)}</div><div class="show-thumbnail"><img src="${roomMediaUrl(`/thumbnail/${seasonItems[0].id}?art=v2`)}"></div><div class="show-meta">${seasonItems.length} episodes<br>${escapeHtml(formatDurationShort(totalLength))}</div></article>`;
|
||
}).join("")}</div>`;
|
||
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
|
||
?`<label class="tile-playback-option"><span>Quality</span><select data-quality-for="${item.id}">${q.map(x=>`<option value="${x.value}">${escapeHtml(x.label)}</option>`).join("")}</select></label>`
|
||
:`<div class="tile-playback-option tile-playback-readonly"><span>Quality</span><strong>${escapeHtml(q[0].label)}</strong></div>`;
|
||
let aHtml="";
|
||
if(tracks.length>1){
|
||
aHtml=`<label class="tile-playback-option"><span>Audio</span><select data-audio-for="${item.id}">${tracks.map(t=>`<option value="${t.stream_index}" ${t.default?"selected":""}>${escapeHtml(audioTrackLabel(t))}</option>`).join("")}</select></label>`;
|
||
}else if(tracks.length===1){
|
||
aHtml=`<div class="tile-playback-option tile-playback-readonly"><span>Audio</span><strong>${escapeHtml(audioTrackLabel(tracks[0]))}</strong></div>`;
|
||
}else{
|
||
aHtml=`<div class="tile-playback-option tile-playback-readonly" data-audio-pending="${item.id}"><span>Audio</span><strong>Detecting…</strong></div>`;
|
||
}
|
||
return `<div class="tile-playback-selectors">${qHtml}${aHtml}</div>`;
|
||
}
|
||
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=`<label class="tile-playback-option"><span>Audio</span><select data-audio-for="${mediaId}">${tracks.map(t=>`<option value="${t.stream_index}" ${t.default?"selected":""}>${escapeHtml(audioTrackLabel(t))}</option>`).join("")}</select></label>`;
|
||
}else if(tracks.length===1){
|
||
replacement=`<div class="tile-playback-option tile-playback-readonly"><span>Audio</span><strong>${escapeHtml(audioTrackLabel(tracks[0]))}</strong></div>`;
|
||
}else{
|
||
replacement=`<div class="tile-playback-option tile-playback-readonly"><span>Audio</span><strong>No audio stream</strong></div>`;
|
||
}
|
||
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=`<h2>${escapeHtml(title)}</h2>${extra}<div class="media-grid">${media.map(i=>{
|
||
const t=getDisplayTitle(i,episodeView);
|
||
return`<article class="media-card cinematic-media-card"><div class="thumbnail-container cinematic-thumbnail" data-play-id="${i.id}" data-play-title="${escapeAttribute(t)}"><img class="media-thumbnail" src="${roomMediaUrl(`/thumbnail/${i.id}?art=v2`)}" loading="lazy"><div class="thumbnail-placeholder">▶</div><div class="thumbnail-play-overlay">▶</div><div class="cinematic-title"><strong>${escapeHtml(t)}</strong><span>${escapeHtml(i.effective_year??i.year??"")} ${i.duration_seconds?`· ${escapeHtml(formatDurationShort(i.duration_seconds))}`:""}</span></div></div><div class="media-meta cinematic-meta"><span>${escapeHtml(i.resolution||"Unknown")}</span><span>${escapeHtml(i.source_name||"Uncategorized")}</span></div>${playbackSelectorMarkup(i)}<div class="media-actions"><button class="primary" data-play-button="${i.id}" data-play-title="${escapeAttribute(t)}">Play</button><a class="button-link" href="${roomMediaUrl(`/external/${i.id}.m3u`)}" title="Open in VLC, mpv, or another M3U-capable player">External</a>${canManageMedia()?`<button data-move-id="${i.id}" data-current-library="${i.source_id??""}">Move</button>`:""}</div></article>`;
|
||
}).join("")}</div>`;
|
||
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 = `
|
||
<h2>Metadata</h2>
|
||
|
||
<div class="panel youtube-metadata-panel">
|
||
<div class="youtube-metadata-heading">
|
||
<div>
|
||
<h3>YouTube Metadata</h3>
|
||
<div class="muted">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.</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="youtube-controls">
|
||
<div class="metadata-filter-group">
|
||
<label>Library</label>
|
||
<select id="youtubeLibrarySelect">
|
||
<option value="">Choose a library...</option>
|
||
${sources.map(s=>`<option value="${s.id}" ${selectedId===s.id?"selected":""}>${escapeHtml(s.name)}</option>`).join("")}
|
||
</select>
|
||
</div>
|
||
|
||
<div class="metadata-filter-group">
|
||
<label>Action</label>
|
||
<select id="youtubeModeSelect">
|
||
<option value="metadata">Update metadata only</option>
|
||
<option value="rename">Rename file + update metadata</option>
|
||
</select>
|
||
</div>
|
||
|
||
<label class="youtube-force-refresh">
|
||
<input id="youtubeForceRefresh" type="checkbox">
|
||
Refresh cached YouTube data
|
||
</label>
|
||
|
||
<button id="youtubePreviewButton" class="primary" type="button">Preview</button>
|
||
<button id="youtubeApplyButton" type="button" disabled>Apply Changes</button>
|
||
</div>
|
||
|
||
<div id="youtubeStatus" class="youtube-status muted">Choose a library and click Preview.</div>
|
||
<div id="youtubeProgressWrap" class="youtube-progress-wrap" hidden>
|
||
<div class="scan-progress-track"><div id="youtubeProgressBar" class="scan-progress-fill" style="width:0%"></div></div>
|
||
<div id="youtubeProgressText" class="scan-percent">0%</div>
|
||
</div>
|
||
<div id="youtubePreviewResults"></div>
|
||
</div>
|
||
|
||
<div class="metadata-toolbar">
|
||
<div class="metadata-filter-group">
|
||
<label>Library</label>
|
||
<select id="metadataLibraryFilter">
|
||
<option value="">All Libraries</option>
|
||
${sources.map(s=>`<option value="${s.id}" ${selectedId===s.id?"selected":""}>${escapeHtml(s.name)}</option>`).join("")}
|
||
</select>
|
||
</div>
|
||
<div class="metadata-filter-group metadata-search-group">
|
||
<label>Search</label>
|
||
<input id="metadataSearchInput" type="search" placeholder="Filter titles...">
|
||
</div>
|
||
<button id="metadataLoadButton" class="primary">Load</button>
|
||
</div>
|
||
<div id="metadataTableContainer"></div>
|
||
`;
|
||
|
||
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=`<div class="error">${escapeHtml(e.message)}</div>`;}}
|
||
function renderMetadataTable(media){const target=document.getElementById("metadataTableContainer");if(!media.length){target.innerHTML='<div class="panel">No media found.</div>';return;}target.innerHTML=`<div class="metadata-table-wrapper"><table class="metadata-table"><thead><tr><th>Preview</th><th>Title</th><th>Series</th><th>Episode Title</th><th>Year</th><th>Season</th><th>Episode</th><th>Resolution</th><th>Library</th><th>Actions</th></tr></thead><tbody>${media.map(i=>`<tr class="metadata-row" data-media-id="${i.id}"><td><img class="metadata-thumbnail" src="${roomMediaUrl(`/thumbnail/${i.id}?art=v2`)}"></td><td><input class="metadata-title-input" value="${escapeAttribute(i.effective_title??i.title??"")}"></td><td><input class="metadata-series-input" value="${escapeAttribute(i.effective_series_title??i.series_title??"")}"></td><td><input class="metadata-episode-title-input" value="${escapeAttribute(i.effective_episode_title??i.episode_title??"")}"></td><td><input class="metadata-year-input" type="number" value="${i.effective_year??i.year??""}"></td><td><input class="metadata-season-input" type="number" value="${i.effective_season??i.season??""}"></td><td><input class="metadata-episode-input" type="number" value="${i.effective_episode??i.episode??""}"></td><td>${escapeHtml(i.resolution||"-")}</td><td>${escapeHtml(i.source_name||"-")}</td><td><div class="metadata-actions"><button class="primary" data-metadata-save="${i.id}">Save</button><button data-metadata-reset="${i.id}">Reset</button><button data-metadata-reanalyze="${i.id}">Re-analyze</button><button data-metadata-info="${i.id}">MediaInfo</button></div></td></tr>`).join("")}</tbody></table></div>`;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=`<div class="metadata-info-dialog"><div class="metadata-info-header"><div><h2>MediaInfo</h2><div class="muted">${escapeHtml(d.file||"")}</div></div><button id="closeMetadataInfoButton">✕</button></div><div class="metadata-info-section"><h3>Normalized Metadata</h3><pre>${escapeHtml(JSON.stringify(d.normalized||{},null,2))}</pre></div><div class="metadata-info-section"><h3>GuessIt</h3><pre>${escapeHtml(JSON.stringify(d.guessit||{},null,2))}</pre></div><div class="metadata-info-section"><h3>MediaInfo</h3><pre>${escapeHtml(JSON.stringify(d.mediainfo||{},null,2))}</pre></div></div>`;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 = `
|
||
<div class="youtube-summary">
|
||
<span><strong>${readyCount}</strong> matched YouTube videos</span>
|
||
<span><strong>${state.skipped || 0}</strong> files without an ID</span>
|
||
<span><strong>${cachedCount}</strong> cache hits</span>
|
||
<span><strong>${errorCount}</strong> errors</span>
|
||
</div>
|
||
<div class="youtube-preview-scroll">
|
||
<table class="youtube-preview-table">
|
||
<thead>
|
||
<tr>
|
||
<th>ID</th>
|
||
<th>Current title</th>
|
||
<th>YouTube title</th>
|
||
<th>Channel</th>
|
||
<th>Filename</th>
|
||
<th>Status</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
${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 `
|
||
<tr>
|
||
<td><code>${escapeHtml(item.video_id || "-")}</code></td>
|
||
<td>${escapeHtml(item.current_title || "-")}</td>
|
||
<td>${escapeHtml(item.proposed_title || "-")}</td>
|
||
<td>${escapeHtml(item.channel_name || "-")}</td>
|
||
<td><code>${escapeHtml(item.current_filename || "-")}</code>${item.proposed_filename ? `<span class="youtube-title-arrow">→</span><code>${escapeHtml(item.proposed_filename)}</code>` : ""}</td>
|
||
<td class="${statusClass}">${escapeHtml(statusText)}</td>
|
||
</tr>`;
|
||
}).join("")}
|
||
</tbody>
|
||
</table>
|
||
</div>`;
|
||
}
|
||
|
||
|
||
// ============================================================
|
||
// 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=`
|
||
<div class="youtube-player-window">
|
||
<div class="youtube-player-header">
|
||
<div id="twitchPlayerTitle" class="youtube-player-title">Twitch</div>
|
||
<div class="youtube-player-actions">
|
||
<button id="twitchPlayerRecord" type="button">Record Live</button>
|
||
<button id="twitchPlayerMinimize" type="button">Minimize</button>
|
||
<button id="twitchPlayerFullscreen" type="button">Fullscreen</button>
|
||
<button id="twitchPlayerClose" type="button">Close</button>
|
||
</div>
|
||
</div>
|
||
<div class="youtube-player-video-wrap">
|
||
<video id="twitchVideoElement" controls autoplay playsinline></video>
|
||
</div>
|
||
<div class="twitch-player-resize-handle" title="Drag to resize"></div>
|
||
</div>`;
|
||
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=`
|
||
<section class="twitch-page">
|
||
<div class="twitch-page-heading">
|
||
<div>
|
||
<h2>Twitch</h2>
|
||
<div class="muted">Streamlink resolves Twitch. Kronic handles playback and DVR recording through FFmpeg.</div>
|
||
</div>
|
||
<button id="twitchRefreshAll" type="button">Refresh</button>
|
||
</div>
|
||
|
||
<form id="twitchAddForm" class="youtube-search-form">
|
||
<input id="twitchChannelInput" type="text"
|
||
placeholder="Twitch channel or https://twitch.tv/channel"
|
||
autocomplete="off">
|
||
<button class="primary" type="submit">Add Channel</button>
|
||
</form>
|
||
|
||
<div id="twitchStatus" class="muted"></div>
|
||
|
||
<section class="youtube-section">
|
||
<div class="youtube-section-heading">
|
||
<h3>Channels</h3>
|
||
<span class="muted">Watch · Record Live · Auto Record When Live</span>
|
||
</div>
|
||
<div id="twitchChannelArea" class="twitch-channel-grid">
|
||
<div class="loading">Loading Twitch channels…</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="youtube-section">
|
||
<div class="youtube-section-heading">
|
||
<h3>Recordings</h3>
|
||
<button id="twitchClearFinished" type="button">Clear Finished</button>
|
||
</div>
|
||
<div id="twitchRecordingArea"></div>
|
||
<div id="kronicScheduledRecordingList" class="kronic-scheduled-list"></div>
|
||
</section>
|
||
</section>`;
|
||
|
||
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 `
|
||
<article class="twitch-channel-card ${live?"is-live":""}">
|
||
<div class="twitch-channel-header">
|
||
<div>
|
||
<strong>${escapeHtml(channel.author||channel.channel_name)}</strong>
|
||
<div class="muted">${live?"LIVE":"Offline"}${channel.category?` · ${escapeHtml(channel.category)}`:""}</div>
|
||
</div>
|
||
${live?`<span class="twitch-live-badge">LIVE</span>`:""}
|
||
</div>
|
||
<div class="twitch-channel-title">
|
||
${escapeHtml(channel.title || (live?"Live stream":"Channel offline"))}
|
||
</div>
|
||
|
||
<label class="twitch-quality-row">
|
||
<span>Quality</span>
|
||
<select data-twitch-quality="${channel.id}">
|
||
${qualities.map(q=>`<option value="${escapeAttribute(q)}" ${q===channel.quality?"selected":""}>${escapeHtml(q)}</option>`).join("")}
|
||
</select>
|
||
</label>
|
||
|
||
<div class="twitch-channel-actions">
|
||
<button class="primary" type="button"
|
||
data-twitch-watch="${channel.id}"
|
||
${live?"":"disabled"}>Watch</button>
|
||
<button type="button"
|
||
data-twitch-record="${channel.id}"
|
||
${live?"":"disabled"}>Record Live</button>
|
||
<button type="button" data-twitch-schedule="${channel.id}" title="Schedule recording for a date and time">Schedule</button>
|
||
<button type="button"
|
||
data-twitch-auto="${channel.id}">
|
||
${Number(channel.auto_record)?"Auto Record: ON":"Auto Record: OFF"}
|
||
</button>
|
||
<button type="button" data-twitch-refresh="${channel.id}">Refresh</button>
|
||
<button type="button" data-twitch-remove="${channel.id}">Remove</button>
|
||
</div>
|
||
</article>`;
|
||
}
|
||
|
||
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("")
|
||
:`<div class="panel muted">No Twitch channels yet.</div>`;
|
||
|
||
recordingArea.innerHTML=recordings.length
|
||
?recordings.map(job=>`
|
||
<div class="twitch-recording-row twitch-recording-${escapeAttribute(job.status)}">
|
||
<div>
|
||
<strong>${escapeHtml(job.title||job.channel_name||"Twitch recording")}</strong>
|
||
<div class="muted">${escapeHtml(job.channel_name||"")} · ${escapeHtml(job.status)} · ${escapeHtml(job.message||"")}</div>
|
||
${job.output_path?`<small>${escapeHtml(job.output_path)}</small>`:""}
|
||
${job.error?`<small class="error">${escapeHtml(job.error)}</small>`:""}
|
||
</div>
|
||
<div>
|
||
${job.status==="recording"||job.status==="queued"
|
||
?`<button type="button" data-twitch-stop="${job.id}">Stop Recording</button>`
|
||
:""}
|
||
</div>
|
||
</div>`).join("")
|
||
:`<div class="muted">No Twitch recordings yet.</div>`;
|
||
|
||
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=`<div class="error">${escapeHtml(error.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
// 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=`<form method="dialog" class="kronic-recording-form">
|
||
<h3>Schedule ${provider==='twitch'?'Twitch':'YouTube live'} recording</h3>
|
||
<p class="muted">${escapeHtml(title||mediaKey)} — the server starts the recording at this time, even with the browser closed.</p>
|
||
<label>Start date and time (your local timezone)<input name="start" type="datetime-local" required value="${localValue}"></label>
|
||
<div id="kronicRecordingError" role="status"></div>
|
||
<div class="kronic-dialog-actions"><button value="cancel">Cancel</button><button type="button" class="primary" id="kronicScheduleConfirm">Schedule recording</button></div>
|
||
</form>`;
|
||
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")}
|
||
<section class="youtube-library-page">
|
||
<div class="youtube-page-header">
|
||
<div>
|
||
<h2>YouTube</h2>
|
||
<div class="muted">Search through the Kronic resolver. Videos you finish streaming are retained in the local watched-video cache.</div>
|
||
</div>
|
||
<div id="youtubeCacheStatus" class="youtube-cache-status">Loading cache...</div>
|
||
</div>
|
||
|
||
<form id="youtubeSearchForm" class="youtube-search-form">
|
||
<input id="youtubeSearchInput" type="search" placeholder="Search YouTube..." autocomplete="off">
|
||
<button class="primary" type="submit">Search</button>
|
||
</form>
|
||
|
||
<div id="youtubeSearchArea"></div>
|
||
<section class="youtube-section cache-jobs-section">
|
||
<div class="youtube-section-heading">
|
||
<h3>Background Cache</h3>
|
||
<span class="muted">Video → Tube cache · Audio → Music library</span>
|
||
</div>
|
||
<div id="cacheJobsArea" class="cache-jobs-area"><div class="muted">Loading jobs…</div></div>
|
||
</section>
|
||
|
||
<div id="youtubeHistoryArea"><div class="loading">Loading watched videos...</div></div>
|
||
</section>
|
||
`;
|
||
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 ? `<details class="youtube-section youtube-collapsible"><summary>Continue Watching <span class="youtube-section-count">${continueItems.length} items</span></summary><div class="youtube-card-grid">${continueItems.map(item => youtubeCardHtml(item, true)).join("")}</div></details>` : ""}
|
||
${recentItems.length ? `<details class="youtube-section youtube-collapsible"><summary>Recently Watched <span class="youtube-section-count">${recentItems.length} items</span></summary><div class="youtube-card-grid">${recentItems.map(item => youtubeCardHtml(item, true)).join("")}</div></details>` : `<div class="panel muted">No YouTube watch history yet.</div>`}
|
||
`;
|
||
registerYouTubeItems(items);
|
||
bindYouTubeWatchButtons();
|
||
} catch (error) {
|
||
target.innerHTML = `<div class="error">${escapeHtml(error.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
async function searchYouTube(query, existingItems=null) {
|
||
const target = document.getElementById("youtubeSearchArea");
|
||
if (!target) return;
|
||
target.innerHTML = `<details class="youtube-section youtube-collapsible" open><summary>Search Results</summary><div class="loading">Searching...</div></details>`;
|
||
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 = `
|
||
<details class="youtube-section youtube-collapsible" open>
|
||
<summary>Search Results <span class="youtube-section-count">${items.length} result${items.length === 1 ? "" : "s"}</span></summary>
|
||
<div class="youtube-card-grid">${items.map(item => youtubeCardHtml(item, false)).join("") || `<div class="panel muted">No results.</div>`}</div>
|
||
</details>
|
||
`;
|
||
bindYouTubeWatchButtons();
|
||
} catch (error) {
|
||
target.innerHTML = `<div class="error">${escapeHtml(error.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
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 `
|
||
<article class="youtube-card">
|
||
<button class="youtube-thumb-button" type="button" data-youtube-watch="${escapeAttribute(id)}" aria-label="Watch ${escapeAttribute(title)}">
|
||
${thumbnail ? `<img src="${escapeAttribute(roomMediaUrl(thumbnail))}" alt="" loading="lazy" referrerpolicy="no-referrer">` : `<div class="youtube-thumb-placeholder">▶</div>`}
|
||
<span class="youtube-play-badge">▶</span>
|
||
${formatYouTubeDuration(duration) ? `<span class="youtube-duration">${escapeHtml(formatYouTubeDuration(duration))}</span>` : ""}
|
||
${historyMode && progressPercent > 0 && !item.completed ? `<span class="youtube-card-progress"><span style="width:${progressPercent}%"></span></span>` : ""}
|
||
</button>
|
||
<div class="youtube-card-body">
|
||
<div class="youtube-card-title">${escapeHtml(title)}</div>
|
||
<div class="youtube-card-channel">${escapeHtml(channel)}</div>
|
||
<div class="youtube-card-meta">
|
||
${cached ? `<span class="youtube-cache-badge">Cached</span>` : ""}
|
||
${historyMode && position >= 30 && !item.completed ? `<span>Resume ${escapeHtml(formatPlaybackTime(position))}</span>` : ""}
|
||
${historyMode && item.completed ? `<span>Watched</span>` : ""}
|
||
</div>
|
||
<div class="youtube-card-actions">
|
||
<button class="primary youtube-watch-button" type="button" data-youtube-watch="${escapeAttribute(id)}">${historyMode && position >= 30 && !item.completed ? "Resume" : "Watch"}</button>
|
||
<button type="button" data-youtube-cache-video="${escapeAttribute(id)}">${item.is_live ? "Record Live" : "Cache Video"}</button>
|
||
${item.is_live ? `<button type="button" data-youtube-schedule="${escapeAttribute(id)}">Schedule Live</button>` : ''}
|
||
<button type="button" data-youtube-cache-music="${escapeAttribute(id)}">Save as Music</button>
|
||
</div>
|
||
</div>
|
||
</article>
|
||
`;
|
||
}
|
||
|
||
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=`
|
||
<div class="cache-job-toolbar">
|
||
<button type="button" data-cache-clear="complete">Clear Completed</button>
|
||
<button type="button" data-cache-clear="failed,cancelled">Clear Errors</button>
|
||
<button type="button" data-cache-clear="complete,failed,cancelled">Clear Finished</button>
|
||
</div>`;
|
||
|
||
if(!jobs.length){
|
||
target.innerHTML=toolbar+`<div class="muted">No cache jobs.</div>`;
|
||
}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=`<button type="button" data-cache-job="${job.id}" data-cache-action="cancel">${live?"Stop Recording":"Cancel"}</button>`;
|
||
}else if(job.status==="failed"||job.status==="cancelled"){
|
||
actions=`
|
||
<button type="button" data-cache-job="${job.id}" data-cache-action="retry">Retry</button>
|
||
<button type="button" data-cache-job="${job.id}" data-cache-action="remove">Remove</button>`;
|
||
}else if(job.status==="complete"){
|
||
actions=`<button type="button" data-cache-job="${job.id}" data-cache-action="remove">Remove</button>`;
|
||
}
|
||
|
||
const progressDisplay=(live&&job.status==="running")
|
||
?`<div class="cache-live-indicator"><span class="cache-live-dot"></span>LIVE</div>`
|
||
:`<div class="scan-progress-track"><div class="scan-progress-fill" style="width:${progress}%"></div></div><span>${Math.round(progress)}%</span>`;
|
||
|
||
return `<div class="cache-job-row cache-job-${escapeAttribute(job.status)}">
|
||
<div class="cache-job-main">
|
||
<strong>${escapeHtml(title)}</strong>
|
||
<span>${escapeHtml(mode)} · ${escapeHtml(job.status)}</span>
|
||
${job.error
|
||
?`<small class="error">${escapeHtml(job.error)}</small>`
|
||
:`<small>${escapeHtml(job.message||"")}</small>`}
|
||
</div>
|
||
<div class="cache-job-progress">${progressDisplay}</div>
|
||
<div class="cache-job-actions">${actions}</div>
|
||
</div>`;
|
||
}).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=`<div class="error">${escapeHtml(error.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
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 = `
|
||
<div class="youtube-player-window" id="youtubePlayerWindow">
|
||
<div class="youtube-player-header">
|
||
<div id="youtubePlayerTitle" class="youtube-player-title">YouTube</div>
|
||
<div class="youtube-player-actions">
|
||
<button id="youtubePlayerCacheVideo" type="button">Cache Video</button>
|
||
<button id="youtubePlayerSaveMusic" type="button">Save as Music</button>
|
||
<button id="youtubePlayerMinimize" type="button">Minimize</button>
|
||
<button id="youtubePlayerFullscreen" type="button">Fullscreen</button>
|
||
<button id="youtubePlayerClose" type="button">Close</button>
|
||
</div>
|
||
</div>
|
||
<video id="youtubeVideoElement" controls autoplay playsinline preload="metadata"></video>
|
||
</div>
|
||
`;
|
||
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 `
|
||
<option value="" ${chosen === "" ? "selected" : ""}>My Channels (no playlist)</option>
|
||
${(collections || []).map(item => `
|
||
<option value="${item.id}" ${String(item.id) === chosen ? "selected" : ""}>${escapeHtml(item.name)}</option>
|
||
`).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 = `<div class="loading">Loading IPTV…</div>`;
|
||
|
||
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 = `
|
||
<section class="iptv-page iptv-library-view">
|
||
<div class="iptv-heading compact">
|
||
<div>
|
||
<h2>IPTV</h2>
|
||
<div class="muted">Live channels</div>
|
||
</div>
|
||
</div>
|
||
<section class="iptv-channel-panel">
|
||
<div class="iptv-channel-toolbar">
|
||
<h3>Channels</h3>
|
||
<input id="iptvChannelSearch" type="search" placeholder="Filter channels…">
|
||
</div>
|
||
<div id="iptvChannelList">${iptvSelectedChannelsHtml(channels)}</div>
|
||
</section>
|
||
</section>`;
|
||
bindIptvChannelOnly();
|
||
}
|
||
|
||
function renderIptvSettingsPage(overview) {
|
||
const collections = overview.collections || [];
|
||
const sources = overview.sources || [];
|
||
|
||
content.innerHTML = `
|
||
<section class="iptv-page iptv-settings-view">
|
||
<div class="iptv-heading">
|
||
<div>
|
||
<h2>IPTV Settings</h2>
|
||
<div class="muted">Add playlists, direct channels, sharing and channel selections.</div>
|
||
</div>
|
||
<button id="iptvSettingsWatch" class="primary" type="button">Watch IPTV</button>
|
||
</div>
|
||
|
||
<section id="iptvManagePanel" class="iptv-manage-panel">
|
||
<div class="iptv-manage-grid">
|
||
<div class="panel iptv-add-card">
|
||
<h3>Playlists</h3>
|
||
<form id="iptvCollectionForm" class="iptv-stack-form">
|
||
<input id="iptvCollectionName" placeholder="New playlist name" required>
|
||
<label class="iptv-public-option"><input id="iptvCollectionPublic" type="checkbox"> Public to all users</label>
|
||
<button type="submit">Create Playlist</button>
|
||
</form>
|
||
<div id="iptvCollectionList" class="iptv-small-list">
|
||
${collections.length ? collections.map(c => `
|
||
<div class="iptv-small-row">
|
||
<span><strong>${escapeHtml(c.name)}</strong><small>${c.channel_count || 0} selected channels</small></span>
|
||
<label class="iptv-public-toggle" title="Share this playlist's selected channels with every approved media-server user">
|
||
<input type="checkbox" data-iptv-collection-public="${c.id}" ${Number(c.is_public) ? "checked" : ""}>
|
||
Public
|
||
</label>
|
||
<button class="danger" data-iptv-delete-collection="${c.id}" type="button">Delete</button>
|
||
</div>`).join("") : `<div class="muted">No named playlists yet.</div>`}
|
||
</div>
|
||
</div>
|
||
|
||
<div class="panel iptv-add-card">
|
||
<h3>1. Upload M3U</h3>
|
||
<form id="iptvUploadForm" class="iptv-stack-form">
|
||
<input id="iptvUploadName" placeholder="List name" required>
|
||
<select id="iptvUploadCollection">${iptvCollectionOptions(collections)}</select>
|
||
<label class="iptv-public-option"><input id="iptvUploadPublic" type="checkbox"> Public to all users</label>
|
||
<input id="iptvUploadFile" type="file" accept=".m3u,.m3u8,text/plain,application/x-mpegURL" required>
|
||
<button class="primary" type="submit">Import File</button>
|
||
</form>
|
||
</div>
|
||
|
||
<div class="panel iptv-add-card">
|
||
<h3>2. M3U URL</h3>
|
||
<form id="iptvUrlForm" class="iptv-stack-form">
|
||
<input id="iptvUrlName" placeholder="List name" required>
|
||
<select id="iptvUrlCollection">${iptvCollectionOptions(collections)}</select>
|
||
<label class="iptv-public-option"><input id="iptvUrlPublic" type="checkbox"> Public to all users</label>
|
||
<input id="iptvUrlValue" type="url" placeholder="https://example/list.m3u" required>
|
||
<button class="primary" type="submit">Import URL</button>
|
||
</form>
|
||
</div>
|
||
|
||
<div class="panel iptv-add-card">
|
||
<h3>3. Direct Channel URL</h3>
|
||
<form id="iptvChannelForm" class="iptv-stack-form">
|
||
<input id="iptvChannelName" placeholder="Channel name" required>
|
||
<select id="iptvChannelCollection">${iptvCollectionOptions(collections)}</select>
|
||
<label class="iptv-public-option"><input id="iptvChannelPublic" type="checkbox"> Public to all users</label>
|
||
<input id="iptvChannelUrl" type="url" placeholder="https://example/live/playlist.m3u8" required>
|
||
<button class="primary" type="submit">Add Channel</button>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="panel iptv-source-panel">
|
||
<div class="iptv-section-heading"><h3>Sources</h3><span class="muted">Choose exactly which channels from each list appear in IPTV.</span></div>
|
||
<div class="iptv-source-list">
|
||
${sources.length ? sources.map(source => iptvSourceRow(source, collections)).join("") : `<div class="muted">No IPTV sources yet.</div>`}
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</section>`;
|
||
|
||
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 ? `<div class="iptv-source-error">${escapeHtml(source.last_error)}</div>` : "";
|
||
const kind = source.source_type === "upload" ? "Uploaded M3U" : (source.source_type === "url" ? "Remote M3U" : "Direct channel");
|
||
return `
|
||
<article class="iptv-source-row">
|
||
<div class="iptv-source-info">
|
||
<strong>${escapeHtml(source.name)}</strong>
|
||
<span>${escapeHtml(kind)} · ${source.selected_count || 0}/${source.channel_count || 0} selected</span>
|
||
${error}
|
||
</div>
|
||
<select data-iptv-source-collection="${source.id}" title="Playlist">
|
||
${iptvCollectionOptions(collections, source.collection_id)}
|
||
</select>
|
||
<label class="iptv-public-toggle" title="Share this source's selected channels with every approved media-server user">
|
||
<input type="checkbox" data-iptv-source-public="${source.id}" ${Number(source.is_public) ? "checked" : ""}>
|
||
Public
|
||
</label>
|
||
${source.source_type !== "channel" ? `<button data-iptv-choose="${source.id}" type="button">Choose Channels</button><button data-iptv-refresh="${source.id}" type="button">Refresh</button>` : ""}
|
||
<button class="danger" data-iptv-delete-source="${source.id}" type="button">Delete</button>
|
||
</article>
|
||
`;
|
||
}
|
||
|
||
function iptvSelectedChannelsHtml(channels) {
|
||
if (!channels.length) return `<div class="panel muted">No channels selected yet. Add a source, then choose the channels you want.</div>`;
|
||
|
||
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 => `
|
||
<section class="iptv-channel-group" data-iptv-group>
|
||
<div class="iptv-group-heading">
|
||
<div><strong>${escapeHtml(section.collection)}</strong><span>${escapeHtml(section.group)}</span></div>
|
||
<span class="muted">${section.channels.length} channel${section.channels.length === 1 ? "" : "s"}</span>
|
||
</div>
|
||
<div class="iptv-channel-grid">
|
||
${section.channels.map(channel => iptvChannelCard(channel)).join("")}
|
||
</div>
|
||
</section>
|
||
`).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 `
|
||
<article class="iptv-channel-card iptv-snapshot-card" data-iptv-channel-card data-search="${escapeAttribute(`${channel.name} ${channel.tvg_id || ""} ${channel.group_name || ""} ${channel.source_name || ""}`.toLowerCase())}">
|
||
<div class="iptv-channel-visual">
|
||
<img class="iptv-channel-snapshot" src="${snapshot}" ${fallbackAttr} alt="" loading="lazy" referrerpolicy="no-referrer">
|
||
<div class="iptv-channel-live-badge">LIVE</div>
|
||
<div class="iptv-channel-visual-shade"></div>
|
||
</div>
|
||
<div class="iptv-channel-body">
|
||
<strong>${escapeHtml(channel.name)}${Number(channel.is_shared) ? ` <em class="iptv-shared-badge">SHARED</em>` : ""}</strong>
|
||
<span>${escapeHtml(channel.group_name || channel.source_name || "")}</span>
|
||
${channel.tvg_id ? `<small>${escapeHtml(channel.tvg_id)}</small>` : ""}
|
||
<div class="iptv-channel-actions">
|
||
<button class="primary" data-iptv-play="${channel.id}" data-iptv-title="${escapeAttribute(channel.name)}" type="button">Watch</button>
|
||
<button data-iptv-hide="${channel.id}" type="button">Hide</button>
|
||
</div>
|
||
</div>
|
||
</article>`;
|
||
}
|
||
|
||
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 = `<button id="iptvChooserBack">← IPTV</button>`;
|
||
document.getElementById("iptvChooserBack").onclick = () => showIptvLibrary("settings");
|
||
content.innerHTML = `<div class="loading">Loading channels…</div>`;
|
||
|
||
try {
|
||
const data = await api(`/api/iptv/sources/${sourceId}/channels`);
|
||
const source = data.source;
|
||
const channels = data.channels || [];
|
||
content.innerHTML = `
|
||
<section class="iptv-chooser-page">
|
||
<div class="iptv-section-heading">
|
||
<div><h2>${escapeHtml(source?.name || "IPTV source")}</h2><div class="muted">Check only the channels you want in your IPTV channel list.</div></div>
|
||
<span class="iptv-count-badge"><span id="iptvCheckedCount">0</span> / ${channels.length} selected</span>
|
||
</div>
|
||
<div class="iptv-chooser-toolbar">
|
||
<input id="iptvChooserSearch" type="search" placeholder="Filter this M3U list…">
|
||
<button id="iptvSelectVisible" type="button">Select Visible</button>
|
||
<button id="iptvClearVisible" type="button">Clear Visible</button>
|
||
<button id="iptvSaveSelection" class="primary" type="button">Save Selection</button>
|
||
</div>
|
||
<div id="iptvChooserRows" class="iptv-chooser-list">
|
||
${channels.map(channel => `
|
||
<label class="iptv-chooser-row" data-iptv-choice-row data-search="${escapeAttribute(`${channel.name} ${channel.tvg_id || ""} ${channel.group_name || ""}`.toLowerCase())}">
|
||
<input type="checkbox" data-iptv-choice="${channel.id}" ${channel.selected && !channel.hidden ? "checked" : ""}>
|
||
<span class="iptv-choice-main"><strong>${escapeHtml(channel.name)}</strong><small>${escapeHtml(channel.group_name || "Ungrouped")}${channel.tvg_id ? ` · ${escapeHtml(channel.tvg_id)}` : ""}</small></span>
|
||
<span class="iptv-choice-url">${escapeHtml(channel.stream_url)}</span>
|
||
</label>
|
||
`).join("") || `<div class="panel muted">No channels were found in this source.</div>`}
|
||
</div>
|
||
</section>
|
||
`;
|
||
|
||
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=`
|
||
<img id="musicPlayerCover" class="music-player-cover" alt="">
|
||
<div class="music-player-info"><strong id="musicPlayerTitle">Nothing playing</strong><span id="musicPlayerArtist"></span></div>
|
||
<button id="musicPrev" type="button" aria-label="Previous">⏮</button>
|
||
<audio id="musicAudio" controls preload="metadata"></audio>
|
||
<button id="musicNext" type="button" aria-label="Next">⏭</button>
|
||
<button id="musicClose" type="button" aria-label="Close">×</button>
|
||
<div class="kronic-music-touch-controls" aria-label="Music playback controls">
|
||
<div class="kronic-music-touch-row">
|
||
<button type="button" id="musicTouchPrev" class="kronic-audio-icon" aria-label="Previous track" title="Previous track">⏮</button>
|
||
<button type="button" id="musicTouchToggle" class="kronic-audio-icon kronic-audio-primary" aria-label="Pause" title="Play or pause">❚❚</button>
|
||
<button type="button" id="musicTouchNext" class="kronic-audio-icon" aria-label="Next track" title="Next track">⏭</button>
|
||
<button type="button" id="musicTouchClose" class="kronic-audio-icon kronic-audio-close" aria-label="Close player" title="Close">✕</button>
|
||
</div>
|
||
<div class="kronic-music-seek-row">
|
||
<span id="musicTouchElapsed">0:00</span>
|
||
<input id="musicTouchSeek" type="range" min="0" max="1000" value="0" aria-label="Seek through track">
|
||
<span id="musicTouchDuration">0:00</span>
|
||
<button type="button" id="musicTouchMute" class="kronic-audio-icon" aria-label="Mute or unmute" title="Mute or unmute">◖))</button>
|
||
</div>
|
||
</div>`;
|
||
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?`<img src="${escapeAttribute(roomMediaUrl(track.cover_url))}" alt="" loading="lazy" referrerpolicy="no-referrer">`:`<div class="music-cover-placeholder">♪</div>`;
|
||
return `<article class="music-track-card">
|
||
<button class="music-cover-button" type="button" data-music-play="${track.id}">${cover}<span class="music-play-overlay">▶</span></button>
|
||
<div class="music-track-body">
|
||
<strong>${escapeHtml(track.title||"Unknown")}</strong>
|
||
<span>${escapeHtml(track.artist||"")}</span>
|
||
<small>${escapeHtml(track.album||track.list_name||"")}</small>
|
||
<div class="music-track-actions"><button class="primary" type="button" data-music-play="${track.id}">Play</button>${track.cached?`<span class="music-cache-badge">Cached</span>`:""}</div>
|
||
</div>
|
||
</article>`;
|
||
}
|
||
|
||
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=`<div class="loading">Loading music…</div>`;
|
||
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])=>`
|
||
<section class="music-section"><div class="music-section-heading"><h3>${escapeHtml(name)}</h3><span class="muted">${items.length} track${items.length===1?"":"s"}</span></div>
|
||
<div class="music-track-grid">${items.map((track,index)=>musicTrackCard(track,tracks,tracks.indexOf(track))).join("")}</div></section>`).join(""):`<div class="panel muted">No music imported yet. Paste a Spotify track, album, playlist, or artist URL above.</div>`;
|
||
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=`<div class="error">${escapeHtml(error.message)}</div>`;}
|
||
}
|
||
|
||
|
||
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=`
|
||
<div class="music-import-job-toolbar">
|
||
<strong>Spotify imports</strong>
|
||
<button type="button" id="musicImportJobsClear">Clear finished</button>
|
||
</div>
|
||
${jobs.map(job=>`
|
||
<div class="music-import-job music-import-job-${escapeAttribute(job.status||"")}">
|
||
<div>
|
||
<strong>${escapeHtml(job.query||"Spotify import")}</strong>
|
||
<div class="muted">
|
||
${escapeHtml(job.status||"")} · ${escapeHtml(job.message||"")}
|
||
</div>
|
||
${job.error?`<div class="error">${escapeHtml(job.error)}</div>`:""}
|
||
</div>
|
||
<div class="music-import-job-counts">
|
||
${job.resolved||0} resolved ·
|
||
${job.inserted||0} new ·
|
||
${job.updated||0} updated ·
|
||
${job.repaired||0} metadata repaired
|
||
</div>
|
||
</div>
|
||
`).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=`<div class="error">${escapeHtml(error.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
async function showMusicLibrary(){
|
||
musicImportJobsInitialized=false;
|
||
clearScanPolling();resetLibraryContext();ensureMusicStyles();ensureMusicPlayer();
|
||
breadcrumb.innerHTML=`Libraries › Music`; toolbar.innerHTML=""; installTopNav("home");
|
||
content.innerHTML=`<section class="music-library-page">
|
||
<div class="music-page-header">
|
||
<div><h2>Music</h2><div class="muted">Cached audio files are discovered automatically. Spotify enriches metadata when the match is confident.</div></div>
|
||
<div class="music-page-tools"><div id="musicCacheStatus" class="music-cache-status">Loading cache…</div></div>
|
||
</div>
|
||
<details class="kronic-music-tools"><summary>Scan music folder</summary><div class="kronic-music-tool-content"><button id="musicReconcileButton" type="button">Scan Music Folder</button></div></details>
|
||
<details class="kronic-music-tools"><summary>Add music / Spotify import</summary>
|
||
<form id="musicImportForm" class="music-import-form"><input id="musicImportInput" placeholder="Paste Spotify track, album, playlist, or artist URL…" autocomplete="off"><button class="primary" type="submit">Add to Music</button></form>
|
||
<div id="musicImportStatus" class="muted"></div><div id="musicImportJobs" class="music-import-jobs"></div></details>
|
||
<form id="musicFilterForm" class="music-filter-form"><input id="musicFilterInput" type="search" placeholder="Filter music…"><button type="submit">Search</button><button id="musicFilterClear" type="button">Clear</button></form>
|
||
<div id="musicTrackArea"></div>
|
||
</section>`;
|
||
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='<button type="button" data-mobile-size="minus" aria-label="Shrink player">−</button><button type="button" data-mobile-size="plus" aria-label="Enlarge player">+</button><button type="button" data-mobile-size="fit" aria-label="Fit player to screen">Fit</button><span class="kronic-mobile-resize-grip" role="slider" tabindex="0" aria-label="Resize player" aria-valuemin="45" aria-valuemax="100" aria-valuenow="95">◢</span>';
|
||
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);}
|
||
}
|