streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s

- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
404errordeveloper 2026-10-09 20:57:43 +02:00
parent b3955bd81e
commit 066e018749
113 changed files with 19002 additions and 1541 deletions

View file

@ -0,0 +1,562 @@
// Schedule overview, global settings, people and keys, and the audit log.
import {
el, pill, toast, confirmDialog, fmtDateTime, fmtRelative, copyText, clear, append, openModal, setText,
} from "../util.js";
import { state, isAdmin, canEdit, refresh } from "../store.js";
import { api } from "../api.js";
import { daysLabel } from "./dashboard.js";
import { openScheduleDialog } from "./stream.js";
// ---------- schedule overview ----------
export function scheduleView(root) {
const body = el("tbody");
const pick = el("select");
root.append(el("div.stack",
el("div.card",
el("div.card-head",
el("h2", { text: "All schedules" }),
el("span.spacer"),
canEdit() ? el("div.row",
pick,
el("button.sm", {
text: "+ Add schedule",
onclick: () => {
if (!pick.value) {
toast("Pick a stream first", true);
return;
}
openScheduleDialog(Number(pick.value), load);
},
}),
) : null,
),
el("p.hint", {
text: "A scheduled start enables the stream and brings it up; a scheduled stop takes it down. " +
"Credentials are refreshed a few minutes beforehand.",
}),
el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Stream" }), el("th", { text: "Action" }),
el("th", { text: "When" }), el("th", { text: "Next" }),
el("th", { text: "Last fired" }), el("th", { text: "" }),
)),
body,
)),
),
));
function fillStreams() {
const want = (state.streams || []).map((s) => `${s.id}:${s.name}`).join("|");
if (pick.dataset.opts === want) return;
pick.dataset.opts = want;
clear(pick);
append(pick, [
el("option", { value: "", text: "Choose a stream…" }),
...(state.streams || []).map((s) => el("option", { value: s.id, text: s.title || s.name })),
]);
}
async function load() {
fillStreams();
try {
const d = await api.allSchedules();
const list = d.schedules || [];
clear(body);
if (!list.length) {
body.append(el("tr", el("td.empty", { colspan: "6", text: "Nothing scheduled yet." })));
return;
}
for (const sc of list) {
body.append(el("tr",
el("td", el("a", { href: `#/stream/${sc.stream_id}`, text: sc.stream_name || `#${sc.stream_id}` })),
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 });
load();
} 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);
load();
} catch (err) {
toast(err.message, true);
}
},
}),
) : null),
));
}
} catch (err) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "6", text: err.message })));
}
}
load();
refresh("schedule");
return () => {};
}
// ---------- settings ----------
export function settingsView(root) {
const wrap = el("div.stack");
root.append(wrap);
async function load() {
clear(wrap);
if (!isAdmin()) {
wrap.append(el("div.card", el("p", { text: "Settings are administrator-only." })));
return;
}
let data;
try {
data = await api.settings();
} catch (err) {
wrap.append(el("div.card", el("p.msg.err", { text: err.message })));
return;
}
const vals = data.settings || {};
const field = (key, label, hint, attrs = {}) => {
const input = el("input", { value: vals[key] || "", placeholder: "default", ...attrs });
input.dataset.key = key;
return el("label", el("span.lbl", { text: label }), input, hint ? el("small.hint", { text: hint }) : null);
};
const form = el("form",
el("div.grid",
field("hls_time", "Segment seconds", "Shorter means lower latency and more requests.",
{ type: "number", min: "1", max: "30" }),
field("hls_list_size", "Playlist length", "How many segments stay in a live playlist.",
{ type: "number", min: "1", max: "500" }),
field("live_wait", "Downloader live wait", "Seconds the downloader waits before starting.",
{ type: "number", min: "0", max: "120" }),
field("ts_ready_bytes", "Buffer before packaging", "Bytes of muxed media to collect before probing.",
{ type: "number", min: "0" }),
field("idle_timeout_s", "Default idle timeout", "Applied to new streams when create omits idle_timeout_s.",
{ type: "number", min: "30", max: "86400" }),
field("default_on_demand", "Default on-demand", "true/false — applied when create omits on_demand."),
field("default_outputs", "Default outputs JSON", "JSON array of output specs for new streams that omit outputs."),
),
el("p.hint", {
text: "Blank means the built-in default. Packager knobs apply the next time a stream starts. " +
"On-demand / idle / outputs defaults apply when a new stream is created without those fields.",
}),
el("div.row.end", { style: { marginTop: "14px" } }, el("button", { type: "submit", text: "Save settings" })),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
const body = {};
for (const input of form.querySelectorAll("input[data-key]")) {
body[input.dataset.key] = input.value.trim();
}
try {
await api.saveSettings(body);
toast("Settings saved — applies at each stream's next start");
load();
} catch (err) {
toast(err.message, true);
}
});
const eff = data.effective || {};
wrap.append(
el("div.card", el("div.card-head", el("h2", { text: "Packaging defaults" })), form),
el("div.card",
el("div.card-head", el("h2", { text: "In effect now" })),
el("div.grid",
...Object.entries(eff).map(([k, v]) =>
el("div", el("div.k.muted", { text: k }), el("div.mono", { text: String(v || "built-in default") }))),
),
),
);
}
load();
return () => {};
}
// ---------- people and API keys ----------
export function peopleView(root) {
const usersBox = el("div");
const keysBox = el("div");
root.append(el("div.stack",
el("div.card",
el("div.card-head",
el("h2", { text: "People" }),
el("span.spacer"),
el("button.sm", { text: "+ Add person", onclick: () => openUserDialog(loadUsers) }),
),
el("p.hint", {
text: "Administrators manage people, keys and settings. Operators run and edit streams. " +
"Viewers can look but not touch, and never see credentials.",
}),
usersBox,
),
el("div.card",
el("div.card-head",
el("h2", { text: "API keys" }),
el("span.spacer"),
el("button.sm", { text: "+ New key", onclick: () => openKeyDialog(loadKeys) }),
),
el("p.hint", {
text: "Machine credentials, one per capture agent. The secret is shown once, " +
"on creation, and only its hash is stored.",
}),
keysBox,
),
));
if (!isAdmin()) {
clear(usersBox);
usersBox.append(el("p", { text: "Administrator-only." }));
return () => {};
}
async function loadUsers() {
try {
const d = await api.users();
const body = el("tbody");
for (const u of d.users || []) {
const self = state.me && state.me.user_id === u.id;
body.append(el("tr",
el("td",
el("div", { text: u.username }),
self ? el("div.sub", { text: "that is you" }) : null,
),
el("td", pill(u.role, "role")),
el("td", u.disabled ? pill("disabled") : pill("active", "ok")),
el("td", { text: u.last_login_at ? fmtDateTime(u.last_login_at) : "never" }),
el("td.actions", el("div.row",
el("select", {
onchange: async (e) => {
try {
await api.patchUser(u.id, { role: e.target.value });
toast("Role updated");
loadUsers();
} catch (err) {
toast(err.message, true);
loadUsers();
}
},
}, ...["viewer", "operator", "admin"].map((r) =>
el("option", { value: r, text: r, selected: u.role === r }))),
el("button.tiny.ghost", {
text: u.disabled ? "Enable" : "Disable",
onclick: async () => {
try {
await api.patchUser(u.id, { disabled: !u.disabled });
loadUsers();
} catch (err) {
toast(err.message, true);
}
},
}),
el("button.tiny.ghost", { text: "Password", onclick: () => openPasswordDialog(u, self) }),
el("button.tiny.danger", {
text: "Remove",
onclick: async () => {
if (!(await confirmDialog(`Remove ${u.username}?`,
"Their sessions end immediately.", "Remove"))) return;
try {
await api.deleteUser(u.id);
toast("Removed");
loadUsers();
} catch (err) {
toast(err.message, true);
}
},
}),
)),
));
}
usersBox.replaceChildren(el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Username" }), el("th", { text: "Role" }), el("th", { text: "Status" }),
el("th", { text: "Last signed in" }), el("th", { text: "" }),
)),
body,
)));
} catch (err) {
usersBox.replaceChildren(el("p.msg.err", { text: err.message }));
}
}
async function loadKeys() {
try {
const d = await api.apiKeys();
const body = el("tbody");
for (const k of d.api_keys || []) {
body.append(el("tr",
el("td", { text: k.name }),
el("td", pill(k.role, "role")),
el("td", k.revoked_at ? pill("revoked") : pill("active", "ok")),
el("td", { text: k.last_used_at ? fmtDateTime(k.last_used_at) : "never" }),
el("td.actions", k.revoked_at ? null : el("button.tiny.danger", {
text: "Revoke",
onclick: async () => {
if (!(await confirmDialog(`Revoke "${k.name}"?`,
"Any agent using it stops working immediately.", "Revoke"))) return;
try {
await api.revokeKey(k.id);
toast("Revoked");
loadKeys();
} catch (err) {
toast(err.message, true);
}
},
})),
));
}
if (!(d.api_keys || []).length) {
body.append(el("tr", el("td.empty", { colspan: "5", text: "No API keys yet." })));
}
keysBox.replaceChildren(el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Name" }), el("th", { text: "Role" }), el("th", { text: "Status" }),
el("th", { text: "Last used" }), el("th", { text: "" }),
)),
body,
)));
} catch (err) {
keysBox.replaceChildren(el("p.msg.err", { text: err.message }));
}
}
loadUsers();
loadKeys();
return () => {};
}
function openUserDialog(onDone) {
const username = el("input", { required: true, autocomplete: "off" });
const password = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" });
const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r })));
const msg = el("p.msg");
const form = el("form",
el("h2", { text: "Add person" }),
el("div.stack", { style: { marginTop: "12px" } },
el("label", el("span.lbl", { text: "Username" }), username),
el("label", el("span.lbl", { text: "Password" }), password,
el("small.hint", { text: "At least 8 characters." })),
el("label", el("span.lbl", { text: "Role" }), role),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Add" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
await api.createUser({ username: username.value.trim(), password: password.value, role: role.value });
close();
toast("Added");
if (onDone) onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
username.focus();
}
function openPasswordDialog(user, self) {
const current = el("input", { type: "password", autocomplete: "current-password" });
const next = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" });
const msg = el("p.msg");
const form = el("form",
el("h2", { text: `Change password for ${user.username}` }),
el("p.hint", {
text: self
? "You will be signed out, because changing a password ends every session for the account."
: "Their sessions end immediately.",
}),
el("div.stack", { style: { marginTop: "12px" } },
self ? el("label", el("span.lbl", { text: "Current password" }), current) : null,
el("label", el("span.lbl", { text: "New password" }), next),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Change" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
await api.setPassword(user.id, { current_password: current.value, password: next.value });
close();
if (self) {
toast("Password changed — sign in again");
setTimeout(() => location.reload(), 900);
} else {
toast("Password changed");
}
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
}
function openKeyDialog(onDone) {
const name = el("input", { required: true, placeholder: "phone-agent-01" });
const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r })));
const msg = el("p.msg");
const form = el("form",
el("h2", { text: "New API key" }),
el("p.hint", { text: "A capture agent needs the operator role." }),
el("div.stack", { style: { marginTop: "12px" } },
el("label", el("span.lbl", { text: "Name" }), name),
el("label", el("span.lbl", { text: "Role" }), role),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Create" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
const k = await api.createKey({ name: name.value.trim(), role: role.value });
// Replace this dialog in place — do not close() first. Closing raced the
// next openModal and wiped the secret box empty.
showSecret(k);
if (onDone) onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
name.focus();
}
function showSecret(key) {
const value = (key && (key.secret || key.token || key.key)) || "";
if (!value) {
openModal(
el("h2", { text: "Key created, but secret missing" }),
el("p.msg.err", {
text: "The server did not return the one-time secret. Check the streamd version, then revoke this key and create another.",
}),
el("div.row.end", { style: { marginTop: "14px" } },
el("button", { text: "Close", onclick: () => document.getElementById("modal").close() })),
);
return;
}
const secret = el("pre.logbox", { text: value, style: { maxHeight: "none" } });
const close = openModal(
el("h2", { text: `Key "${key.name || "agent"}" created` }),
el("p.hint", {
text: "Copy it now. Only a hash is stored, so this is the one and only time it is shown.",
}),
secret,
el("p.hint", { text: "In apps/agent/agent.yaml set: api_key: <the value above>" }),
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { text: "Copy", onclick: () => copyText(value, "API key") }),
el("button", { text: "Done", onclick: () => close() }),
),
);
}
// ---------- audit log ----------
export function auditView(root) {
const body = el("tbody");
const filter = el("input", { type: "search", placeholder: "Filter by actor…" });
root.append(el("div.card",
el("div.card-head",
el("h2", { text: "Audit log" }),
el("span.spacer"),
filter,
el("button.ghost.sm", { text: "Reload", onclick: () => load() }),
),
el("p.hint", { text: "Every change, who made it, and from where. Login attempts included." }),
el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "When" }), el("th", { text: "Actor" }), el("th", { text: "Action" }),
el("th", { text: "Status" }), el("th", { text: "From" }),
)),
body,
)),
));
let rows = [];
function paint() {
const q = filter.value.trim().toLowerCase();
const list = q ? rows.filter((e) => String(e.actor || "").toLowerCase().includes(q)) : rows;
clear(body);
if (!list.length) {
body.append(el("tr", el("td.empty", { colspan: "5", text: "Nothing recorded." })));
return;
}
for (const e of list) {
const bad = e.status >= 400;
body.append(el("tr",
el("td.mono", { text: fmtDateTime(e.at), title: e.at }),
el("td",
el("div", { text: e.actor || "anonymous" }),
el("div.sub", { text: e.actor_kind || "" }),
),
el("td",
el("div", { text: e.note || `${e.method} ${e.path}` }),
el("div.sub.mono", { text: `${e.method} ${e.path}` }),
),
el("td", pill(String(e.status), bad ? "down" : "ok")),
el("td.mono", { text: e.ip || "—" }),
));
}
}
async function load() {
if (!isAdmin()) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "5", text: "Administrator-only." })));
return;
}
try {
const d = await api.audit(300);
rows = d.audit || [];
paint();
} catch (err) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "5", text: err.message })));
}
}
filter.addEventListener("input", paint);
load();
return () => {};
}
export { setText };

