// One stream: everything about it on a single page. import { el, pill, setText, toast, confirmDialog, sparkline, fmtBitrate, fmtSeconds, fmtAge, fmtDateTime, fmtRelative, copyText, absURL, clear, append, openModal, } from "../util.js"; import { state, subscribe, refresh, canEdit, isAdmin, streamById } from "../store.js"; import { api } from "../api.js"; import { publishLinks, variantEditor, outputEditor, player, previewChoices, timeline } from "../components.js"; import { daysLabel } from "./dashboard.js"; export function streamView(root, id, tab = "live") { const activeTab = ["live", "config", "debug"].includes(tab) ? tab : "live"; const titleRow = el("div.card-head"); const statRow = el("div.tiles"); const linksBox = el("div"); const playerBox = el("div"); const chartBox = el("div.stack"); const eventsBox = el("div"); const logBox = el("div"); const schedBox = el("div"); const configBox = el("div"); const livePanel = el("div.stack", el("div.card", el("div.card-head", el("h2", { text: "Publish endpoints" })), linksBox, ), el("div.card", el("div.card-head", el("h2", { text: "Preview" })), playerBox, ), ); const configPanel = el("div.stack", el("div.card", el("div.card-head", el("h2", { text: "Configuration" }), el("span.spacer"), isAdmin() ? el("button.danger.sm", { text: "Delete stream", onclick: () => remove() }) : null, ), configBox, ), el("div.card", el("div.card-head", el("h2", { text: "Schedule" })), schedBox, ), ); const debugPanel = el("div.stack", el("div.card", el("div.card-head", el("h2", { text: "Health" })), chartBox, ), el("div.card", el("div.card-head", el("h2", { text: "Timeline" })), eventsBox, ), el("div.card", el("div.card-head", el("h2", { text: "Logs" })), logBox, ), ); const tabNav = el("nav.tabs", el("a", { href: `#/stream/${id}`, class: activeTab === "live" ? "active" : "", text: "Live", }), el("a", { href: `#/stream/${id}/config`, class: activeTab === "config" ? "active" : "", text: "Config", }), el("a", { href: `#/stream/${id}/debug`, class: activeTab === "debug" ? "active" : "", text: "Debug", }), ); livePanel.hidden = activeTab !== "live"; configPanel.hidden = activeTab !== "config"; debugPanel.hidden = activeTab !== "debug"; root.append(el("div.stack", el("div.card", titleRow, statRow), tabNav, livePanel, configPanel, debugPanel, )); let currentPlayer = null; let detail = null; function paintHeader() { const s = detail || streamById(id); if (!s) { clear(titleRow); titleRow.append(el("h2", { text: "Stream not found" })); return; } clear(titleRow); append(titleRow, [ el("div", el("h2", { text: s.title || s.name }), el("div.sub.mono", { text: s.name }), ), pill(s.health || "stopped"), s.enabled === false ? pill("out of service", "off") : null, s.on_demand ? pill("on-demand", "tag") : null, s.public === false ? pill("private", "tag") : null, el("span.spacer"), canEdit() ? el("div.row", el("button.sm", { text: "Start", onclick: () => act("start") }), el("button.ghost.sm", { text: "Stop", onclick: () => act("stop") }), el("button.ghost.sm", { text: "Restart", onclick: () => act("restart") }), el("button.ghost.sm", { text: "Refresh keys", title: "Ask connected agents to capture fresh credentials now", onclick: requestCapture, }), el("button.ghost.sm", { text: "Probe", title: "Fetch the manifest without starting anything", onclick: probe }), el("button.ghost.sm", { text: "Duplicate", onclick: duplicate }), ) : null, ]); clear(statRow); append(statRow, [ tile("Viewers", s.viewers ? String(s.viewers) : "0"), tile("Bitrate", fmtBitrate(s.bitrate_mbps)), tile("Uptime", s.uptime_s ? fmtSeconds(s.uptime_s) : "—"), tile("Playlist age", fmtAge(s.playlist_age_s)), tile("Credentials", s.needs_capture ? "stale" : (s.drm_required ? (s.key_valid ? "ok" : "missing") : "not needed"), s.needs_capture ? "warn" : ""), tile("PID", s.pid ? String(s.pid) : "—"), ]); if (s.last_error) { statRow.append(el("div.tile.down", el("div.k", { text: "Last error" }), el("div", { text: s.last_error, style: { fontSize: "12px", marginTop: "4px" } }), )); } linksBox.replaceChildren(publishLinks(s)); // Rebuild the preview when the published ladder changes (new FHD/HD/SD // links), so the quality picker stays in sync with Publish endpoints. const choices = previewChoices(s); const choiceKey = choices.map((c) => c.play_path).join("|"); if (!currentPlayer || currentPlayer._choiceKey !== choiceKey) { if (currentPlayer && currentPlayer.stop) currentPlayer.stop(); const preferred = choices.find((c) => c.master) || choices[0]; currentPlayer = player({ path: preferred ? preferred.play_path : (s.play_path || `/hls/${s.name}/index.m3u8`), choices, }); currentPlayer._choiceKey = choiceKey; playerBox.replaceChildren( currentPlayer, el("p.hint", { text: choices.length > 1 ? "Pick FHD / HD / SD (or ABR master), then Play preview. Copy any publish link for VLC or ffplay." : "Play preview uses the source playlist. Copy a publish link for VLC or ffplay.", }), ); } } function tile(label, value, cls) { return el(`div.tile${cls ? "." + cls : ""}`, el("div.k", { text: label }), el("div.v", { text: String(value), style: { fontSize: "18px" } }), ); } async function loadDetail() { try { detail = await api.stream(id); paintHeader(); paintConfig(); } catch (err) { clear(titleRow); titleRow.append(el("h2", { text: "Stream not found" }), el("p.hint", { text: err.message })); } } async function loadMetrics(window = "1h") { try { const d = await api.metrics(id, window); const points = d.metrics || []; clear(chartBox); const picker = el("div.row", el("span.muted", { text: "Window" }), ...["15m", "1h", "6h", "24h", "7d"].map((w) => el(`button.tiny${w === window ? "" : ".ghost"}`, { text: w, onclick: () => loadMetrics(w), })), el("span.spacer"), d.uptime_ratio !== undefined ? el("span.muted", { text: `healthy ${(d.uptime_ratio * 100).toFixed(1)}% of this window` }) : null, ); append(chartBox, [ picker, el("div", el("h3.muted", { text: "Bitrate (Mb/s)" }), sparkline(points, (p) => p.bitrate_mbps, { label: "bitrate" }), ), el("div", el("h3.muted", { text: "Viewers" }), sparkline(points, (p) => p.viewers, { label: "viewers", min: 1 }), ), el("div", el("h3.muted", { text: "Playlist age (s)" }), sparkline(points, (p) => p.playlist_age_s, { label: "playlist age", min: 10 }), ), points.length < 2 ? el("p.hint", { text: "Health samples are recorded every 5 seconds while the stream runs." }) : null, ]); } catch (err) { chartBox.replaceChildren(el("p.msg.err", { text: err.message })); } } async function loadEvents() { try { const d = await api.events(id, 120); eventsBox.replaceChildren(timeline(d.events || [])); } catch (err) { eventsBox.replaceChildren(el("p.msg.err", { text: err.message })); } } let logSource = "nre"; let logVariant = ""; let sse = null; function paintLogs() { clear(logBox); if (!canEdit()) { logBox.append(el("p.hint", { text: "Logs are available to operators." })); return; } const pre = el("pre.logbox", { text: "loading…" }); const follow = el("input", { type: "checkbox" }); const variants = ((detail && detail.variants) || []).filter((v) => v.enabled && v.id !== "fhd"); const varSel = el("select", { onchange: (e) => { logVariant = e.target.value; load(); }, }, el("option", { value: "", text: "source rung" }), ...variants.map((v) => el("option", { value: v.id, text: v.label || v.id, selected: logVariant === v.id })), ); append(logBox, [ el("div.row", el("span.muted", { text: "Source" }), ...[["nre", "downloader"], ["ffmpeg.err", "packager (stderr)"], ["ffmpeg.out", "packager (stdout)"]] .map(([val, label]) => el(`button.tiny${val === logSource ? "" : ".ghost"}`, { text: label, onclick: () => { logSource = val; paintLogs(); }, })), varSel, el("span.spacer"), el("label.inline-check", follow, el("span", { text: "Follow" })), el("button.tiny.ghost", { text: "Reload", onclick: () => load() }), ), pre, ]); follow.addEventListener("change", () => (follow.checked ? startFollow() : stopFollow())); async function load() { stopFollow(); follow.checked = false; try { const d = await api.logs(id, logSource, logVariant); setText(pre, d.exists ? (d.lines || "(empty)") : (d.note || "no log yet")); pre.scrollTop = pre.scrollHeight; } catch (err) { setText(pre, err.message); } } function startFollow() { stopFollow(); const q = new URLSearchParams({ source: logSource }); if (logVariant) q.set("variant", logVariant); sse = new EventSource(`/api/streams/${id}/logs/stream?${q}`); sse.addEventListener("log", (ev) => { const atBottom = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 40; pre.append(document.createTextNode(ev.data + "\n")); // Bound what the page holds; a busy stream would grow without limit. if (pre.childNodes.length > 4000) pre.removeChild(pre.firstChild); if (atBottom) pre.scrollTop = pre.scrollHeight; }); sse.addEventListener("note", (ev) => { pre.append(document.createTextNode(`\n${ev.data}\n`)); }); sse.onerror = () => { stopFollow(); follow.checked = false; toast("Live log tail disconnected", true); }; } function stopFollow() { if (sse) { sse.close(); sse = null; } } load(); } async function loadSchedules() { try { const d = await api.schedules(id); const list = d.schedules || []; clear(schedBox); if (!list.length) schedBox.append(el("div.empty", { text: "Nothing scheduled for this stream." })); else { const body = el("tbody"); for (const sc of list) { body.append(el("tr", el("td", pill(sc.action)), el("td", el("div", { text: sc.kind === "weekly" ? `${daysLabel(sc.days_mask)} at ${sc.time_of_day}` : "once" }), el("div.sub", { text: sc.kind === "weekly" ? sc.tz : fmtDateTime(sc.at_utc) }), ), el("td", el("div", { text: sc.enabled ? fmtRelative(sc.next_fire_at) : "disabled" }), el("div.sub", { text: sc.enabled ? fmtDateTime(sc.next_fire_at) : "" }), ), el("td", { text: sc.last_fired_at ? fmtDateTime(sc.last_fired_at) : "—" }), el("td.actions", canEdit() ? el("div.row", el("button.tiny.ghost", { text: sc.enabled ? "Disable" : "Enable", onclick: async () => { try { await api.patchSchedule(sc.id, { enabled: !sc.enabled }); loadSchedules(); } catch (err) { toast(err.message, true); } }, }), el("button.tiny.danger", { text: "Delete", onclick: async () => { if (!(await confirmDialog("Delete this schedule?", "", "Delete"))) return; try { await api.deleteSchedule(sc.id); loadSchedules(); } catch (err) { toast(err.message, true); } }, }), ) : null), )); } schedBox.append(el("div.table-wrap", el("table", el("thead", el("tr", el("th", { text: "Action" }), el("th", { text: "When" }), el("th", { text: "Next" }), el("th", { text: "Last fired" }), el("th", { text: "" }), )), body, ))); } if (canEdit()) { schedBox.append(el("div.row", { style: { marginTop: "12px" } }, el("button.sm", { text: "+ Add schedule", onclick: () => openScheduleDialog(id, loadSchedules) }), el("span.hint", { text: "Credentials are refreshed a few minutes before a scheduled start.", }), )); } } catch (err) { schedBox.replaceChildren(el("p.msg.err", { text: err.message })); } } function paintConfig() { const s = detail; if (!s) return; clear(configBox); if (!canEdit()) { configBox.append(el("p.hint", { text: "Configuration is editable by operators." })); return; } const title = el("input", { value: s.title || "" }); const desc = el("input", { value: s.description || "" }); const tags = el("input", { value: s.tags || "" }); const mpd = el("input", { value: s.mpd || "" }); const key = el("textarea", { rows: "3", placeholder: s.has_key ? "unchanged — type to replace" : "none", spellcheck: "false" }); const egress = el("select", el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress })); const proxy = el("input", { placeholder: s.has_proxy ? "unchanged — type to replace" : "none" }); const headers = el("input", { placeholder: s.has_headers ? "unchanged — type to replace" : "{}" }); const drm = el("select", ...[["auto", "Auto — infer from the key"], ["yes", "Encrypted — keys required"], ["no", "Clear — no keys needed"]] .map(([v, t]) => el("option", { value: v, text: t, selected: (s.drm_mode || "auto") === v })), ); const onDemand = el("input", { type: "checkbox", checked: !!s.on_demand }); const isPublic = el("input", { type: "checkbox", checked: s.public !== false }); const idle = el("input", { type: "number", value: s.idle_timeout_s || 300, min: "30", max: "86400" }); const enabled = el("input", { type: "checkbox", checked: !!s.enabled }); const hlsTime = el("input", { type: "number", min: "1", max: "30", placeholder: "inherit" }); const listSize = el("input", { type: "number", min: "1", max: "500", placeholder: "inherit" }); const videoSel = el("input", { value: s.video_select || "", placeholder: "for=best (blank = module default)" }); const audioSel = el("input", { value: s.audio_select || "", placeholder: "for=best (blank = module default)" }); const appSel = el("select"); const chanSel = el("select"); const rewriter = el("select", el("option", { value: "", text: "Inherit from module / none", selected: !s.rewriter }), ); try { const ps = JSON.parse(s.settings_json || "{}"); if (ps.hls_time) hlsTime.value = ps.hls_time; if (ps.hls_list_size) listSize.value = ps.hls_list_size; } catch { // settings_json is operator-entered; a bad value just means no override. } const variants = variantEditor(s.variants); const outputs = outputEditor(s.outputs); const msg = el("p.msg"); function fillChannels(apps) { clear(chanSel); const a = (apps || []).find((x) => x.name === appSel.value); if (a && a.channels && a.channels.length) { append(chanSel, a.channels.map((c) => el("option", { value: c.id, text: c.label && c.label !== c.id ? `${c.id} — ${c.label}` : c.id, selected: s.channel === c.id, }))); if (s.channel && !a.channels.some((c) => c.id === s.channel)) { chanSel.append(el("option", { value: s.channel, text: `${s.channel} (stored)`, selected: true })); } return; } chanSel.append(el("option", { value: "", text: a ? "(module declares no channels)" : "(none)", selected: !s.channel, })); if (s.channel) { chanSel.append(el("option", { value: s.channel, text: `${s.channel} (stored)`, selected: true })); } } // Load module/channel/rewriter pickers asynchronously; paint the rest now. (async () => { let apps = []; let rewriters = []; try { const d = await api.apps(); apps = d.apps || []; rewriters = d.rewriters || []; } catch { // Pickers stay empty; free-text overrides still work via stored values. } clear(appSel); append(appSel, [ el("option", { value: "", text: "(none)", selected: !s.app }), ...apps.map((a) => el("option", { value: a.name, text: a.name, selected: s.app === a.name })), ]); if (s.app && !apps.some((a) => a.name === s.app)) { appSel.append(el("option", { value: s.app, text: `${s.app} (stored)`, selected: true })); } appSel.onchange = () => fillChannels(apps); fillChannels(apps); for (const n of rewriters) { rewriter.append(el("option", { value: n, text: n, selected: s.rewriter === n })); } if (s.rewriter && !rewriters.includes(s.rewriter)) { rewriter.append(el("option", { value: s.rewriter, text: `${s.rewriter} (stored)`, selected: true })); } try { const eg = await api.egress(); clear(egress); egress.append(el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress })); for (const p of eg.profiles || []) { egress.append(el("option", { value: p.name, text: `${p.name} (${p.kind}${p.status ? ", " + p.status : ""})`, selected: s.egress === p.name, })); } if (s.egress && !(eg.profiles || []).some((p) => p.name === s.egress)) { egress.append(el("option", { value: s.egress, text: `${s.egress} (stored)`, selected: true })); } } catch { // Older servers without /api/egress. } })(); const revealBtn = el("button.ghost.sm", { type: "button", text: "Reveal stored credentials", onclick: async () => { try { const full = await api.stream(id, true); key.value = full.key || ""; proxy.value = full.proxy || ""; headers.value = full.headers_json || "{}"; revealBtn.remove(); toast("Revealed — this was recorded in the audit log"); } catch (err) { toast(err.message, true); } }, }); const form = el("form", el("div.grid", el("label", el("span.lbl", { text: "Title" }), title), el("label", el("span.lbl", { text: "Tags" }), tags), el("label.span2", el("span.lbl", { text: "Description" }), desc), el("label", el("span.lbl", { text: "App module" }), appSel), el("label", el("span.lbl", { text: "Channel" }), chanSel), el("label", el("span.lbl", { text: "Rewriter" }), rewriter), el("label", el("span.lbl", { text: "Encryption" }), drm), el("label", el("span.lbl", { text: "Video select" }), videoSel), el("label", el("span.lbl", { text: "Audio select" }), audioSel), el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd), el("label.span2", el("span.lbl", { text: "Keys" }), key), el("label", el("span.lbl", { text: "Egress tunnel" }), egress), el("label", el("span.lbl", { text: "Origin proxy URL" }), proxy), el("label", el("span.lbl", { text: "Headers JSON" }), headers), el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle), el("label", el("span.lbl", { text: "Segment seconds" }), hlsTime), el("label", el("span.lbl", { text: "Playlist length" }), listSize), el("label.inline-check", enabled, el("span", { text: "Enabled" })), el("label.inline-check", onDemand, el("span", { text: "Start on demand" })), el("label.inline-check", isPublic, el("span", { text: "Publicly fetchable" })), ), el("div.row", { style: { marginTop: "8px" } }, revealBtn, el("span.hint", { text: "Credentials are never sent to the browser unless you ask." })), el("div.stack", { style: { marginTop: "14px" } }, variants, outputs), msg, el("div.row.end", { style: { marginTop: "14px" } }, el("button", { type: "submit", text: "Save changes" }), ), ); form.addEventListener("submit", async (ev) => { ev.preventDefault(); msg.textContent = ""; msg.classList.remove("err"); const body = { title: title.value, description: desc.value, tags: tags.value, app: appSel.value, channel: chanSel.value, rewriter: rewriter.value, video_select: videoSel.value.trim(), audio_select: audioSel.value.trim(), mpd: mpd.value.trim(), drm_mode: drm.value, enabled: enabled.checked, on_demand: onDemand.checked, public: isPublic.checked, idle_timeout_s: parseInt(idle.value, 10) || 300, variants: variants.readValue(), outputs: outputs.readValue(), settings_json: JSON.stringify({ hls_time: parseInt(hlsTime.value, 10) || 0, hls_list_size: parseInt(listSize.value, 10) || 0, }), }; // Only send a credential when it was actually typed, so saving the form // does not wipe a key the browser was never given. body.egress = egress.value.trim(); if (key.value.trim()) body.key = key.value.trim(); if (proxy.value.trim()) body.proxy = proxy.value.trim(); if (headers.value.trim()) { try { JSON.parse(headers.value); } catch { msg.textContent = "Headers must be valid JSON."; msg.classList.add("err"); return; } body.headers_json = headers.value.trim(); } try { await api.patchStream(id, body); toast("Saved"); await loadDetail(); await refresh("save"); loadEvents(); } catch (err) { msg.textContent = err.message; msg.classList.add("err"); } }); configBox.append(form); } async function requestCapture() { try { const res = await api.capture(id); const n = res.agents_notified || 0; if (n > 0) toast(`Asked ${n} agent(s) to refresh credentials`); else toast("No agents connected — capture was queued for when one appears", true); loadEvents(); await refresh("capture"); } catch (err) { toast(err.message, true); } } async function act(what) { const s = detail || streamById(id); if (what === "stop" && s && s.health === "ok") { if (!(await confirmDialog(`Stop ${s.title || s.name}?`, "Anyone watching will be disconnected.", "Stop"))) return; } try { await api.action(id, what); toast(what); await loadDetail(); await refresh("action"); loadEvents(); } catch (err) { toast(err.message, true); } } async function probe() { toast("Probing the origin…"); try { const r = await api.probe(id); openModal( el("h2", { text: r.ok ? "Manifest looks good" : "Probe failed" }), el("p", { text: r.summary || r.error || "" }), el("div.grid", { style: { marginTop: "12px" } }, kv("Status", r.status || "—"), kv("Kind", r.kind || "—"), kv("Round trip", `${r.elapsed_ms} ms`), kv("Size", `${r.bytes || 0} bytes`), kv("Live", r.live ? "yes" : "no"), kv("Encrypted", r.encrypted ? (r.drm_systems || []).join(", ") || "yes" : "no"), r.default_kid ? kv("Default KID", r.default_kid) : null, kv("Keys stored", r.have_keys ? "yes" : "no"), ), r.error ? el("p.msg.err", { text: r.error }) : null, el("div.row.end", { style: { marginTop: "14px" } }, el("button", { text: "Close", onclick: () => document.getElementById("modal").close() })), ); loadEvents(); } catch (err) { toast(err.message, true); } } function kv(k, v) { return el("div", el("div.k.muted", { text: k }), el("div.mono", { text: String(v) })); } async function duplicate() { const s = detail || streamById(id); const name = el("input", { value: `${s.name}-copy` }); const form = el("form", el("h2", { text: "Duplicate stream" }), el("p.hint", { text: "Everything is copied, including credentials. The copy starts disabled." }), el("label", { style: { marginTop: "10px" } }, el("span.lbl", { text: "New name" }), name), el("div.row.end", { style: { marginTop: "14px" } }, el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), el("button", { type: "submit", text: "Duplicate" }), ), ); form.addEventListener("submit", async (ev) => { ev.preventDefault(); try { const copy = await api.duplicate(id, { name: name.value.trim() }); close(); await refresh("duplicate"); location.hash = `#/stream/${copy.id}`; } catch (err) { toast(err.message, true); } }); const close = openModal(form); } async function remove() { const s = detail || streamById(id); if (!(await confirmDialog(`Delete ${s.name}?`, "The stream, its history and its schedules are removed. This cannot be undone.", "Delete permanently"))) return; try { await api.deleteStream(id); toast("Deleted"); await refresh("delete"); location.hash = "#/streams"; } catch (err) { toast(err.message, true); } } const off = subscribe(() => paintHeader()); loadDetail(); if (activeTab === "live" || activeTab === "debug") { loadMetrics("1h"); loadEvents(); } if (activeTab === "config") loadSchedules(); if (activeTab === "debug") paintLogs(); // Prefetch sibling tab data so switching feels instant after first visit. if (activeTab === "live") { loadSchedules(); } if (activeTab === "config") { loadEvents(); } const tick = setInterval(() => { if (activeTab === "debug" || activeTab === "live") { loadMetrics(currentWindow()); loadEvents(); } }, 30000); let lastWindow = "1h"; function currentWindow() { return lastWindow; } return () => { off(); clearInterval(tick); if (sse) sse.close(); if (currentPlayer) currentPlayer.stop(); }; } /** Dialog for adding a schedule to a stream. */ export function openScheduleDialog(streamID, onDone) { const action = el("select", el("option", { value: "start", text: "Start the stream" }), el("option", { value: "stop", text: "Stop the stream" }), ); const kind = el("select", { onchange: sync }, el("option", { value: "weekly", text: "Every week" }), el("option", { value: "once", text: "Once" }), ); const time = el("input", { type: "time", value: "19:00", required: true }); const at = el("input", { type: "datetime-local" }); const tz = el("select"); // Intl gives the browser's own zone; offer it first since it is almost // always the one an operator means. const localZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; for (const z of Array.from(new Set([localZone, "UTC", "Europe/Dublin", "Europe/London"]))) { tz.append(el("option", { value: z, text: z, selected: z === localZone })); } const days = [0, 1, 2, 3, 4, 5, 6].map((d) => el("input", { type: "checkbox", checked: d >= 1 && d <= 5 })); const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const dayRow = el("div.row", ...days.map((cb, i) => el("label.inline-check", cb, el("span", { text: dayNames[i] })))); const weeklyRows = el("div.stack", el("label", el("span.lbl", { text: "Time of day" }), time), el("label", el("span.lbl", { text: "Days" }), dayRow), ); const onceRow = el("label", el("span.lbl", { text: "Date and time" }), at); const msg = el("p.msg"); function sync() { weeklyRows.hidden = kind.value !== "weekly"; onceRow.hidden = kind.value !== "once"; } const form = el("form", el("h2", { text: "Add schedule" }), el("div.stack", { style: { marginTop: "12px" } }, el("label", el("span.lbl", { text: "Action" }), action), el("label", el("span.lbl", { text: "Repeat" }), kind), weeklyRows, onceRow, el("label", el("span.lbl", { text: "Timezone" }), tz), ), el("p.hint", { text: "Times are local to the chosen zone, so an event stays put across a clock change." }), msg, el("div.row.end", { style: { marginTop: "14px" } }, el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }), el("button", { type: "submit", text: "Add" }), ), ); sync(); form.addEventListener("submit", async (ev) => { ev.preventDefault(); msg.textContent = ""; msg.classList.remove("err"); const body = { action: action.value, kind: kind.value, tz: tz.value }; if (kind.value === "weekly") { let mask = 0; days.forEach((cb, i) => { if (cb.checked) mask |= 1 << i; }); if (!mask) { msg.textContent = "Pick at least one day."; msg.classList.add("err"); return; } body.days_mask = mask; body.time_of_day = time.value; } else { if (!at.value) { msg.textContent = "Pick a date and time."; msg.classList.add("err"); return; } // Send the local wall-clock value; the server reads it in the zone above. body.at_utc = at.value.replace("T", " "); } try { await api.createSchedule(streamID, body); close(); toast("Schedule added"); if (onDone) onDone(); } catch (err) { msg.textContent = err.message; msg.classList.add("err"); } }); const close = openModal(form); }