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,645 @@
/* streamd dashboard — signal amber on charcoal.
Tokens redefine for dark; components only use var(--…). */
:root {
color-scheme: light dark;
--bg: #f4f2ee;
--bg-elev: #ffffff;
--bg-sunken: #ebe7e0;
--sidebar: #1a1814;
--sidebar-text: #cfc6b8;
--sidebar-active: #2a2620;
--border: #ddd6cb;
--border-strong: #c9bfb0;
--text: #16140f;
--text-dim: #6a6358;
--accent: #c47a12;
--accent-soft: #f8ecda;
--accent-ink: #ffffff;
--ok: #0f7b4f;
--ok-soft: #dcf5e8;
--warn: #9a6200;
--warn-soft: #fdf0d5;
--down: #b4232a;
--down-soft: #fde4e4;
--idle: #6a6358;
--idle-soft: #ebe7e0;
--shadow: 0 1px 2px rgba(40, 30, 16, .05), 0 6px 18px -6px rgba(40, 30, 16, .12);
--radius: 10px;
--radius-sm: 7px;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
--ease: 180ms ease;
}
/* Charcoal dark: page and sidebar differ so the shell still reads. */
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #141210;
--bg-elev: #1c1a17;
--bg-sunken: #0f0e0c;
--sidebar: #0c0b0a;
--sidebar-text: #cfc6b8;
--sidebar-active: #24201c;
--border: #2e2a24;
--border-strong: #3d372f;
--text: #f2ebe0;
--text-dim: #a89f90;
--accent: #e8a23a;
--accent-soft: #2a2010;
--accent-ink: #1a1408;
--ok: #3dd68c;
--ok-soft: #163024;
--warn: #e6b84d;
--warn-soft: #2a220c;
--down: #f07178;
--down-soft: #2e1414;
--idle: #a89f90;
--idle-soft: #24201c;
--shadow: 0 1px 0 rgba(255, 255, 255, .04) inset, 0 8px 24px rgba(0, 0, 0, .35);
}
}
:root[data-theme="dark"] {
--bg: #141210;
--bg-elev: #1c1a17;
--bg-sunken: #0f0e0c;
--sidebar: #0c0b0a;
--sidebar-text: #cfc6b8;
--sidebar-active: #24201c;
--border: #2e2a24;
--border-strong: #3d372f;
--text: #f2ebe0;
--text-dim: #a89f90;
--accent: #e8a23a;
--accent-soft: #2a2010;
--accent-ink: #1a1408;
--ok: #3dd68c;
--ok-soft: #163024;
--warn: #e6b84d;
--warn-soft: #2a220c;
--down: #f07178;
--down-soft: #2e1414;
--idle: #a89f90;
--idle-soft: #24201c;
--shadow: 0 1px 0 rgba(255, 255, 255, .04) inset, 0 8px 24px rgba(0, 0, 0, .35);
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
}
h1, h2, h3 { margin: 0; font-weight: 600; letter-spacing: -0.01em; }
h1 { font-size: 21px; }
h2 { font-size: 15px; }
h3 { font-size: 13px; font-weight: 600; }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
.mono { font-family: var(--mono); font-size: 12px; }
.muted { color: var(--text-dim); }
.hint { color: var(--text-dim); font-size: 12px; margin: 2px 0 0; }
.spacer { flex: 1; }
.only-mobile { display: none; }
.sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
}
/* ---------- layout ---------- */
#app {
display: grid;
grid-template-columns: 232px 1fr;
min-height: 100vh;
}
/* Explicit display rules beat the UA [hidden] stylesheet; force hide. */
#app[hidden],
#gate[hidden],
.stack[hidden],
[hidden] {
display: none !important;
}
#sidebar {
background: var(--sidebar);
color: var(--sidebar-text);
display: flex;
flex-direction: column;
padding: 14px 10px;
gap: 14px;
position: sticky;
top: 0;
height: 100vh;
}
.brand {
display: flex;
align-items: center;
gap: 9px;
padding: 2px 8px 8px;
}
.brand-name { font-weight: 600; color: #fff; font-size: 15px; letter-spacing: -0.01em; }
.logo {
width: 22px; height: 22px; border-radius: 6px; flex: 0 0 auto;
background: var(--accent);
position: relative;
}
.logo::after {
content: ""; position: absolute; left: 8px; top: 6px;
border-left: 7px solid var(--accent-ink);
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
}
.logo.big { width: 34px; height: 34px; border-radius: 9px; }
.logo.big::after { left: 12px; top: 9px; border-left-width: 11px; border-top-width: 8px; border-bottom-width: 8px; }
#nav { display: flex; flex-direction: column; gap: 2px; }
#nav a {
display: flex; align-items: center; gap: 10px;
padding: 8px 10px;
border-radius: var(--radius-sm);
color: var(--sidebar-text);
font-size: 13.5px;
}
#nav a:hover { background: var(--sidebar-active); text-decoration: none; color: #fff; }
#nav a.active { background: var(--sidebar-active); color: #fff; font-weight: 600; }
#nav a .ico {
width: 16px; height: 16px; flex: 0 0 auto;
display: inline-flex; align-items: center; justify-content: center;
opacity: .85;
}
#nav a .ico svg { width: 16px; height: 16px; display: block; }
#nav a[hidden] { display: none; }
.sidebar-foot { margin-top: auto; display: flex; flex-direction: column; gap: 6px; }
.chip {
padding: 6px 8px; border-radius: 6px;
background: rgba(255, 255, 255, .05);
color: var(--sidebar-text);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 11px;
}
.chip .chip-label {
display: block; font-size: 10px; font-weight: 600;
color: rgba(255,255,255,.45); letter-spacing: .02em; margin-bottom: 1px;
}
.chip .chip-val { font-family: var(--mono); font-size: 11px; }
#main { display: flex; flex-direction: column; min-width: 0; }
#topbar {
display: flex; align-items: center; gap: 12px;
padding: 12px 20px;
background: var(--bg-elev);
border-bottom: 1px solid var(--border);
position: sticky; top: 0; z-index: 20;
}
#page-title { font-size: 21px; font-weight: 600; letter-spacing: -0.02em; }
.who { display: flex; align-items: center; gap: 8px; }
.conn {
display: inline-flex; align-items: center; gap: 6px;
font-size: 12px; padding: 4px 10px; border-radius: 999px;
background: var(--ok-soft); color: var(--ok); font-weight: 600;
}
.conn::before {
content: ""; width: 7px; height: 7px; border-radius: 50%;
background: currentColor; box-shadow: 0 0 0 3px color-mix(in srgb, currentColor 25%, transparent);
}
.conn.off { background: var(--down-soft); color: var(--down); }
.conn.warn { background: var(--warn-soft); color: var(--warn); }
#uptime {
font-size: 12px; color: var(--text-dim);
font-variant-numeric: tabular-nums;
}
#theme-btn {
display: inline-flex; align-items: center; gap: 6px;
font-size: 12px; font-weight: 500; color: var(--text-dim);
border: 1px solid var(--border); border-radius: var(--radius-sm);
background: transparent; padding: 5px 10px;
}
#theme-btn:hover { background: var(--bg-sunken); color: var(--text); filter: none; }
#view { padding: 20px; min-width: 0; }
#view:focus { outline: none; }
#view.view-enter { animation: view-in var(--ease) both; }
@keyframes view-in {
from { opacity: 0; }
to { opacity: 1; }
}
.stack { display: flex; flex-direction: column; gap: 16px; }
/* ---------- cards ---------- */
.card {
background: var(--bg-elev);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 16px;
}
.card > h2 { margin-bottom: 12px; }
.card-head {
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
margin-bottom: 12px;
}
.card-head h2 { margin: 0; }
/* ---------- stat tiles ---------- */
.tile-band { display: flex; flex-direction: column; gap: 8px; }
.tile-band-label {
font-size: 11px; font-weight: 600; color: var(--text-dim);
text-transform: uppercase; letter-spacing: .04em;
}
.tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 12px;
}
.tile {
background: var(--bg-elev);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 13px 15px;
box-shadow: var(--shadow);
}
.tile .k { font-size: 11.5px; color: var(--text-dim); text-transform: uppercase; letter-spacing: .04em; }
.tile .v { font-size: 26px; font-weight: 600; line-height: 1.15; margin-top: 3px; font-variant-numeric: tabular-nums; }
.tile.ok .v { color: var(--ok); }
.tile.down .v { color: var(--down); }
.tile.warn .v { color: var(--warn); }
.tile.alarm {
border-color: color-mix(in srgb, var(--down) 35%, var(--border));
}
.tile.alarm.down { background: color-mix(in srgb, var(--down-soft) 55%, var(--bg-elev)); }
.tile.alarm.warn { background: color-mix(in srgb, var(--warn-soft) 55%, var(--bg-elev)); }
/* ---------- forms ---------- */
label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--text-dim); }
label > span.lbl { font-size: 12px; }
input, select, textarea, button {
font: inherit;
color: var(--text);
background: var(--bg-elev);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: 7px 9px;
}
input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
input[type=checkbox] { width: 16px; height: 16px; accent-color: var(--accent); padding: 0; }
textarea { font-family: var(--mono); font-size: 12px; resize: vertical; min-height: 4.2em; white-space: pre; }
input:disabled, select:disabled, textarea:disabled { opacity: .55; }
button {
cursor: pointer;
background: var(--accent);
border-color: transparent;
color: var(--accent-ink);
font-weight: 600;
font-size: 13px;
padding: 7px 13px;
transition: background var(--ease), border-color var(--ease), color var(--ease), transform 80ms ease;
}
button:hover { background: color-mix(in srgb, var(--accent) 88%, #000); }
button:active:not(:disabled) { transform: translateY(1px); }
button.ghost {
background: transparent; color: var(--text); border-color: var(--border-strong); font-weight: 500;
}
button.ghost:hover { background: var(--bg-sunken); }
button.danger { background: transparent; color: var(--down); border-color: var(--down); }
button.danger:hover { background: var(--down-soft); }
button.sm { padding: 4px 9px; font-size: 12px; }
button.tiny { padding: 2px 7px; font-size: 11px; font-weight: 500; }
button:disabled, button[aria-busy="true"] { opacity: .55; cursor: not-allowed; transform: none; }
button[aria-busy="true"] { position: relative; }
.icon-btn {
background: transparent; border-color: transparent; color: var(--text-dim);
padding: 5px 8px; font-size: 15px;
}
.icon-btn:hover { background: var(--bg-sunken); color: var(--text); }
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: 11px 14px;
}
.span2 { grid-column: 1 / -1; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.row.end { justify-content: flex-end; }
.inline-check { flex-direction: row; align-items: center; gap: 7px; color: var(--text); font-size: 13px; }
fieldset {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 12px;
margin: 0;
}
legend { padding: 0 6px; font-size: 12px; font-weight: 600; color: var(--text); }
.msg { min-height: 1.2em; margin: 6px 0 0; font-size: 13px; }
.msg.err { color: var(--down); }
.msg.ok { color: var(--ok); }
/* ---------- pills ---------- */
.pill {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 11.5px;
font-weight: 600;
white-space: nowrap;
background: var(--idle-soft);
color: var(--idle);
}
.pill.ok { background: var(--ok-soft); color: var(--ok); }
.pill.starting, .pill.pending { background: var(--warn-soft); color: var(--warn); }
.pill.down, .pill.error { background: var(--down-soft); color: var(--down); }
.pill.stopped, .pill.off { background: var(--idle-soft); color: var(--idle); }
.pill.role { background: var(--accent-soft); color: var(--accent); }
.pill.tag { background: var(--bg-sunken); color: var(--text-dim); font-weight: 500; }
/* ---------- tables ---------- */
.table-wrap { overflow-x: auto; margin: 0 -16px -16px; padding: 0 16px 4px; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: middle; }
th {
color: var(--text-dim); font-weight: 600; font-size: 11.5px;
text-transform: uppercase; letter-spacing: .03em;
position: sticky; top: 0; background: var(--bg-elev); z-index: 1;
}
th.sortable { cursor: pointer; user-select: none; }
th.sortable:hover { color: var(--text); }
th .arrow { opacity: .5; font-size: 9px; }
tbody tr:hover { background: var(--bg-sunken); }
tbody tr:last-child td { border-bottom: none; }
td.actions { white-space: nowrap; }
td.actions .row { gap: 5px; }
.name-cell strong { font-size: 13.5px; }
.name-cell a { color: var(--text); }
.name-cell a:hover { color: var(--accent); }
.sub { color: var(--text-dim); font-size: 11.5px; margin-top: 1px; }
.empty { padding: 28px 8px; text-align: center; color: var(--text-dim); }
/* ---------- publish links ---------- */
.links { display: flex; flex-direction: column; gap: 5px; min-width: 200px; }
.links.compact { min-width: 0; max-width: 280px; }
.link-row {
display: flex; align-items: center; gap: 7px;
padding: 5px 7px;
background: var(--bg-sunken);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
.link-row .lab {
font-size: 10.5px; font-weight: 700; letter-spacing: .03em;
color: var(--accent); min-width: 52px;
}
.link-row.master .lab { color: var(--ok); }
.link-row .path {
flex: 1; min-width: 0;
font-family: var(--mono); font-size: 11px; color: var(--text-dim);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
button.copied { color: var(--ok); border-color: var(--ok); }
/* ---------- sparkline ---------- */
.spark { display: block; width: 100%; height: 44px; }
.spark .line { fill: none; stroke: var(--accent); stroke-width: 1.5; }
.spark .area { fill: var(--accent); opacity: .12; }
.spark .zero { stroke: var(--border-strong); stroke-width: 1; stroke-dasharray: 2 3; }
/* ---------- timeline ---------- */
.timeline { display: flex; flex-direction: column; gap: 0; }
.ev {
display: grid;
grid-template-columns: 74px 110px 1fr;
gap: 10px;
padding: 7px 0;
border-bottom: 1px solid var(--border);
font-size: 12.5px;
align-items: baseline;
}
.ev:last-child { border-bottom: none; }
.ev .at { font-family: var(--mono); font-size: 11px; color: var(--text-dim); }
.ev .msg { word-break: break-word; }
.ev .msg .who { color: var(--text-dim); font-size: 11px; }
.ev.error .msg { color: var(--down); }
.ev.warn .msg { color: var(--warn); }
/* ---------- log viewer ---------- */
.logbox {
background: var(--bg-sunken);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 10px 12px;
font-family: var(--mono);
font-size: 11.5px;
line-height: 1.45;
white-space: pre-wrap;
word-break: break-word;
max-height: 420px;
overflow: auto;
margin: 0;
}
/* ---------- player ---------- */
.player-wrap { background: #000; border-radius: var(--radius-sm); overflow: hidden; }
.preview-player .preview-controls { flex-wrap: wrap; gap: 8px; align-items: center; }
.preview-player select.sm {
min-width: 10rem;
padding: 4px 8px;
font: inherit;
color: var(--text);
background: var(--surface-2, var(--panel));
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
video { width: 100%; max-height: 420px; display: block; background: #000; }
/* ---------- variant / output editors ---------- */
.vrow, .orow {
display: grid;
grid-template-columns: auto 1fr 90px 100px 100px auto;
gap: 8px;
align-items: center;
padding: 8px 0;
border-bottom: 1px solid var(--border);
}
.orow { grid-template-columns: auto 1fr 110px 110px; }
.vrow:last-of-type, .orow:last-of-type { border-bottom: none; }
.vrow input[type=text], .vrow input[type=number], .orow input[type=number] { padding: 5px 7px; font-size: 12px; }
.vrow .vname { font-weight: 600; font-size: 13px; }
.vrow .locked-note, .orow .fmt { font-size: 11px; color: var(--text-dim); }
.col-head {
display: grid;
grid-template-columns: auto 1fr 90px 100px 100px auto;
gap: 8px;
font-size: 10.5px; text-transform: uppercase; letter-spacing: .03em;
color: var(--text-dim);
padding-bottom: 5px;
border-bottom: 1px solid var(--border);
}
.col-head.out { grid-template-columns: auto 1fr 110px 110px; }
/* ---------- auth gate ---------- */
#gate {
min-height: 100vh;
display: grid;
place-items: center;
padding: 20px;
background: var(--bg);
}
.auth-card {
width: 100%; max-width: 370px;
background: var(--bg-elev);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 26px;
display: flex; flex-direction: column; gap: 13px;
}
.auth-card h2 { margin: 0; }
.auth-sub { margin: -4px 0 0; color: var(--text-dim); font-size: 13px; }
.auth-card button[type=submit] { margin-top: 4px; padding: 9px; }
/* ---------- toast & modal ---------- */
#toast-stack {
position: fixed; right: 16px; bottom: 16px; z-index: 100;
display: flex; flex-direction: column-reverse; gap: 8px;
max-width: min(420px, calc(100vw - 32px));
pointer-events: none;
}
.toast {
background: var(--sidebar); color: #fff;
padding: 10px 15px;
border-radius: var(--radius-sm);
box-shadow: var(--shadow);
font-size: 13px;
pointer-events: auto;
animation: toast-in var(--ease) both;
}
.toast.out { animation: toast-out var(--ease) both; }
.toast.err { background: var(--down); }
@keyframes toast-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: none; }
}
@keyframes toast-out {
from { opacity: 1; transform: none; }
to { opacity: 0; transform: translateY(8px); }
}
dialog {
border: 1px solid var(--border);
background: var(--bg-elev);
color: var(--text);
border-radius: var(--radius);
padding: 20px;
width: min(560px, calc(100vw - 32px));
box-shadow: var(--shadow);
}
dialog::backdrop { background: rgba(0, 0, 0, .6); backdrop-filter: blur(2px); }
/* ---------- tabs / wizard / skeleton ---------- */
.tabs {
display: flex; gap: 2px;
border-bottom: 1px solid var(--border);
margin: 0 0 16px;
}
.tabs a, .tabs button {
background: transparent; border: none; border-bottom: 2px solid transparent;
border-radius: 0; color: var(--text-dim); font-weight: 500;
padding: 8px 14px; margin-bottom: -1px;
}
.tabs a:hover, .tabs button:hover { color: var(--text); background: transparent; text-decoration: none; }
.tabs a.active, .tabs button.active {
color: var(--text); border-bottom-color: var(--accent); font-weight: 600;
}
.wizard-steps {
display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px;
}
.wizard-steps .step {
font-size: 12px; color: var(--text-dim); padding: 4px 10px;
border-radius: 999px; border: 1px solid var(--border);
background: transparent; font-weight: 500; transform: none;
}
.wizard-steps .step:hover { background: var(--bg-sunken); color: var(--text); }
.wizard-steps .step.on { color: var(--accent-ink); background: var(--accent); border-color: transparent; font-weight: 600; }
.wizard-steps .step.on:hover { background: var(--accent); color: var(--accent-ink); }
.wizard-steps .step.done { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, var(--border)); }
.wizard-foot {
position: sticky; bottom: 0; z-index: 5;
display: flex; gap: 8px; align-items: center; justify-content: flex-end;
margin: 20px -20px -20px; padding: 14px 20px;
background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
border-top: 1px solid var(--border);
backdrop-filter: blur(6px);
}
.skeleton {
background: linear-gradient(90deg, var(--bg-sunken) 25%, var(--border) 50%, var(--bg-sunken) 75%);
background-size: 200% 100%;
animation: shimmer 1.2s ease-in-out infinite;
border-radius: var(--radius-sm);
min-height: 1em;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.flag-more {
font-size: 11px; color: var(--text-dim); padding: 2px 6px;
border-radius: 999px; background: var(--bg-sunken);
}
/* ---------- responsive ---------- */
@media (max-width: 900px) {
.only-mobile { display: inline-flex; }
#app { grid-template-columns: 1fr; }
#sidebar {
position: fixed; inset: 0 auto 0 0; width: 258px; z-index: 50;
transform: translateX(-100%);
transition: transform .18s ease;
}
#app.nav-open #sidebar { transform: none; }
#app.nav-open::after {
content: ""; position: fixed; inset: 0; z-index: 40;
background: rgba(0, 0, 0, .55);
}
#view { padding: 16px; }
#topbar { padding: 10px 16px; }
.who #who-name { display: none; }
.vrow, .col-head { grid-template-columns: auto 1fr 1fr; }
.vrow > .del { grid-column: 3; justify-self: end; }
.col-head { display: none; }
.table-wrap { margin: 0 -16px -16px; padding: 0 16px 4px; }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}

View file

@ -0,0 +1,134 @@
// API client. Carries the CSRF token on mutations and routes a 401 back to
// the sign-in screen rather than leaving a half-dead page.
let csrfToken = "";
const onUnauthorized = [];
export function setCSRF(token) {
csrfToken = token || "";
}
export function getCSRF() {
return csrfToken;
}
/** Register a callback for when the session turns out to be gone. */
export function onAuthLost(fn) {
onUnauthorized.push(fn);
}
export class ApiError extends Error {
constructor(message, status, body) {
super(message);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
async function request(method, path, body, opts = {}) {
const headers = {};
let payload;
if (body !== undefined && body !== null) {
headers["Content-Type"] = "application/json";
payload = JSON.stringify(body);
}
// The session cookie is HttpOnly, so the double-submit token is what proves
// this request came from the dashboard and not from another origin.
if (method !== "GET" && method !== "HEAD" && csrfToken) {
headers["X-CSRF-Token"] = csrfToken;
}
const res = await fetch(path, {
method,
headers,
body: payload,
credentials: "same-origin",
signal: opts.signal,
});
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
if (res.status === 401) {
// allow401 lets boot/login/setup read the JSON body (e.g. needs_setup)
// without treating it as a hard failure or kicking the session.
if (opts.allow401) return data;
for (const fn of onUnauthorized) fn(data);
throw new ApiError((data && data.error) || "not signed in", 401, data);
}
if (!res.ok) {
const msg = (data && data.error) || res.statusText || `request failed (${res.status})`;
throw new ApiError(msg, res.status, data);
}
return data;
}
export const api = {
get: (p, opts) => request("GET", p, null, opts),
post: (p, b, opts) => request("POST", p, b ?? {}, opts),
patch: (p, b, opts) => request("PATCH", p, b ?? {}, opts),
put: (p, b, opts) => request("PUT", p, b ?? {}, opts),
del: (p, opts) => request("DELETE", p, null, opts),
// --- session ---
me: () => request("GET", "/api/me", null, { allow401: true }),
login: (username, password) => request("POST", "/api/login", { username, password }, { allow401: true }),
setup: (setup_token, username, password) =>
request("POST", "/api/setup", { setup_token, username, password }, { allow401: true }),
logout: () => request("POST", "/api/logout", {}),
setupState: () => request("GET", "/api/setup", null, { allow401: true }),
// --- streams ---
health: () => request("GET", "/api/health", null, { allow401: true }),
overview: () => api.get("/api/overview"),
streams: () => api.get("/api/streams"),
stream: (id, reveal) => api.get(`/api/streams/${id}${reveal ? "?reveal=1" : ""}`),
createStream: (body) => api.post("/api/streams", body),
patchStream: (id, body) => api.patch(`/api/streams/${id}`, body),
deleteStream: (id) => api.del(`/api/streams/${id}`),
action: (id, what) => api.post(`/api/streams/${id}/${what}`),
bulk: (ids, action) => api.post("/api/streams/bulk", { ids, action }),
duplicate: (id, body) => api.post(`/api/streams/${id}/duplicate`, body),
probe: (id, mpd) => api.post(`/api/streams/${id}/probe`, mpd ? { mpd } : {}),
capture: (id) => api.post(`/api/streams/${id}/capture`),
credentials: (id, body) => api.post(`/api/streams/${id}/credentials`, body),
// --- history ---
events: (id, limit = 100) => api.get(`/api/streams/${id}/events?limit=${limit}`),
metrics: (id, window = "1h") => api.get(`/api/streams/${id}/metrics?window=${encodeURIComponent(window)}`),
logs: (id, source, variant) => {
const q = new URLSearchParams({ source, tail: "600" });
if (variant) q.set("variant", variant);
return api.get(`/api/streams/${id}/logs?${q}`);
},
// --- schedules ---
schedules: (id) => api.get(`/api/streams/${id}/schedules`),
allSchedules: () => api.get("/api/schedules"),
upcoming: (limit = 10) => api.get(`/api/schedules?upcoming=1&limit=${limit}`),
createSchedule: (id, body) => api.post(`/api/streams/${id}/schedules`, body),
patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body),
deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`),
// --- admin ---
settings: () => api.get("/api/settings"),
saveSettings: (body) => api.put("/api/settings", body),
users: () => api.get("/api/users"),
createUser: (body) => api.post("/api/users", body),
patchUser: (id, body) => api.patch(`/api/users/${id}`, body),
deleteUser: (id) => api.del(`/api/users/${id}`),
setPassword: (id, body) => api.post(`/api/users/${id}/password`, body),
apiKeys: () => api.get("/api/apikeys"),
createKey: (body) => api.post("/api/apikeys", body),
revokeKey: (id) => api.del(`/api/apikeys/${id}`),
audit: (limit = 200) => api.get(`/api/audit?limit=${limit}`),
agents: () => api.get("/api/agents"),
apps: () => api.get("/api/apps"),
};

View file

@ -0,0 +1,331 @@
// Application shell: sign-in gate, hash router, chrome.
import { api, setCSRF, onAuthLost } from "./api.js";
import { state, subscribe, connect, disconnect, refresh, setMe, isAdmin } from "./store.js";
import { $, $$, el, clear, setText, toast, fmtSeconds } from "./util.js";
import { dashboard } from "./views/dashboard.js";
import { streams } from "./views/streams.js";
import { streamView } from "./views/stream.js";
import { scheduleView, settingsView, peopleView, auditView } from "./views/admin.js";
const app = $("#app");
const gate = $("#gate");
const viewRoot = $("#view");
let teardown = null;
// ---------- theme ----------
function showingDark() {
const cur = document.documentElement.dataset.theme;
if (cur) return cur === "dark";
return window.matchMedia("(prefers-color-scheme: dark)").matches;
}
function paintThemeLabel() {
const label = $("#theme-btn-label");
if (!label) return;
// Button names the mode you will switch *to*.
setText(label, showingDark() ? "Light" : "Dark");
}
function initTheme() {
const saved = localStorage.getItem("streamd.theme");
if (saved === "light" || saved === "dark") {
document.documentElement.dataset.theme = saved;
}
paintThemeLabel();
$("#theme-btn").addEventListener("click", () => {
const next = showingDark() ? "light" : "dark";
document.documentElement.dataset.theme = next;
paintThemeLabel();
try {
localStorage.setItem("streamd.theme", next);
} catch {
// Private browsing; the choice simply will not persist.
}
});
}
// ---------- routes ----------
const ROUTES = [
{ path: /^\/?$/, title: "Dashboard", nav: "/", mount: (root) => dashboard(root) },
{ path: /^\/streams$/, title: "Streams", nav: "/streams", mount: (root) => streams(root) },
{
path: /^\/streams\/new$/, title: "Add stream", nav: "/streams",
mount: (root) => import("./views/stream-form.js").then((m) => m.streamCreate(root)),
},
{
path: /^\/stream\/(\d+)(?:\/(live|config|debug))?$/, title: "Stream", nav: "/streams",
mount: (root, m) => streamView(root, Number(m[1]), m[2] || "live"),
},
{ path: /^\/schedule$/, title: "Schedule", nav: "/schedule", mount: (root) => scheduleView(root) },
{ path: /^\/settings$/, title: "Settings", nav: "/settings", admin: true, mount: (root) => settingsView(root) },
{ path: /^\/people$/, title: "People & keys", nav: "/people", admin: true, mount: (root) => peopleView(root) },
{ path: /^\/audit$/, title: "Audit log", nav: "/audit", admin: true, mount: (root) => auditView(root) },
];
function currentPath() {
const h = location.hash.replace(/^#/, "");
return h || "/";
}
function route() {
const path = currentPath();
if (teardown) {
try {
teardown();
} catch (err) {
console.error("view teardown failed", err);
}
teardown = null;
}
clear(viewRoot);
for (const r of ROUTES) {
const m = path.match(r.path);
if (!m) continue;
if (r.admin && !isAdmin()) {
viewRoot.append(el("div.card",
el("h2", { text: "Not available" }),
el("p.hint", { text: "This page is administrator-only." }),
));
setText($("#page-title"), "Not available");
return;
}
setText($("#page-title"), r.title);
document.title = `${r.title} · streamd`;
markNav(r.nav);
viewRoot.classList.remove("view-enter");
void viewRoot.offsetWidth;
viewRoot.classList.add("view-enter");
try {
const mounted = r.mount(viewRoot, m);
// Mount may return a teardown, or a Promise thereof (lazy create page).
if (mounted && typeof mounted.then === "function") {
mounted.then((fn) => { teardown = fn || null; }).catch((err) => {
console.error(err);
viewRoot.append(el("div.card", el("p.msg.err", { text: `This page failed to render: ${err.message}` })));
});
} else {
teardown = mounted || null;
}
} catch (err) {
console.error(err);
viewRoot.append(el("div.card", el("p.msg.err", { text: `This page failed to render: ${err.message}` })));
}
app.classList.remove("nav-open");
viewRoot.focus({ preventScroll: true });
return;
}
setText($("#page-title"), "Not found");
markNav("");
viewRoot.append(el("div.card",
el("h2", { text: "Not found" }),
el("p", el("a", { href: "#/", text: "Back to the dashboard" })),
));
}
function markNav(nav) {
for (const a of $$("#nav a")) {
a.classList.toggle("active", a.dataset.nav === nav);
}
}
// ---------- chrome ----------
function paintChrome() {
const me = state.me || {};
setText($("#who-name"), me.name || "");
const role = $("#who-role");
setText(role, me.role || "");
role.className = `pill role`;
for (const a of $$("#nav a[data-admin]")) a.hidden = !isAdmin();
const conn = $("#conn");
const live = !!state.connected;
setText(conn, live ? "Live" : "Reconnecting");
conn.classList.toggle("off", !live);
conn.classList.toggle("warn", !live);
conn.title = live ? "WebSocket connected" : "WebSocket reconnecting — data may be stale";
setText($("#uptime"), state.uptimeS ? `up ${fmtSeconds(state.uptimeS)}` : "");
const agents = state.agents || [];
const agentVal = $("#agent-chip .chip-val") || $("#agent-chip");
const agentIds = agents.map((a) => a.agent_id);
setText(agentVal, agents.length ? agentIds.join(", ") : "none");
$("#agent-chip").title = agents.length
? agentIds.join("\n")
: "No capture agents connected";
const d = state.deps;
if (d) {
const mark = (ok) => (ok ? "✓" : "✗");
// /api/health gives paths to a signed-in caller and booleans otherwise.
const has = (v) => (typeof v === "boolean" ? v : !!v);
const chip = $("#deps-chip");
const val = chip.querySelector(".chip-val") || chip;
setText(val, `ffmpeg${mark(has(d.ffmpeg))} nre${mark(has(d.nre))} mp4decrypt${mark(has(d.mp4decrypt))}`);
chip.title = [
`ffmpeg: ${d.ffmpeg || "missing"}`,
`N_m3u8DL-RE: ${d.nre || "missing"}`,
`mp4decrypt: ${d.mp4decrypt || "missing"}`,
d.bin_dir ? `bin: ${d.bin_dir}` : "",
].filter(Boolean).join("\n");
}
if (state.lastError) toastOnce(state.lastError);
}
let lastToast = "";
function toastOnce(msg) {
if (msg === lastToast) return;
lastToast = msg;
toast(msg, true);
setTimeout(() => (lastToast = ""), 8000);
}
// ---------- sign-in ----------
function showGate(opts = {}) {
disconnect();
app.hidden = true;
gate.hidden = false;
const form = $("#login-form");
const setupRow = $("#setup-row");
const needsSetup = !!opts.needsSetup;
setupRow.hidden = !needsSetup;
setupRow.querySelector("input").required = needsSetup;
setText($("#gate-title"), needsSetup ? "Create the first administrator" : "Sign in to streamd");
setText($("#gate-note"), needsSetup
? "No accounts exist yet. Paste the one-time setup token from the streamd startup log."
: "");
setText($("#gate-submit"), needsSetup ? "Create account" : "Sign in");
setText($("#gate-msg"), opts.message || "");
$("#gate-msg").classList.toggle("err", !!opts.message);
form.dataset.mode = needsSetup ? "setup" : "login";
(needsSetup ? setupRow.querySelector("input") : form.username).focus();
}
function showApp() {
gate.hidden = true;
app.hidden = false;
connect();
route();
}
async function submitGate(ev) {
ev.preventDefault();
const form = ev.target;
const msg = $("#gate-msg");
setText(msg, "");
msg.classList.remove("err");
const btn = $("#gate-submit");
btn.disabled = true;
try {
const username = form.username.value.trim();
const password = form.password.value;
let res;
if (form.dataset.mode === "setup") {
res = await api.setup(form.setup_token.value.trim(), username, password);
} else {
res = await api.login(username, password);
}
if (!res || res.error) {
throw new Error((res && res.error) || "sign-in failed");
}
setCSRF(res.csrf_token || "");
// Prefer /api/me (includes csrf). If the Set-Cookie round-trip is slow or
// blocked, fall back to the login/setup payload so the UI still advances.
let me = await api.me();
if (!me || !me.role) {
if (res.user) {
me = {
name: res.user.username || username,
role: res.user.role || "admin",
actor_kind: "user",
user_id: res.user.id,
csrf_token: res.csrf_token,
};
} else if (res.role || res.name) {
me = res;
}
}
if (!me || !me.role) {
throw new Error(
"Account was created/accepted, but the browser session cookie was not established. " +
"Allow cookies for this origin, then hard-refresh and sign in.",
);
}
setMe(me);
form.reset();
showApp();
await refresh("signed-in");
} catch (err) {
setText(msg, err.message || String(err));
msg.classList.add("err");
} finally {
btn.disabled = false;
}
}
async function logout() {
try {
await api.logout();
} catch {
// Signing out locally matters more than the request succeeding.
}
setCSRF("");
setMe(null);
showGate({ message: "Signed out." });
}
// ---------- boot ----------
async function boot() {
initTheme();
subscribe(paintChrome);
window.addEventListener("hashchange", route);
$("#login-form").addEventListener("submit", submitGate);
$("#logout-btn").addEventListener("click", logout);
$("#nav-open").addEventListener("click", () => app.classList.add("nav-open"));
$("#nav-close").addEventListener("click", () => app.classList.remove("nav-open"));
app.addEventListener("click", (ev) => {
// Tapping the scrim closes the mobile drawer.
if (app.classList.contains("nav-open") && !ev.target.closest("#sidebar") && !ev.target.closest("#nav-open")) {
app.classList.remove("nav-open");
}
});
document.addEventListener("keydown", (ev) => {
if (ev.key === "Escape") app.classList.remove("nav-open");
});
// A session that expires while the page is open sends the viewer back to
// sign-in rather than leaving a page full of failing requests.
onAuthLost(() => {
setMe(null);
showGate({ message: "Your session expired. Sign in again." });
});
try {
const me = await api.me();
if (me && me.role) {
setCSRF(me.csrf_token || "");
setMe(me);
await refresh("boot");
showApp();
return;
}
// allow401 returns the 401 JSON body instead of throwing.
showGate({ needsSetup: !!(me && me.needs_setup) });
} catch (err) {
const needsSetup = !!(err.body && err.body.needs_setup);
showGate({ needsSetup });
}
}
boot();

View file

@ -0,0 +1,375 @@
// Shared pieces used by more than one view.
import { el, pill, copyText, absURL, fmtAge, fmtDateTime, clear, append } from "./util.js";
/** A list of copyable publish endpoints, one row per variant x format. */
export function publishLinks(stream, opts = {}) {
const links = Array.isArray(stream.links) ? stream.links : [];
const box = el(`div.links${opts.compact ? ".compact" : ""}`);
if (!links.length) {
// A stream with no resolved links still has its canonical HLS path.
const path = stream.play_path || `/hls/${stream.name}/index.m3u8`;
box.append(linkRow({ output_label: "HLS", variant_label: "", play_path: path, health: stream.health }, opts));
return box;
}
const shown = opts.limit ? links.slice(0, opts.limit) : links;
for (const l of shown) box.append(linkRow(l, opts));
if (opts.limit && links.length > opts.limit) {
box.append(el("div.hint", { text: `+${links.length - opts.limit} more` }));
}
return box;
}
function linkRow(l, opts = {}) {
const url = absURL(l.play_path);
const label = l.master
? "MASTER"
: [l.variant_label, l.output_label].filter(Boolean).join(" · ");
const copyBtn = el("button.tiny.ghost", {
text: "Copy",
title: `Copy ${url}`,
onclick: (ev) => copyText(url, label ? `${label} link` : "link", ev.currentTarget),
});
return el(`div.link-row${l.master ? ".master" : ""}`,
el("span.lab", { text: label || "HLS" }),
el("span.path", { text: l.play_path, title: url }),
!opts.compact && l.health ? pill(l.health) : null,
copyBtn,
);
}
/**
* Editor for the output ladder: any number of rungs at any height and
* bitrate, which replaces the three hardcoded checkboxes.
*/
export function variantEditor(variants) {
const rows = el("div");
const wrap = el("fieldset",
el("legend", { text: "Quality ladder" }),
el("p.hint", {
text: "The source rung is always published as a straight copy. Each extra rung is " +
"re-encoded, so every one you enable costs CPU.",
}),
el("div.col-head",
el("span", { text: "On" }), el("span", { text: "Name" }),
el("span", { text: "Height" }), el("span", { text: "Video" }),
el("span", { text: "Audio" }), el("span", { text: "" }),
),
rows,
el("div.row", { style: { marginTop: "10px" } },
el("button.ghost.sm", {
type: "button",
text: "+ Add rung",
onclick: () => rows.append(variantRow({
id: "", label: "", enabled: true, height: 480,
video_bitrate: "1200k", audio_bitrate: "96k",
})),
}),
el("button.ghost.sm", {
type: "button",
text: "+ Add audio-only",
onclick: () => rows.append(variantRow({
id: "audio", label: "Audio", enabled: true, height: 0,
audio_only: true, audio_bitrate: "96k",
})),
}),
),
);
const list = (variants && variants.length ? variants : [{ id: "fhd", label: "FHD", enabled: true, height: 0 }]);
for (const v of list) rows.append(variantRow(v));
wrap.readValue = () => Array.from(rows.children)
.map((r) => r.readValue())
.filter((v) => v && (v.audio_only || v.height > 0 || v.id === "fhd"));
return wrap;
}
function variantRow(v) {
const isSource = !v.audio_only && (!v.height || v.height <= 0) && (v.id === "fhd" || !v.id);
const on = el("input", { type: "checkbox", checked: isSource || v.enabled !== false, disabled: isSource });
const name = el("input", {
type: "text", value: v.label || (v.id || "").toUpperCase(), placeholder: "HD",
disabled: isSource, maxlength: "24",
});
const height = el("input", {
type: "number", value: v.height || 0, min: "0", max: "4320", step: "2",
disabled: isSource || v.audio_only,
});
const vbr = el("input", {
type: "text", value: v.video_bitrate || "", placeholder: "2800k",
disabled: isSource || v.audio_only,
});
const abr = el("input", { type: "text", value: v.audio_bitrate || "", placeholder: "128k", disabled: isSource });
const row = el("div.vrow",
on,
isSource
? el("div", el("div.vname", { text: v.label || "FHD" }), el("div.locked-note", { text: "source · copy" }))
: name,
isSource ? el("span.locked-note", { text: "as source" }) : height,
isSource ? el("span.locked-note", { text: "copy" }) : (v.audio_only ? el("span.locked-note", { text: "none" }) : vbr),
abr,
isSource
? el("span")
: el("button.tiny.danger.del", { type: "button", text: "Remove", onclick: () => row.remove() }),
);
row.readValue = () => {
if (isSource) return { id: "fhd", label: "FHD", enabled: true, height: 0 };
const h = v.audio_only ? 0 : Math.max(0, parseInt(height.value, 10) || 0);
const label = name.value.trim() || (v.audio_only ? "Audio" : `${h}p`);
return {
id: (v.id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
label,
enabled: on.checked,
height: h,
audio_only: !!v.audio_only,
video_bitrate: v.audio_only ? "" : vbr.value.trim(),
audio_bitrate: abr.value.trim(),
};
};
return row;
}
/** Editor for which formats a stream publishes. */
export function outputEditor(outputs) {
const rows = el("div");
const wrap = el("fieldset",
el("legend", { text: "Publish formats" }),
el("p.hint", {
text: "Every enabled rung is published in each enabled format. The formats share " +
"one encode per rung, so adding a format is far cheaper than adding a rung.",
}),
el("div.col-head.out",
el("span", { text: "On" }), el("span", { text: "Format" }),
el("span", { text: "Segment s" }), el("span", { text: "Playlist len" }),
),
rows,
);
const list = outputs && outputs.length ? outputs : [
{ id: "hls", label: "HLS", format: "hls", enabled: true },
{ id: "cmaf", label: "CMAF", format: "hls_fmp4", enabled: false },
{ id: "dash", label: "DASH", format: "dash", enabled: false },
{ id: "ts", label: "TS", format: "mpegts", enabled: false },
];
for (const o of list) rows.append(outputRow(o));
wrap.readValue = () => Array.from(rows.children).map((r) => r.readValue());
return wrap;
}
const FORMAT_BLURB = {
hls: "index.m3u8 — MPEG-TS HLS, the broadest player support",
hls_fmp4: "cmaf/index.m3u8 — fMP4 segments, better on Safari",
dash: "dash/index.mpd — MPEG-DASH",
mpegts: "/live/<name>.ts — one endless URL, opens in VLC",
};
function outputRow(o) {
const on = el("input", { type: "checkbox", checked: !!o.enabled });
const seg = el("input", { type: "number", min: "0", max: "30", value: o.segment_duration || "", placeholder: "inherit" });
const len = el("input", { type: "number", min: "0", max: "500", value: o.list_size || "", placeholder: "inherit" });
const row = el("div.orow",
on,
el("div",
el("div", { text: o.label || o.id }),
el("div.fmt", { text: FORMAT_BLURB[o.format] || o.format }),
),
seg,
len,
);
row.readValue = () => ({
id: o.id,
label: o.label,
format: o.format,
enabled: on.checked,
segment_duration: parseInt(seg.value, 10) || 0,
list_size: parseInt(len.value, 10) || 0,
});
return row;
}
/**
* An HLS preview player using the vendored hls.js, with native fallback.
*
* @param {string|object} playPathOrOpts
* string path, or { path, choices: [{ label, play_path }] } so the operator
* can pick FHD / HD / SD (or ABR master) before hitting Play preview.
*/
export function player(playPathOrOpts) {
const opts = typeof playPathOrOpts === "string"
? { path: playPathOrOpts, choices: [] }
: (playPathOrOpts || {});
let playPath = opts.path || "";
const choices = Array.isArray(opts.choices) ? opts.choices.filter((c) => c && c.play_path) : [];
if (!playPath && choices.length) playPath = choices[0].play_path;
const video = el("video", { controls: true, playsinline: true, muted: true, preload: "none" });
const note = el("p.hint");
const pathHint = el("p.hint.mono");
setPathHint(playPath);
let quality = null;
if (choices.length > 1) {
quality = el("select.sm", {
title: "Preview quality",
onchange: () => {
playPath = quality.value;
setPathHint(playPath);
// If already playing, switch source immediately.
if (hls || video.src) start();
},
});
for (const c of choices) {
quality.append(el("option", {
value: c.play_path,
text: c.label || c.play_path,
selected: c.play_path === playPath,
}));
}
}
const wrap = el("div.preview-player",
el("div.player-wrap", video),
el("div.row.preview-controls", { style: { marginTop: "8px" } },
quality
? el("label.row", { style: { gap: "6px", alignItems: "center" } },
el("span.muted", { text: "Quality" }),
quality,
)
: null,
el("button.sm", { type: "button", text: "Play preview", onclick: start }),
el("button.ghost.sm", { type: "button", text: "Stop", onclick: stop }),
note,
),
pathHint,
);
let hls = null;
function setPathHint(path) {
pathHint.textContent = path ? `Playing ${path}` : "";
}
async function start() {
stop();
if (quality) playPath = quality.value;
if (!playPath) {
note.textContent = "no playlist to play";
return;
}
setPathHint(playPath);
const url = absURL(playPath);
// Safari plays HLS natively; everywhere else needs hls.js, which is
// served from this host so the page CSP can stay default-src 'self'.
if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = url;
note.textContent = "native HLS";
video.play().catch((e) => (note.textContent = e.message));
return;
}
note.textContent = "loading player…";
try {
const mod = await import("/static/vendor/hls.min.js");
const Hls = mod.default || window.Hls;
if (!Hls || !Hls.isSupported()) {
note.textContent = "this browser cannot play HLS — use the copied link in VLC";
return;
}
hls = new Hls({ lowLatencyMode: false, enableWorker: true });
hls.on(Hls.Events.ERROR, (_e, data) => {
if (data && data.fatal) note.textContent = `player error: ${data.details || data.type}`;
});
hls.loadSource(url);
hls.attachMedia(video);
note.textContent = "hls.js";
video.play().catch(() => {
note.textContent = "ready — press play";
});
} catch (err) {
note.textContent = `could not load the player: ${err.message}`;
}
}
function stop() {
if (hls) {
hls.destroy();
hls = null;
}
video.removeAttribute("src");
video.load();
note.textContent = "";
}
wrap.stop = stop;
return wrap;
}
/** Build preview quality choices from a stream's publish links (HLS/CMAF). */
export function previewChoices(stream) {
const links = Array.isArray(stream && stream.links) ? stream.links : [];
const out = [];
const seen = new Set();
for (const l of links) {
if (!l || !l.play_path) continue;
const fmt = String(l.format || "").toLowerCase();
// Prefer MPEG-TS HLS and fMP4 HLS; skip DASH/TS fanout for in-browser preview.
if (fmt && fmt !== "hls" && fmt !== "hls_fmp4" && fmt !== "cmaf") continue;
if (seen.has(l.play_path)) continue;
seen.add(l.play_path);
const label = l.master
? "ABR master"
: [l.variant_label || l.variant_id, l.output_label].filter(Boolean).join(" · ") || l.play_path;
out.push({ label, play_path: l.play_path, master: !!l.master });
}
if (!out.length) {
const path = (stream && stream.play_path) || (stream && stream.name ? `/hls/${stream.name}/index.m3u8` : "");
if (path) out.push({ label: "Source", play_path: path });
}
return out;
}
/** A stream's event timeline. */
export function timeline(events) {
const box = el("div.timeline");
if (!events || !events.length) {
box.append(el("div.empty", { text: "Nothing recorded yet." }));
return box;
}
for (const e of events) {
const sev = e.severity === "error" ? "error" : e.severity === "warn" ? "warn" : "info";
box.append(el(`div.ev.${sev}`,
el("span.at", { text: fmtDateTime(e.at), title: e.at }),
pill(e.kind),
el("span.msg",
el("span", { text: e.message || "" }),
e.actor && e.actor !== "system" ? el("span.who", { text: ` — ${e.actor}` }) : null,
),
));
}
return box;
}
/** A tag strip. */
export function tagList(tags) {
const row = el("span.row", { style: { gap: "4px" } });
for (const t of String(tags || "").split(",").filter(Boolean)) {
row.append(pill(t, "tag"));
}
return row;
}
/** Health summary for a stream row, including the staleness age. */
export function healthCell(s) {
return 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: `playlist ${fmtAge(s.playlist_age_s)} old` }) : null,
);
}
/** Replace a container's children with new nodes. */
export function replace(node, ...children) {
clear(node);
append(node, children);
return node;
}

View file

@ -0,0 +1,200 @@
// Client state, kept fresh by a websocket with a polling fallback.
//
// The old dashboard re-fetched everything on a five second timer. Here the
// server pushes health and change deltas, and the timer is only a safety net
// for when the socket is down.
import { api } from "./api.js";
const listeners = new Set();
export const state = {
me: null,
streams: [],
overview: null,
agents: [],
deps: null,
uptimeS: 0,
connected: false,
lastError: "",
};
export function subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
function emit(reason) {
for (const fn of listeners) {
try {
fn(state, reason);
} catch (err) {
console.error("subscriber failed", err);
}
}
}
export function streamById(id) {
return state.streams.find((s) => String(s.id) === String(id)) || null;
}
let inflight = null;
/** Refresh the stream list and headline numbers. */
export async function refresh(reason = "poll") {
// Coalesce: a websocket burst must not become a burst of requests.
if (inflight) return inflight;
inflight = (async () => {
try {
const [overview, streams, health] = await Promise.all([
api.overview().catch(() => null),
api.streams(),
api.health().catch(() => null),
]);
state.streams = streams.streams || [];
if (overview) state.overview = overview;
if (health) {
state.uptimeS = health.uptime_s || 0;
if (health.deps) state.deps = health.deps;
}
state.lastError = "";
} catch (err) {
state.lastError = err.message || String(err);
} finally {
inflight = null;
emit(reason);
}
})();
return inflight;
}
export function setMe(me) {
state.me = me;
emit("me");
}
export function isAdmin() {
return state.me && state.me.role === "admin";
}
export function canEdit() {
return state.me && (state.me.role === "admin" || state.me.role === "operator");
}
// ---------- websocket ----------
let ws = null;
let reconnectTimer = null;
let backoff = 1000;
let pollTimer = null;
let stopped = false;
const scheduleRefresh = (() => {
let t = null;
return (reason) => {
// Several pushes often arrive together (a restart touches health and the
// stream row); one refresh shortly after covers them all.
clearTimeout(t);
t = setTimeout(() => refresh(reason), 220);
};
})();
export function connect() {
stopped = false;
openSocket();
startPolling();
}
export function disconnect() {
stopped = true;
clearTimeout(reconnectTimer);
clearInterval(pollTimer);
pollTimer = null;
if (ws) {
try {
ws.close();
} catch {
/* already closing */
}
ws = null;
}
state.connected = false;
}
function startPolling() {
clearInterval(pollTimer);
// Slow when pushed to, brisk when the socket is down.
pollTimer = setInterval(() => {
if (!state.connected) refresh("poll-fallback");
else refresh("poll-slow");
}, 15000);
}
function openSocket() {
if (stopped) return;
if (ws) {
try {
ws.close();
} catch {
/* ignore */
}
}
const proto = location.protocol === "https:" ? "wss:" : "ws:";
let sock;
try {
sock = new WebSocket(`${proto}//${location.host}/ws/ui`);
} catch {
scheduleReconnect();
return;
}
ws = sock;
sock.onopen = () => {
state.connected = true;
backoff = 1000;
emit("ws-open");
};
sock.onmessage = (ev) => {
let msg;
try {
msg = JSON.parse(ev.data);
} catch {
return;
}
switch (msg.type) {
case "agents":
case "agent_online":
case "agent_offline":
state.agents = msg.agents || [];
emit("agents");
if (msg.type !== "agents") scheduleRefresh("agent-change");
break;
case "runtime":
case "streams_changed":
case "claims_changed":
scheduleRefresh(msg.type);
break;
default:
break;
}
};
sock.onclose = () => {
if (ws === sock) ws = null;
state.connected = false;
emit("ws-close");
scheduleReconnect();
};
sock.onerror = () => {
// onclose follows, which is where the reconnect is scheduled.
};
}
function scheduleReconnect() {
if (stopped) return;
clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(openSocket, backoff);
backoff = Math.min(backoff * 2, 20000);
}

View file

@ -0,0 +1,350 @@
// DOM and formatting helpers.
//
// Everything here builds nodes and sets textContent rather than assembling
// HTML strings. A stream title, a log line and an error message all come from
// outside, and node building makes it impossible for them to become markup.
/**
* el("div.card", {title: "x"}, child, ...) -> HTMLElement
* The tag accepts a CSS-like shorthand: "span.pill.ok" or "#id.cls".
*/
export function el(spec, attrs, ...children) {
let tag = "div";
const classes = [];
let id = "";
const m = String(spec).match(/^([a-zA-Z][a-zA-Z0-9-]*)?((?:[.#][^.#]+)*)$/);
if (m) {
if (m[1]) tag = m[1];
for (const part of (m[2] || "").match(/[.#][^.#]+/g) || []) {
if (part[0] === ".") classes.push(part.slice(1));
else id = part.slice(1);
}
}
const node = document.createElement(tag);
if (classes.length) node.className = classes.join(" ");
if (id) node.id = id;
if (attrs && (typeof attrs !== "object" || attrs instanceof Node || Array.isArray(attrs))) {
children.unshift(attrs);
attrs = null;
}
for (const [k, v] of Object.entries(attrs || {})) {
if (v === null || v === undefined || v === false) continue;
if (k === "class") node.className = v;
else if (k === "text") node.textContent = v;
else if (k === "html") throw new Error("el(): raw html is not allowed");
else if (k === "dataset") Object.assign(node.dataset, v);
else if (k === "style" && typeof v === "object") Object.assign(node.style, v);
else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v);
else if (v === true) node.setAttribute(k, "");
else node.setAttribute(k, v);
}
append(node, children);
return node;
}
export function append(node, children) {
for (const c of children.flat(4)) {
if (c === null || c === undefined || c === false || c === "") continue;
node.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
return node;
}
export function clear(node) {
while (node.firstChild) node.removeChild(node.firstChild);
return node;
}
export function $(sel, root = document) {
return root.querySelector(sel);
}
export function $$(sel, root = document) {
return Array.from(root.querySelectorAll(sel));
}
/** pill("ok") -> a status chip. */
export function pill(text, extraClass) {
const cls = String(text || "unknown").toLowerCase().replace(/[^a-z0-9]+/g, "-");
return el(`span.pill.${cls}${extraClass ? "." + extraClass : ""}`, { text: text || "unknown" });
}
// ---------- formatting ----------
export function fmtSeconds(s) {
s = Math.max(0, Math.round(Number(s) || 0));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m ${s % 60}s`;
const h = Math.floor(m / 60);
if (h < 24) return `${h}h ${m % 60}m`;
return `${Math.floor(h / 24)}d ${h % 24}h`;
}
export function fmtAge(s) {
if (s === null || s === undefined || s === 0) return "—";
const n = Number(s);
if (!isFinite(n)) return "—";
return n < 10 ? `${n.toFixed(1)}s` : `${Math.round(n)}s`;
}
export function fmtBitrate(mbps) {
const n = Number(mbps) || 0;
if (n <= 0) return "—";
return n < 10 ? `${n.toFixed(2)} Mb/s` : `${n.toFixed(1)} Mb/s`;
}
export function fmtTime(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (isNaN(d)) return "—";
return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}
export function fmtDateTime(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (isNaN(d)) return "—";
return d.toLocaleString([], {
month: "short", day: "numeric", hour: "2-digit", minute: "2-digit",
});
}
/** fmtRelative("2026-01-01T...") -> "in 4m" / "6m ago" */
export function fmtRelative(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (isNaN(d)) return "—";
const diff = d.getTime() - Date.now();
const abs = Math.abs(diff);
const mins = Math.round(abs / 60000);
let label;
if (abs < 45000) label = "now";
else if (mins < 60) label = `${mins}m`;
else if (mins < 60 * 24) label = `${Math.round(mins / 60)}h`;
else label = `${Math.round(mins / 1440)}d`;
if (label === "now") return "now";
return diff > 0 ? `in ${label}` : `${label} ago`;
}
export function absURL(path) {
if (!path) return "";
try {
return new URL(path, location.origin).href;
} catch {
return path;
}
}
// ---------- interaction ----------
const TOAST_MAX = 3;
export function toast(msg, isError) {
const stack = $("#toast-stack");
if (!stack) return;
const node = el(`div.toast${isError ? ".err" : ""}`, {
role: isError ? "alert" : "status",
text: String(msg),
});
stack.append(node);
while (stack.children.length > TOAST_MAX) {
stack.firstElementChild.remove();
}
const ms = isError ? 5200 : 2400;
setTimeout(() => {
node.classList.add("out");
setTimeout(() => node.remove(), 200);
}, ms);
}
/** Mark a button busy for the duration of an async fn. */
export async function withBusy(btn, fn) {
if (!btn) return fn();
const prev = btn.getAttribute("aria-busy") === "true";
if (prev) return;
btn.setAttribute("aria-busy", "true");
btn.disabled = true;
try {
return await fn();
} finally {
btn.removeAttribute("aria-busy");
btn.disabled = false;
}
}
/** Flip a copy button label to "Copied" briefly; still toasts as fallback. */
export function markCopied(btn, ms = 1200) {
if (!btn) return;
const prev = btn.dataset.prevLabel || btn.textContent;
btn.dataset.prevLabel = prev;
btn.textContent = "Copied";
btn.classList.add("copied");
clearTimeout(Number(btn.dataset.copyTimer || 0));
btn.dataset.copyTimer = String(setTimeout(() => {
btn.textContent = btn.dataset.prevLabel || "Copy";
btn.classList.remove("copied");
}, ms));
}
export async function copyText(text, label = "link", btn) {
if (!text) return;
const ok = async () => {
if (btn) markCopied(btn);
else toast(`Copied ${label}`);
};
try {
await navigator.clipboard.writeText(text);
await ok();
return;
} catch {
// Clipboard API needs a secure context; plain HTTP behind a proxy is a
// normal deployment, so fall back rather than failing.
}
const ta = el("textarea", { style: { position: "fixed", left: "-9999px" } });
ta.value = text;
document.body.append(ta);
ta.select();
try {
document.execCommand("copy");
await ok();
} catch {
toast("Could not copy — select the text instead", true);
}
ta.remove();
}
/** Open a modal built from nodes. Returns a close function. */
export function openModal(...children) {
const dlg = $("#modal");
const body = $("#modal-body");
// Always rebuild body here. Do not clear on the dialog "close" event: callers
// often close() then immediately openModal() again (e.g. create API key →
// show secret), and an async close handler would wipe the new content.
clear(body);
append(body, children);
const close = () => {
if (dlg.open) dlg.close();
};
if (!dlg.open) dlg.showModal();
return close;
}
/** A yes/no dialog that resolves to a boolean. */
export function confirmDialog(title, detail, confirmLabel = "Confirm", danger = true) {
return new Promise((resolve) => {
let settled = false;
const done = (v) => {
if (settled) return;
settled = true;
close();
resolve(v);
};
const close = openModal(
el("h2", { text: title }),
detail ? el("p.hint", { text: detail }) : null,
el("div.row.end", { style: { marginTop: "16px" } },
el("button.ghost", { text: "Cancel", onclick: () => done(false) }),
el(danger ? "button.danger" : "button", { text: confirmLabel, onclick: () => done(true) }),
),
);
$("#modal").addEventListener("close", () => done(false), { once: true });
});
}
/** Debounce for filter inputs. */
export function debounce(fn, ms = 180) {
let t = null;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
}
// ---------- sparkline ----------
/**
* sparkline(points, pick) -> inline SVG.
* Drawn by hand rather than with a chart library: one series, no axes, and no
* reason to ship a dependency for it.
*/
export function sparkline(points, pick, opts = {}) {
const w = opts.width || 240;
const h = opts.height || 44;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "spark");
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
svg.setAttribute("preserveAspectRatio", "none");
svg.setAttribute("role", "img");
const vals = (points || []).map(pick).map((v) => (isFinite(v) ? Number(v) : 0));
if (vals.length < 2) {
svg.setAttribute("aria-label", "not enough data yet");
const t = document.createElementNS(svg.namespaceURI, "text");
t.setAttribute("x", 4);
t.setAttribute("y", h / 2 + 4);
t.setAttribute("fill", "currentColor");
t.setAttribute("font-size", "10");
t.setAttribute("opacity", ".55");
t.textContent = "collecting…";
svg.append(t);
return svg;
}
const max = Math.max(...vals, opts.min || 0.0001);
const stepX = w / (vals.length - 1);
const y = (v) => h - 2 - (v / max) * (h - 6);
const pts = vals.map((v, i) => `${(i * stepX).toFixed(2)},${y(v).toFixed(2)}`);
const area = document.createElementNS(svg.namespaceURI, "path");
area.setAttribute("class", "area");
area.setAttribute("d", `M0,${h} L${pts.join(" L")} L${w},${h} Z`);
const line = document.createElementNS(svg.namespaceURI, "polyline");
line.setAttribute("class", "line");
line.setAttribute("points", pts.join(" "));
svg.append(area, line);
svg.setAttribute("aria-label", `${opts.label || "series"}, latest ${vals[vals.length - 1]}, peak ${max}`);
return svg;
}
// ---------- keyed list rendering ----------
/**
* Reconcile a list of rows into a parent by key.
*
* The old dashboard rebuilt the whole table with innerHTML every five
* seconds, which threw away focus, scroll position, text selection and any
* open menu. This updates in place instead: existing rows are patched, new
* ones inserted, departed ones removed.
*/
export function reconcile(parent, items, keyOf, create, update) {
const existing = new Map();
for (const node of Array.from(parent.children)) {
const k = node.dataset.key;
if (k !== undefined) existing.set(k, node);
else node.remove();
}
let prev = null;
for (const item of items) {
const key = String(keyOf(item));
let node = existing.get(key);
if (node) {
existing.delete(key);
update(node, item);
} else {
node = create(item);
node.dataset.key = key;
}
// Place it after the previous row, moving it only when out of order.
const want = prev ? prev.nextSibling : parent.firstChild;
if (node !== want) parent.insertBefore(node, want);
prev = node;
}
for (const node of existing.values()) node.remove();
}
/** Set textContent only when it differs, so selections survive updates. */
export function setText(node, text) {
const s = text === null || text === undefined ? "" : String(text);
if (node.textContent !== s) node.textContent = s;
}

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;
}

View file

@ -0,0 +1,13 @@
# Vendored third-party assets
These are served from streamd itself rather than a CDN, so the dashboard's
Content-Security-Policy can stay `default-src 'self'`. Loading them from a CDN
would mean trusting a third party with script execution on a page that holds an
operator session.
| File | Version | Source |
|---|---|---|
| `hls.min.js` | 1.5.17 | https://cdn.jsdelivr.net/npm/hls.js@1.5.17/dist/hls.min.js |
To update, download the new version, replace the file and change the version
here. Nothing else references the version number.

File diff suppressed because one or more lines are too long