View file

@ -0,0 +1,180 @@
// Dashboard: the headline numbers, what is scheduled next, and recent events.
import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js";
import { state, subscribe, refresh } from "../store.js";
import { timeline } from "../components.js";
export function dashboard(root) {
const alarmTiles = el("div.tiles");
const trafficTiles = el("div.tiles");
const upcomingBody = el("tbody");
const feed = el("div");
const attention = el("div.stack");
root.append(el("div.stack",
el("div.tile-band",
el("div.tile-band-label", { text: "Alarms" }),
alarmTiles,
),
el("div.tile-band",
el("div.tile-band-label", { text: "Traffic" }),
trafficTiles,
),
el("div.card",
el("div.card-head", el("h2", { text: "Needs attention" })),
attention,
),
el("div.card",
el("div.card-head",
el("h2", { text: "Coming up" }),
el("span.spacer"),
el("a", { href: "#/schedule", text: "Manage schedule" }),
),
el("div.table-wrap",
el("table",
el("thead", el("tr",
el("th", { text: "When" }),
el("th", { text: "Stream" }),
el("th", { text: "Action" }),
el("th", { text: "Repeats" }),
)),
upcomingBody,
),
),
),
el("div.card",
el("div.card-head", el("h2", { text: "Recent activity" })),
feed,
),
));
function paint() {
const t = (state.overview && state.overview.totals) || {};
const streams = state.streams || [];
const counts = {
streams: t.streams ?? streams.length,
running: t.running ?? streams.filter((s) => s.health === "ok").length,
down: t.down ?? streams.filter((s) => s.health === "down").length,
starting: t.starting ?? streams.filter((s) => s.health === "starting").length,
idle: t.ondemand_idle ?? 0,
viewers: t.viewers ?? 0,
capture: t.needs_capture ?? 0,
};
reconcile(alarmTiles,
[
{ k: "down", label: "Down", v: counts.down, cls: counts.down ? "down alarm" : "" },
{ k: "capture", label: "Need credentials", v: counts.capture, cls: counts.capture ? "warn alarm" : "" },
{ k: "starting", label: "Starting", v: counts.starting, cls: counts.starting ? "warn alarm" : "" },
],
(d) => d.k,
(d) => el(`div.tile${d.cls ? "." + d.cls.split(" ").join(".") : ""}`,
el("div.k", { text: d.label }),
el("div.v", { text: String(d.v) }),
),
(node, d) => {
node.className = `tile${d.cls ? " " + d.cls : ""}`;
setText(node.querySelector(".v"), String(d.v));
},
);
reconcile(trafficTiles,
[
{ k: "live", label: "Live now", v: counts.running, cls: counts.running ? "ok" : "" },
{ k: "viewers", label: "Viewers", v: counts.viewers, cls: "" },
{ k: "idle", label: "On-demand idle", v: counts.idle, cls: "" },
{ k: "total", label: "Streams", v: counts.streams, cls: "" },
],
(d) => d.k,
(d) => el(`div.tile${d.cls ? "." + d.cls.split(" ").join(".") : ""}`,
el("div.k", { text: d.label }),
el("div.v", { text: String(d.v) }),
),
(node, d) => {
node.className = `tile${d.cls ? " " + d.cls : ""}`;
setText(node.querySelector(".v"), String(d.v));
},
);
// Needs attention: anything down, or enabled but missing credentials.
const problems = streams.filter(
(s) => s.health === "down" || (s.enabled && s.needs_capture),
);
if (!problems.length) {
reconcile(attention, [{ id: "none" }], (x) => x.id,
() => el("div.empty",
el("p", { text: "Everything looks healthy." }),
el("p", el("a", { href: "#/streams", text: "View all streams" })),
), () => {});
} else {
reconcile(attention, problems, (s) => s.id,
(s) => el("div.row",
el("a", { href: `#/stream/${s.id}`, text: s.title || s.name, class: "grow" }),
el("span.spacer"),
el("span.sub.reason"),
el("span.st"),
),
(node, s) => {
const a = node.querySelector("a");
a.href = `#/stream/${s.id}`;
setText(a, s.title || s.name);
setText(node.querySelector(".reason"),
s.needs_capture ? "needs fresh credentials" : (s.last_error || ""));
const st = node.querySelector(".st");
st.replaceChildren(pill(s.health || "stopped"));
},
);
}
const upcoming = (state.overview && state.overview.upcoming) || [];
if (!upcoming.length) {
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
() => el("tr", el("td.empty", { colspan: "4", text: "Nothing scheduled." })), () => {});
} else {
reconcile(upcomingBody, upcoming, (s) => s.id,
() => el("tr", el("td.when"), el("td.who"), el("td.act"), el("td.rep")),
(tr, s) => {
const when = tr.querySelector(".when");
when.replaceChildren(
el("div", { text: fmtRelative(s.next_fire_at) }),
el("div.sub", { text: fmtDateTime(s.next_fire_at) }),
);
const who = tr.querySelector(".who");
who.replaceChildren(el("a", {
href: `#/stream/${s.stream_id}`, text: s.stream_name || `#${s.stream_id}`,
}));
tr.querySelector(".act").replaceChildren(pill(s.action));
setText(tr.querySelector(".rep"),
s.kind === "weekly" ? `${daysLabel(s.days_mask)} ${s.time_of_day} ${s.tz}` : "once");
},
);
}
const events = (state.overview && state.overview.recent_events) || [];
feed.replaceChildren(timeline(events.map((e) => ({
...e,
message: e.stream_name ? `${e.stream_name}: ${e.message}` : e.message,
}))));
}
const off = subscribe(paint);
paint();
refresh("dashboard");
// Keep the relative times honest without a full refetch.
const tick = setInterval(paint, 30000);
return () => {
off();
clearInterval(tick);
};
}
const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export function daysLabel(mask) {
const bits = Number(mask) || 0;
if (!bits) return "—";
if (bits === 0x7f) return "every day";
const days = [];
for (let i = 0; i < 7; i++) if (bits & (1 << i)) days.push(DAY_NAMES[i]);
return days.join(", ");
}

