(() => { const tokenEl = document.getElementById("token"); const rowsEl = document.getElementById("rows"); const listMsg = document.getElementById("list-msg"); const formMsg = document.getElementById("form-msg"); const uptimeEl = document.getElementById("uptime"); const agentsEl = document.getElementById("agents-status"); const dlg = document.getElementById("edit-dlg"); const editForm = document.getElementById("edit-form"); const toastEl = document.getElementById("toast"); tokenEl.value = localStorage.getItem("streamd_token") || ""; tokenEl.addEventListener("change", () => { localStorage.setItem("streamd_token", tokenEl.value.trim()); connectUIWS(); }); function token() { return tokenEl.value.trim(); } function headers(json) { const h = {}; if (json) h["Content-Type"] = "application/json"; const t = token(); if (t) h["Authorization"] = "Bearer " + t; return h; } async function api(path, opts = {}) { const res = await fetch(path, opts); const text = await res.text(); let data = null; try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; } if (!res.ok) { const msg = (data && data.error) || res.statusText || "request failed"; throw new Error(msg); } return data; } function age(s) { if (s == null || s === 0) return "—"; return Number(s).toFixed(1) + "s"; } function absURL(path) { if (!path) return ""; try { return new URL(path, location.origin).href; } catch { return path; } } let toastTimer = null; function toast(msg) { if (!toastEl) return; toastEl.hidden = false; toastEl.classList.add("show"); toastEl.textContent = msg; clearTimeout(toastTimer); toastTimer = setTimeout(() => { toastEl.hidden = true; toastEl.classList.remove("show"); }, 1800); } async function copyText(text) { if (!text) return; try { await navigator.clipboard.writeText(text); toast("Copied m3u8 link"); } catch { const ta = document.createElement("textarea"); ta.value = text; ta.style.position = "fixed"; ta.style.left = "-9999px"; document.body.appendChild(ta); ta.select(); try { document.execCommand("copy"); toast("Copied m3u8 link"); } catch { toast("Copy failed"); } ta.remove(); } } function claimLabel(s) { if (!s.claimed_by) return '—'; let exp = ""; if (s.claim_expires_at) { const ms = Date.parse(s.claim_expires_at) - Date.now(); if (!Number.isNaN(ms)) { exp = ms > 0 ? ` (${Math.ceil(ms / 1000)}s)` : " (expired)"; } } return `${esc(s.claimed_by)}${esc(exp)}`; } function enabledVariants(s) { const list = Array.isArray(s.variants) ? s.variants : []; const enabled = list.filter((v) => v && v.enabled !== false && v.health !== "off"); if (enabled.length) return enabled; return [{ id: "fhd", label: "FHD", enabled: true, height: 0, play_path: s.play_path || ("/hls/" + s.name + "/index.m3u8"), health: s.health || "stopped", playlist_age_s: s.playlist_age_s, }]; } function linksCell(s) { const vars = enabledVariants(s); return ``; } function render(streams) { if (!streams.length) { rowsEl.innerHTML = ""; listMsg.textContent = "No streams yet. Add one above."; return; } listMsg.textContent = streams.length + " stream(s)"; rowsEl.innerHTML = streams.map((s) => { const need = !s.mpd ? " needs MPD" : ""; return ` ${esc(s.name)}
${esc(s.title || "")}${need}
${esc(s.app)} / ${esc(s.channel)} ${esc(s.health || "stopped")} ${claimLabel(s)} ${age(s.playlist_age_s)} ${linksCell(s)} ${s.claimed_by ? `` : ""} `; }).join(""); } function esc(v) { return String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function readVariantToggles(root) { const cards = root.querySelectorAll(".variant-card input[data-id]"); const out = []; cards.forEach((input) => { const id = input.dataset.id; const height = Number(input.dataset.height || 0); const enabled = id === "fhd" ? true : !!input.checked; const item = { id, label: id.toUpperCase(), enabled, height: id === "fhd" ? 0 : height, }; if (height > 0) { item.video_bitrate = input.dataset.vbr || ""; item.audio_bitrate = input.dataset.abr || ""; } out.push(item); }); return out; } function setVariantToggles(root, variants) { const byId = {}; (variants || []).forEach((v) => { byId[v.id] = v; }); root.querySelectorAll(".variant-card input[data-id]").forEach((input) => { const id = input.dataset.id; if (id === "fhd") { input.checked = true; return; } const v = byId[id]; input.checked = !!(v && v.enabled); const card = input.closest(".variant-card"); if (card) card.classList.toggle("on", input.checked); }); } function wireVariantCards(root) { root.querySelectorAll(".variant-card").forEach((card) => { const input = card.querySelector("input[type=checkbox]"); if (!input || input.disabled) { card.classList.add("on"); return; } const sync = () => card.classList.toggle("on", input.checked); input.addEventListener("change", sync); sync(); }); } wireVariantCards(document.getElementById("create-variants")); wireVariantCards(document.getElementById("edit-variants")); function renderAgents(list) { if (!agentsEl) return; if (!list || !list.length) { agentsEl.textContent = "agents: none connected"; return; } agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", "); } const depsEl = document.getElementById("deps-status"); function renderDeps(d) { if (!depsEl || !d) return; const bit = (label, path) => (path ? label + "✓" : label + "✗"); depsEl.textContent = [ bit("ffmpeg", d.ffmpeg), bit("nre", d.nre), bit("mp4decrypt", d.mp4decrypt), ].join(" · "); depsEl.title = [ "bin: " + (d.bin_dir || ""), "ffmpeg: " + (d.ffmpeg || "(missing)"), "nre: " + (d.nre || "(missing)"), "mp4decrypt: " + (d.mp4decrypt || "(missing)"), ...(d.notes || []), ].join("\n"); } async function refresh() { try { const [health, list, agents] = await Promise.all([ api("/api/health"), api("/api/streams"), api("/api/agents").catch(() => ({ agents: [] })), ]); uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s"; renderDeps(health.deps); render(list.streams || []); renderAgents(agents.agents || []); listMsg.classList.remove("err"); } catch (e) { listMsg.textContent = e.message; listMsg.classList.add("err"); } } const appSel = document.getElementById("app-select"); const chanSel = document.getElementById("channel-select"); let apps = []; function fillChannels() { const a = apps.find((x) => x.name === appSel.value); chanSel.innerHTML = ""; if (!a || !a.channels.length) { const o = document.createElement("option"); o.value = ""; o.textContent = a ? "(no module.yaml — no channels)" : "(no apps)"; chanSel.appendChild(o); return; } for (const ch of a.channels) { const o = document.createElement("option"); o.value = ch.id; o.textContent = ch.label && ch.label !== ch.id ? ch.id + " — " + ch.label : ch.id; chanSel.appendChild(o); } } async function loadApps() { try { const data = await api("/api/apps"); apps = data.apps || []; } catch (e) { apps = []; } appSel.innerHTML = ""; if (!apps.length) { const o = document.createElement("option"); o.value = ""; o.textContent = "(no app modules compiled in)"; appSel.appendChild(o); } for (const a of apps) { const o = document.createElement("option"); o.value = a.name; o.textContent = a.name; appSel.appendChild(o); } fillChannels(); } appSel.addEventListener("change", fillChannels); loadApps(); document.getElementById("refresh").addEventListener("click", refresh); document.getElementById("create-form").addEventListener("submit", async (ev) => { ev.preventDefault(); formMsg.textContent = ""; formMsg.classList.remove("err"); const fd = new FormData(ev.target); const body = Object.fromEntries(fd.entries()); body.variants = readVariantToggles(document.getElementById("create-variants")); try { await api("/api/streams", { method: "POST", headers: headers(true), body: JSON.stringify(body), }); ev.target.reset(); ev.target.headers_json.value = "{}"; setVariantToggles(document.getElementById("create-variants"), [ { id: "fhd", enabled: true }, { id: "hd", enabled: false }, { id: "sd", enabled: false }, ]); fillChannels(); formMsg.textContent = "Created."; refresh(); } catch (e) { formMsg.textContent = e.message; formMsg.classList.add("err"); } }); rowsEl.addEventListener("click", async (ev) => { const btn = ev.target.closest("button[data-act]"); if (!btn) return; const act = btn.dataset.act; if (act === "copy-link") { copyText(btn.dataset.url || ""); return; } const id = btn.dataset.id; try { if (act === "delete") { if (!confirm("Delete stream #" + id + "?")) return; await api("/api/streams/" + id, { method: "DELETE", headers: headers(false) }); } else if (act === "unclaim") { await api("/api/streams/" + id + "/claim/release", { method: "POST", headers: headers(true), body: JSON.stringify({ agent_id: "" }), }); } else if (act === "edit") { const st = await api("/api/streams/" + id); editForm.id.value = st.id; editForm.title.value = st.title || ""; editForm.channel.value = st.channel || ""; editForm.mpd.value = st.mpd || ""; editForm.key.value = st.key || ""; if (editForm.proxy) editForm.proxy.value = st.proxy || ""; editForm.headers_json.value = st.headers_json || "{}"; setVariantToggles(document.getElementById("edit-variants"), st.variants || []); dlg.showModal(); return; } else { await api("/api/streams/" + id + "/" + act, { method: "POST", headers: headers(false), }); } refresh(); } catch (e) { listMsg.textContent = e.message; listMsg.classList.add("err"); } }); document.getElementById("edit-cancel").addEventListener("click", () => dlg.close()); editForm.addEventListener("submit", async (ev) => { ev.preventDefault(); const id = editForm.id.value; const body = { title: editForm.title.value, channel: editForm.channel.value, mpd: editForm.mpd.value, key: editForm.key.value, proxy: editForm.proxy ? editForm.proxy.value : "", headers_json: editForm.headers_json.value, variants: readVariantToggles(document.getElementById("edit-variants")), }; try { await api("/api/streams/" + id, { method: "PATCH", headers: headers(true), body: JSON.stringify(body), }); dlg.close(); refresh(); } catch (e) { alert(e.message); } }); let uiWS = null; let uiWSTimer = null; function connectUIWS() { if (uiWS) { try { uiWS.close(); } catch {} uiWS = null; } const proto = location.protocol === "https:" ? "wss:" : "ws:"; const ws = new WebSocket(proto + "//" + location.host + "/ws/ui"); uiWS = ws; ws.onmessage = (ev) => { try { const msg = JSON.parse(ev.data); if (msg.type === "agents" || msg.type === "agent_online" || msg.type === "agent_offline") { renderAgents(msg.agents || []); } if (msg.type === "claims_changed" || msg.type === "agent_offline") { refresh(); } } catch {} }; ws.onclose = () => { clearTimeout(uiWSTimer); uiWSTimer = setTimeout(connectUIWS, 3000); }; } refresh(); connectUIWS(); setInterval(refresh, 5000); })();