View file

@ -0,0 +1,263 @@
// Stepped full-page create flow: Basics → Source → Outputs → Review.
import {
el, clear, append, toast, setText, withBusy,
} from "../util.js";
import { api } from "../api.js";
import { refresh, canEdit } from "../store.js";
import { variantEditor, outputEditor } from "../components.js";
const STEPS = ["Basics", "Source", "Outputs", "Review"];
export function streamCreate(root) {
if (!canEdit()) {
root.append(el("div.card",
el("h2", { text: "Not available" }),
el("p.hint", { text: "Operators and admins can create streams." }),
));
return;
}
let step = 0;
let apps = [];
const name = el("input", { name: "name", required: true, placeholder: "city-news", maxlength: "64" });
const title = el("input", { name: "title", placeholder: "City News" });
const appSel = el("select", { onchange: fillChannels },
el("option", { value: "", text: "(none)" }));
const chanSel = el("select");
const tags = el("input", { placeholder: "council, sports" });
const onDemand = el("input", { type: "checkbox" });
const enabled = el("input", { type: "checkbox", checked: true });
const isPublic = el("input", { type: "checkbox", checked: true });
const mpd = el("input", { placeholder: "https://…/manifest.mpd" });
const key = el("textarea", { rows: "3", placeholder: "KID:KEY per line — leave empty for clear streams", spellcheck: "false" });
const proxy = el("input", { placeholder: "socks5://127.0.0.1:1080 (optional)" });
const headers = el("input", { value: "{}" });
const idle = el("input", { type: "number", value: "300", min: "30", max: "86400" });
const drm = el("select",
el("option", { value: "auto", text: "Auto — infer from the key" }),
el("option", { value: "yes", text: "Encrypted — keys required" }),
el("option", { value: "no", text: "Clear — no keys needed" }),
);
const rewriter = el("select",
el("option", { value: "", text: "Inherit from module / none" }),
);
const videoSel = el("input", { placeholder: "for=best (blank = module default)" });
const audioSel = el("input", { placeholder: "for=best (blank = module default)" });
const variants = variantEditor(null);
const outputs = outputEditor(null);
const stepNav = el("div.wizard-steps");
const panel = el("div");
const msg = el("p.msg");
const backBtn = el("button.ghost", { type: "button", text: "Back", onclick: () => go(step - 1) });
const nextBtn = el("button", { type: "button", text: "Next", onclick: () => go(step + 1) });
const skipBtn = el("button.ghost", {
type: "button",
text: "Use defaults → Review",
onclick: () => go(3),
});
const createBtn = el("button", { type: "button", text: "Create stream", onclick: (ev) => submit(ev.currentTarget) });
const cancelBtn = el("button.ghost", {
type: "button", text: "Cancel",
onclick: () => { location.hash = "#/streams"; },
});
const footLeft = el("div.row");
const footRight = el("div.row");
root.append(el("div.card",
el("div.card-head",
el("h2", { text: "Add stream" }),
el("span.spacer"),
el("a", { href: "#/streams", text: "Back to list" }),
),
stepNav,
panel,
msg,
el("div.wizard-foot", footLeft, el("span.spacer"), footRight),
));
function fillChannels() {
clear(chanSel);
const a = apps.find((x) => x.name === appSel.value);
if (!a || !a.channels || !a.channels.length) {
chanSel.append(el("option", { value: "", text: a ? "(module declares no channels)" : "(none)" }));
return;
}
append(chanSel, a.channels.map((c) =>
el("option", { value: c.id, text: c.label && c.label !== c.id ? `${c.id} — ${c.label}` : c.id })));
}
function body() {
return {
name: name.value.trim(),
title: title.value.trim(),
app: appSel.value,
channel: chanSel.value,
mpd: mpd.value.trim(),
key: key.value.trim(),
proxy: proxy.value.trim(),
headers_json: headers.value.trim() || "{}",
tags: tags.value,
drm_mode: drm.value,
rewriter: rewriter.value,
video_select: videoSel.value.trim(),
audio_select: audioSel.value.trim(),
enabled: enabled.checked,
on_demand: onDemand.checked,
public: isPublic.checked,
idle_timeout_s: parseInt(idle.value, 10) || 300,
variants: variants.readValue(),
outputs: outputs.readValue(),
};
}
function validateStep(i) {
setText(msg, "");
msg.classList.remove("err");
if (i === 0) {
if (!name.value.trim()) {
setText(msg, "Name is required.");
msg.classList.add("err");
return false;
}
}
if (i === 1) {
try {
JSON.parse(headers.value || "{}");
} catch {
setText(msg, "Headers must be valid JSON.");
msg.classList.add("err");
return false;
}
}
return true;
}
function go(i) {
if (i > step && !validateStep(step)) return;
step = Math.max(0, Math.min(STEPS.length - 1, i));
paint();
}
function paintSteps() {
clear(stepNav);
append(stepNav, STEPS.map((label, i) =>
el(`button.step${i === step ? ".on" : ""}${i < step ? ".done" : ""}`, {
type: "button",
text: `${i + 1}. ${label}`,
onclick: () => {
if (i <= step || validateStep(step)) go(i);
},
})));
}
function paintPanel() {
clear(panel);
if (step === 0) {
panel.append(el("div.grid",
el("label", el("span.lbl", { text: "Name (URL slug)" }), name),
el("label", el("span.lbl", { text: "Title" }), title),
el("label", el("span.lbl", { text: "App module" }), appSel),
el("label", el("span.lbl", { text: "Channel" }), chanSel),
el("label", el("span.lbl", { text: "Tags" }), tags),
el("label.inline-check", enabled, el("span", { text: "Enabled (required for on-demand wake)" })),
el("label.inline-check", onDemand, el("span", { text: "Start on demand, stop when idle" })),
el("label.inline-check", isPublic, el("span", { text: "Publicly fetchable" })),
));
} else if (step === 1) {
panel.append(el("div.grid",
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: "Origin proxy" }), proxy),
el("label", el("span.lbl", { text: "Headers JSON" }), headers),
el("label", el("span.lbl", { text: "Encryption" }), drm),
el("label", el("span.lbl", { text: "Rewriter" }), rewriter),
el("label", el("span.lbl", { text: "Video select" }), videoSel),
el("label", el("span.lbl", { text: "Audio select" }), audioSel),
el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle),
));
} else if (step === 2) {
panel.append(el("div.stack", variants, outputs));
} else {
const b = body();
panel.append(el("div.stack",
el("p.hint", { text: "Confirm and create. You can edit everything later on the stream page." }),
el("div.card", { style: { boxShadow: "none" } },
row("Name", b.name),
row("Title", b.title || "—"),
row("Module", b.app ? `${b.app} / ${b.channel || "—"}` : "—"),
row("Manifest", b.mpd || "(from module / capture)"),
row("Encryption", b.drm_mode),
row("On-demand", b.on_demand ? "yes" : "no"),
row("Public", b.public ? "yes" : "no"),
row("Variants", String((b.variants || []).filter((v) => v.enabled).length) + " enabled"),
row("Outputs", String((b.outputs || []).filter((o) => o.enabled).length) + " enabled"),
),
));
}
}
function row(k, v) {
return el("div.row", { style: { justifyContent: "space-between", padding: "4px 0" } },
el("span.muted", { text: k }),
el("span.mono", { text: v }),
);
}
function paintFoot() {
clear(footLeft);
clear(footRight);
footLeft.append(cancelBtn);
if (step === 0 && (appSel.value || name.value)) footLeft.append(skipBtn);
if (step > 0) footRight.append(backBtn);
if (step < STEPS.length - 1) footRight.append(nextBtn);
else footRight.append(createBtn);
}
function paint() {
paintSteps();
paintPanel();
paintFoot();
if (step === 0) name.focus();
}
async function submit(btn) {
if (!validateStep(0) || !validateStep(1)) {
go(0);
return;
}
await withBusy(btn, async () => {
try {
const st = await api.createStream(body());
toast(`Created ${st.name}`);
await refresh("create");
location.hash = `#/stream/${st.id}`;
} catch (err) {
setText(msg, err.message);
msg.classList.add("err");
}
});
}
(async () => {
try {
const d = await api.apps();
apps = d.apps || [];
clear(appSel);
appSel.append(el("option", { value: "", text: "(none)" }));
append(appSel, apps.map((a) => el("option", { value: a.name, text: a.name })));
fillChannels();
for (const n of d.rewriters || []) {
rewriter.append(el("option", { value: n, text: n }));
}
} catch {
// Module list is optional.
}
paint();
})();
paint();
}

View file

@ -0,0 +1,816 @@
// 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 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 }));
}
})();
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: "Origin proxy" }), 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.
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);
}

View file

@ -0,0 +1,292 @@
// Streams list: search, filter, sort, bulk actions. Create is a full page.
import {
el, pill, setText, reconcile, toast, confirmDialog, debounce, fmtAge, clear, append,
} from "../util.js";
import { state, subscribe, refresh, canEdit } from "../store.js";
import { api } from "../api.js";
import { publishLinks, tagList } from "../components.js";
const view = {
q: "",
health: "all",
tag: "all",
sort: "name",
dir: 1,
selected: new Set(),
};
export function streams(root) {
const tbody = el("tbody");
const countLabel = el("span.muted");
const bulkBar = el("div.row");
const search = el("input", {
type: "search", placeholder: "Search name, title, tag…", value: view.q,
oninput: debounce((e) => {
view.q = e.target.value.trim().toLowerCase();
paint();
}),
});
const healthSel = el("select", {
onchange: (e) => {
view.health = e.target.value;
paint();
},
}, ...["all", "ok", "starting", "down", "stopped"].map((v) =>
el("option", { value: v, text: v === "all" ? "Any health" : v, selected: view.health === v })));
const tagSel = el("select", {
onchange: (e) => {
view.tag = e.target.value;
paint();
},
});
const head = el("thead", el("tr",
el("th", { style: { width: "28px" } }, el("input", {
type: "checkbox", title: "Select all shown",
onchange: (e) => {
const shown = visible();
if (e.target.checked) shown.forEach((s) => view.selected.add(s.id));
else shown.forEach((s) => view.selected.delete(s.id));
paint();
},
})),
sortTh("name", "Stream"),
sortTh("health", "Health"),
sortTh("viewers", "Viewers"),
el("th", { text: "Publish" }),
el("th", { text: "Actions" }),
));
root.append(el("div.stack",
el("div.card",
el("div.card-head",
el("h2", { text: "Streams" }),
countLabel,
el("span.spacer"),
search, healthSel, tagSel,
canEdit() ? el("button.sm", {
text: "+ Add stream",
onclick: () => { location.hash = "#/streams/new"; },
}) : null,
),
bulkBar,
el("div.table-wrap", el("table", head, tbody)),
),
));
function sortTh(key, label) {
const th = el("th.sortable", {
onclick: () => {
if (view.sort === key) view.dir *= -1;
else {
view.sort = key;
view.dir = 1;
}
paint();
},
}, el("span", { text: label }), el("span.arrow"));
th.dataset.sortKey = key;
return th;
}
function visible() {
let list = (state.streams || []).slice();
if (view.q) {
list = list.filter((s) =>
`${s.name} ${s.title} ${s.tags} ${s.app} ${s.channel}`.toLowerCase().includes(view.q));
}
if (view.health !== "all") list = list.filter((s) => (s.health || "stopped") === view.health);
if (view.tag !== "all") {
list = list.filter((s) => String(s.tags || "").split(",").includes(view.tag));
}
const dir = view.dir;
list.sort((a, b) => {
switch (view.sort) {
case "health":
return dir * String(a.health || "").localeCompare(String(b.health || ""));
case "viewers":
return dir * ((a.viewers || 0) - (b.viewers || 0));
default:
return dir * String(a.name).localeCompare(String(b.name));
}
});
return list;
}
function paint() {
const list = visible();
const total = (state.streams || []).length;
setText(countLabel, list.length === total ? `${total}` : `${list.length} of ${total}`);
const tags = new Set();
for (const s of state.streams || []) {
for (const t of String(s.tags || "").split(",").filter(Boolean)) tags.add(t);
}
const wantTags = ["all", ...Array.from(tags).sort()];
if (tagSel.dataset.opts !== wantTags.join("|")) {
tagSel.dataset.opts = wantTags.join("|");
clear(tagSel);
append(tagSel, wantTags.map((t) =>
el("option", { value: t, text: t === "all" ? "Any tag" : t, selected: view.tag === t })));
}
for (const th of head.querySelectorAll("th.sortable")) {
const arrow = th.querySelector(".arrow");
setText(arrow, th.dataset.sortKey === view.sort ? (view.dir > 0 ? "▲" : "▼") : "");
}
const ids = new Set((state.streams || []).map((s) => s.id));
for (const id of Array.from(view.selected)) if (!ids.has(id)) view.selected.delete(id);
paintBulk();
if (!list.length) {
reconcile(tbody, [{ id: "none" }], (x) => x.id,
() => el("tr", el("td.empty", { colspan: "6" },
total
? el("span", { text: "No stream matches these filters." })
: el("div",
el("p", { text: "No streams yet." }),
canEdit()
? el("p", el("a", { href: "#/streams/new", text: "Add your first stream" }))
: null,
),
)), () => {});
return;
}
reconcile(tbody, list, (s) => s.id, createRow, updateRow);
}
function paintBulk() {
const n = view.selected.size;
clear(bulkBar);
if (!n || !canEdit()) return;
append(bulkBar, [
el("span.muted", { text: `${n} selected` }),
el("button.ghost.sm", { text: "Start", onclick: () => bulk("start") }),
el("button.ghost.sm", { text: "Stop", onclick: () => bulk("stop") }),
el("button.ghost.sm", { text: "Restart", onclick: () => bulk("restart") }),
el("button.ghost.sm", { text: "Clear", onclick: () => { view.selected.clear(); paint(); } }),
]);
bulkBar.style.marginBottom = "12px";
}
async function bulk(action) {
const ids = Array.from(view.selected);
if (!ids.length) return;
if (!(await confirmDialog(
`${action[0].toUpperCase()}${action.slice(1)} ${ids.length} stream(s)?`,
action === "start"
? "Selected streams will start (or wake) now."
: "Viewers currently watching will be disconnected.",
action[0].toUpperCase() + action.slice(1),
action !== "start",
))) return;
try {
const res = await api.bulk(ids, action);
const failed = (res.results || []).filter((r) => !r.ok);
if (failed.length) {
toast(`${res.ok_count} ok, ${failed.length} failed: ${failed[0].error}`, true);
} else {
toast(`${action} applied to ${res.ok_count} stream(s)`);
}
view.selected.clear();
await refresh("bulk");
} catch (err) {
toast(err.message, true);
}
}
function createRow(s) {
const tr = el("tr",
el("td", el("input", {
type: "checkbox", class: "sel",
onchange: (e) => {
const id = Number(tr.dataset.key);
if (e.target.checked) view.selected.add(id);
else view.selected.delete(id);
paintBulk();
},
})),
el("td.name-cell"),
el("td.health-cell"),
el("td.viewers-cell.mono"),
el("td.links-cell"),
el("td.actions"),
);
updateRow(tr, s);
return tr;
}
function flagPills(s) {
const flags = [];
if (s.enabled === false) flags.push(pill("out of service", "off"));
if (s.on_demand) flags.push(pill("on-demand", "tag"));
if (s.public === false) flags.push(pill("private", "tag"));
if (!s.mpd) flags.push(pill("no manifest", "down"));
if (s.needs_capture) flags.push(pill("needs keys", "starting"));
for (const n of Array.from(tagList(s.tags).childNodes)) flags.push(n);
const shown = flags.slice(0, 2);
const rest = flags.length - shown.length;
if (rest > 0) {
const titles = flags.slice(2).map((n) => n.textContent).join(", ");
shown.push(el("span.flag-more", { text: `+${rest}`, title: titles }));
}
return shown;
}
function updateRow(tr, s) {
tr.querySelector(".sel").checked = view.selected.has(s.id);
const nameCell = tr.querySelector(".name-cell");
nameCell.replaceChildren(
el("div", el("a", { href: `#/stream/${s.id}`, text: s.title || s.name })),
el("div.sub.mono", { text: s.name }),
el("div.row", { style: { gap: "4px", marginTop: "3px" } }, ...flagPills(s)),
);
tr.querySelector(".health-cell").replaceChildren(
el("div", pill(s.health || "stopped")),
s.last_error ? el("div.sub", { text: s.last_error, title: s.last_error }) : null,
s.playlist_age_s ? el("div.sub", { text: fmtAge(s.playlist_age_s) }) : null,
);
setText(tr.querySelector(".viewers-cell"), s.viewers ? String(s.viewers) : "—");
tr.querySelector(".links-cell").replaceChildren(
publishLinks(s, { limit: 1, compact: true }),
);
const actions = tr.querySelector(".actions");
if (!canEdit()) {
actions.replaceChildren(el("a", { href: `#/stream/${s.id}`, text: "Open" }));
return;
}
actions.replaceChildren(el("div.row",
el("button.ghost.sm", { text: "Start", onclick: () => act(s, "start") }),
el("button.ghost.sm", { text: "Stop", onclick: () => act(s, "stop") }),
el("a.sm", { href: `#/stream/${s.id}`, text: "Open" }),
));
}
async function act(s, what) {
if (what === "stop" && s.health === "ok") {
const ok = await confirmDialog(`Stop ${s.title || s.name}?`,
"Anyone watching will be disconnected.", "Stop");
if (!ok) return;
}
try {
await api.action(s.id, what);
toast(`${s.name}: ${what}`);
await refresh("action");
} catch (err) {
toast(err.message, true);
}
}
const off = subscribe(paint);
paint();
refresh("streams");
return off;
}