streamd: preview quality picker, dashboard polish, C4 wrap keys
- 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:
parent
b3955bd81e
commit
066e018749
113 changed files with 19002 additions and 1541 deletions
|
|
@ -7,61 +7,67 @@ single binary as `drm serve`.
|
|||
apps/streamd/
|
||||
servecmd/ the command body, imported by apps/cli
|
||||
internal/api HTTP handlers
|
||||
internal/auth sessions, API keys, roles
|
||||
internal/db SQLite store
|
||||
internal/ui dashboard (index.html, app.js, app.css)
|
||||
internal/ui dashboard
|
||||
internal/supervisor downloader + ffmpeg supervision
|
||||
internal/ws agent heartbeat
|
||||
internal/ws agent + dashboard websockets
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
|
||||
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
```
|
||||
|
||||
Port 8083 by default, to stay clear of anything already on 8080/8081. On start,
|
||||
missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt)
|
||||
unless you pass `--skip-deps`. Flags / env still win when set.
|
||||
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
|
||||
non-loopback address) logs a startup warning — put TLS in front, or keep loopback
|
||||
and reverse-proxy. Port 8083 stays clear of anything already on 8080/8081.
|
||||
|
||||
Open `http://HOST:8083/` and put the token in the header box for mutating actions.
|
||||
Add a stream with an `.mpd` URL; Widevine keys are optional for clear content.
|
||||
Optional per-stream SOCKS5/HTTP `proxy` routes origin fetches (geo egress).
|
||||
On start, missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE,
|
||||
mp4decrypt) unless you pass `--skip-deps`.
|
||||
|
||||
## API
|
||||
### Auth
|
||||
|
||||
The old shared bearer token is optional and discouraged. Prefer:
|
||||
|
||||
1. First-run setup creates an **admin** account (or `--admin-user` / `--admin-pass`).
|
||||
2. Sign in at the dashboard (session cookie + CSRF).
|
||||
3. Create **API keys** (Settings → API keys) for agents and scripts — roles
|
||||
`admin` / `operator` / `viewer`.
|
||||
|
||||
Legacy `--token` / `STREAMD_TOKEN` still works as an admin API key and logs a
|
||||
warning so you can migrate.
|
||||
|
||||
`GET /api/health` stays readable without a principal (liveness only). Stream list,
|
||||
credentials, and mutations need a session or API key.
|
||||
|
||||
## API (short)
|
||||
|
||||
| Method | Path | Notes |
|
||||
|---|---|---|
|
||||
| GET | `/api/health` | liveness + uptime |
|
||||
| GET | `/api/apps` | modules/<name>/ providers, channels, registered rewriters |
|
||||
| GET | `/api/streams` | list + runtime (the agent polls this) |
|
||||
| POST | `/api/streams` | create |
|
||||
| GET | `/api/health` | liveness (+ deps when authenticated) |
|
||||
| GET | `/api/apps` | modules, channels, rewriters |
|
||||
| GET | `/api/streams` | list + runtime (agent polls this) |
|
||||
| POST | `/api/streams` | create (`enabled` defaults false unless set; use the form checkbox) |
|
||||
| GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete |
|
||||
| POST | `/api/streams/:id/start\|stop\|restart` | desired state |
|
||||
| POST | `/api/streams/:id/credentials` | `{mpd,key?,pssh?,auth?,pid?}` — key optional; restarts if enabled |
|
||||
| POST | `/api/streams/:id/claim` | agent lease (`agent_id`, TTL ~3m) |
|
||||
| POST | `/api/streams/:id/claim/release` | release lease |
|
||||
| POST | `/api/streams/:id/capture` | ask connected agents to refresh credentials now |
|
||||
| POST | `/api/streams/:id/credentials` | `{mpd,key?,…}` — restarts if enabled |
|
||||
| POST | `/api/streams/:id/claim` | agent lease |
|
||||
|
||||
Mutating routes need `Authorization: Bearer TOKEN` (or `X-Streamd-Token`, or
|
||||
`?token=`). HLS output is served from `--data/www` at `/hls/<name>/index.m3u8`.
|
||||
HLS output is served from `--data/www` at `/hls/<name>/index.m3u8`.
|
||||
|
||||
Installation-wide settings (`idle_timeout_s`, `default_on_demand`,
|
||||
`default_outputs`, packager knobs) apply when creating a stream that omits those
|
||||
fields, or at the next media start for packager knobs.
|
||||
|
||||
## No provider knowledge
|
||||
|
||||
The schema has no provider defaults, and the dashboard's app/channel pickers come
|
||||
from `/api/apps`. Per-stream downloader settings resolve at start time:
|
||||
App/channel pickers come from `/api/apps`. Downloader settings resolve at start:
|
||||
|
||||
```text
|
||||
stored row -> the stream's app module (app.StreamDefaults) -> neutral defaults
|
||||
stored row -> app module (StreamDefaults) -> installation settings -> neutral defaults
|
||||
```
|
||||
|
||||
The manifest rewriter is a registry lookup on the stream's `rewriter` column, and
|
||||
HLS is detected from the manifest shape — not from an app or stream name.
|
||||
|
||||
## Status
|
||||
|
||||
| Area | State |
|
||||
|---|---|
|
||||
| serve + SQLite + CRUD UI + claims + credentials | done |
|
||||
| `/api/apps` + module-driven defaults | done |
|
||||
| Real downloader/ffmpeg workers + playlist health | partial — least exercised path |
|
||||
|
||||
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
||||
|
|
|
|||
|
|
@ -4,13 +4,16 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/deps"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
type Supervisor interface {
|
||||
|
|
@ -19,63 +22,103 @@ type Supervisor interface {
|
|||
Restart(id int64) error
|
||||
}
|
||||
|
||||
// CaptureRequester asks connected agents to refresh a stream's credentials
|
||||
// now, rather than on their next poll. Implemented by the websocket hub.
|
||||
type CaptureRequester interface {
|
||||
RequestCapture(st db.Stream, reason string) int
|
||||
}
|
||||
|
||||
// Viewers reports the live client count per stream, from the HLS gate.
|
||||
type Viewers interface {
|
||||
ViewersFor(streamName string) int
|
||||
}
|
||||
|
||||
// Notifier pushes change notifications to dashboards and agents.
|
||||
type Notifier interface {
|
||||
NotifyStreamChanged(name, reason string)
|
||||
}
|
||||
|
||||
// Scheduler exposes the upcoming schedule for the dashboard.
|
||||
type Scheduler interface {
|
||||
Upcoming(limit int) any
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
Store *db.Store
|
||||
Token string
|
||||
Auth *auth.Store
|
||||
Trust httpx.Trust
|
||||
Supervisor Supervisor
|
||||
Capture CaptureRequester
|
||||
Viewers Viewers
|
||||
Notifier Notifier
|
||||
Scheduler Scheduler
|
||||
StartedAt time.Time
|
||||
Deps deps.Status
|
||||
WWWRoot string // data/www — used to report variant playlist health
|
||||
LogRoot string // data/logs — source for the log tail endpoints
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
func (h *Handler) Mount(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/health", h.health)
|
||||
mux.HandleFunc("/api/streams", h.streams)
|
||||
mux.HandleFunc("/api/streams/", h.streamAction)
|
||||
mux.HandleFunc("/api/overview", h.overview)
|
||||
h.MountControl(mux)
|
||||
mux.HandleFunc("/api/apps", h.apps)
|
||||
mux.HandleFunc("/api/modules", h.modules)
|
||||
mux.HandleFunc("/api/modules/", h.modules)
|
||||
}
|
||||
|
||||
func (h *Handler) auth(w http.ResponseWriter, r *http.Request) bool {
|
||||
if h.Token == "" {
|
||||
return true
|
||||
func (h *Handler) logger() *slog.Logger {
|
||||
if h.Log != nil {
|
||||
return h.Log
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return true
|
||||
}
|
||||
auth := r.Header.Get("Authorization")
|
||||
tok := strings.TrimPrefix(auth, "Bearer ")
|
||||
if tok == "" {
|
||||
tok = r.Header.Get("X-Streamd-Token")
|
||||
}
|
||||
if tok == "" {
|
||||
tok = r.URL.Query().Get("token")
|
||||
}
|
||||
if tok != h.Token {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return slog.Default()
|
||||
}
|
||||
|
||||
// audit records a mutating request against the caller.
|
||||
func (h *Handler) audit(r *http.Request, p *auth.Principal, status int, note string) {
|
||||
if h.Auth == nil {
|
||||
return
|
||||
}
|
||||
h.Auth.AuditRequest(p, h.Trust, r, status, note)
|
||||
}
|
||||
|
||||
// health is the one route that stays readable without a principal: a reverse
|
||||
// proxy and a container orchestrator both need it for liveness checks. It
|
||||
// deliberately reveals nothing but liveness and whether the media tools are
|
||||
// present — no stream names, no paths.
|
||||
func (h *Handler) health(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
out := map[string]any{
|
||||
"ok": true,
|
||||
"service": "streamd",
|
||||
"uptime_s": time.Since(h.StartedAt).Seconds(),
|
||||
"started_at": h.StartedAt.UTC().Format(time.RFC3339),
|
||||
"deps": h.Deps,
|
||||
})
|
||||
}
|
||||
// Tool paths are filesystem layout, so only an authenticated caller gets
|
||||
// them. Anonymous callers still get a usable liveness answer.
|
||||
if p := auth.From(r); p != nil {
|
||||
out["deps"] = h.Deps
|
||||
out["role"] = string(p.Role)
|
||||
} else {
|
||||
out["deps"] = h.Deps.Public()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
// Reading the stream list now requires a principal. It used to be
|
||||
// open, and it carries manifest URLs and (before redaction) keys.
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListStreams()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
|
|
@ -85,11 +128,15 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
|
|||
list = []db.Stream{}
|
||||
}
|
||||
for i := range list {
|
||||
h.enrichVariantHealth(&list[i])
|
||||
h.enrich(&list[i])
|
||||
// The list is never a place for credentials, whatever the role:
|
||||
// it is the response the agent polls and the dashboard renders.
|
||||
list[i].Redact()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"streams": list})
|
||||
case http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in db.CreateStream
|
||||
|
|
@ -102,8 +149,11 @@ func (h *Handler) streams(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.enrichVariantHealth(&st)
|
||||
writeJSON(w, http.StatusCreated, st)
|
||||
h.audit(r, p, http.StatusCreated, "created stream "+st.Name)
|
||||
h.logger().Info("stream created", "stream", st.Name, "by", p.Actor())
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "created")
|
||||
writeJSON(w, http.StatusCreated, st.Redacted())
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
|
|
@ -131,18 +181,64 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
sub = parts[2]
|
||||
}
|
||||
|
||||
switch {
|
||||
case action == "events" && r.Method == http.MethodPost:
|
||||
h.postEvent(w, r, id)
|
||||
return
|
||||
case action == "events" && r.Method == http.MethodGet:
|
||||
h.listEvents(w, r, id)
|
||||
return
|
||||
case action == "metrics" && r.Method == http.MethodGet:
|
||||
h.listMetrics(w, r, id)
|
||||
return
|
||||
case action == "logs" && sub == "stream" && r.Method == http.MethodGet:
|
||||
h.streamLogsSSE(w, r, id)
|
||||
return
|
||||
case action == "logs" && r.Method == http.MethodGet:
|
||||
h.streamLogs(w, r, id)
|
||||
return
|
||||
case action == "schedules":
|
||||
h.streamSchedules(w, r, id)
|
||||
return
|
||||
case action == "duplicate" && r.Method == http.MethodPost:
|
||||
h.duplicate(w, r, id)
|
||||
return
|
||||
case action == "probe" && r.Method == http.MethodPost:
|
||||
h.probe(w, r, id)
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case action == "" && r.Method == http.MethodGet:
|
||||
p, ok := auth.Guard(w, r, auth.RoleViewer)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
h.enrichVariantHealth(&st)
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.enrich(&st)
|
||||
// Credentials come back only for an operator who explicitly asks, and
|
||||
// asking is recorded.
|
||||
reveal := truthy(r.URL.Query().Get("reveal"))
|
||||
if reveal && p.Role.AtLeast(auth.RoleOperator) {
|
||||
h.audit(r, p, http.StatusOK, "revealed credentials for stream "+st.Name)
|
||||
h.logger().Info("credentials revealed", "stream", st.Name, "by", p.Actor())
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
return
|
||||
}
|
||||
if reveal {
|
||||
// Say so rather than silently returning a blank key.
|
||||
writeErr(w, http.StatusForbidden, "role "+string(p.Role)+" cannot reveal credentials (needs operator)")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut):
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in db.PatchStream
|
||||
|
|
@ -156,6 +252,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "edited stream "+st.Name+changeNote(before, st, in))
|
||||
// Editing mpd/key/headers/variants must tear down the live media worker
|
||||
// and bring up a fresh instance with the new credentials.
|
||||
if h.Supervisor != nil && credentialsChanged(before, st, in) {
|
||||
|
|
@ -166,13 +263,16 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
st, _ = h.Store.GetStream(id)
|
||||
}
|
||||
h.enrichVariantHealth(&st)
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "patched")
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "" && r.Method == http.MethodDelete:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
before, _ := h.Store.GetStream(id)
|
||||
if h.Supervisor != nil {
|
||||
_ = h.Supervisor.Stop(id)
|
||||
}
|
||||
|
|
@ -180,10 +280,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "deleted stream "+before.Name)
|
||||
h.logger().Info("stream deleted", "stream", before.Name, "by", p.Actor())
|
||||
h.notify(before.Name, "deleted")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
|
||||
case action == "start" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.SetEnabled(id, true)
|
||||
|
|
@ -191,6 +295,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "started stream "+st.Name)
|
||||
if h.Supervisor != nil {
|
||||
if err := h.Supervisor.Start(id); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
|
|
@ -198,10 +303,13 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
st, _ = h.Store.GetStream(id)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "started")
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "stop" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if h.Supervisor != nil {
|
||||
|
|
@ -212,10 +320,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.audit(r, p, http.StatusOK, "stopped stream "+st.Name)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "stopped")
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "restart" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.SetEnabled(id, true)
|
||||
|
|
@ -223,6 +335,7 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "restarted stream "+st.Name)
|
||||
if h.Supervisor != nil {
|
||||
if err := h.Supervisor.Restart(id); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
|
|
@ -230,10 +343,44 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
st, _ = h.Store.GetStream(id)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "restarted")
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "capture" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
if h.Capture == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "capture push is not available")
|
||||
return
|
||||
}
|
||||
n := h.Capture.RequestCapture(st, "manual")
|
||||
h.audit(r, p, http.StatusOK, "requested capture for stream "+st.Name)
|
||||
h.logger().Info("capture requested", "stream", st.Name, "by", p.Actor(), "agents", n)
|
||||
if n > 0 {
|
||||
h.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo,
|
||||
"manual capture requested (%d agent(s))", n)
|
||||
} else {
|
||||
h.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn,
|
||||
"manual capture requested but no agents are connected")
|
||||
}
|
||||
h.notify(st.Name, "capture")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"stream": st.Name,
|
||||
"agents_notified": n,
|
||||
})
|
||||
|
||||
case action == "credentials" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var cred db.Credentials
|
||||
|
|
@ -246,6 +393,10 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// Never log the credential itself, only that it arrived.
|
||||
h.audit(r, p, http.StatusOK, "set credentials for stream "+st.Name+credNote(st))
|
||||
h.logger().Info("credentials updated", "stream", st.Name, "by", p.Actor(),
|
||||
"has_key", st.HasKey, "key_valid", st.KeyValid)
|
||||
_ = h.Store.ReleaseClaim(id, "")
|
||||
// Always kill the old media worker; start a fresh one when enabled.
|
||||
if h.Supervisor != nil {
|
||||
|
|
@ -256,10 +407,13 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
st, _ = h.Store.GetStream(id)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "credentials")
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "claim" && sub == "" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
|
|
@ -277,10 +431,14 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
_ = p
|
||||
// A claim is high-volume agent bookkeeping, so it is not audited; the
|
||||
// capture events that follow it are.
|
||||
h.enrich(&st)
|
||||
writeJSON(w, http.StatusOK, st.Redacted())
|
||||
|
||||
case action == "claim" && sub == "release" && r.Method == http.MethodPost:
|
||||
if !h.auth(w, r) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
|
|
@ -298,6 +456,34 @@ func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
// enrich fills the response-only fields: per-output health, publish links and
|
||||
// the live viewer count.
|
||||
func (h *Handler) enrich(st *db.Stream) {
|
||||
h.enrichVariantHealth(st)
|
||||
h.enrichLinks(st)
|
||||
if h.Viewers != nil {
|
||||
st.Viewers = h.Viewers.ViewersFor(st.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// notify pushes a stream change to every connected dashboard and agent so
|
||||
// they do not wait for the next poll.
|
||||
func (h *Handler) notify(name, reason string) {
|
||||
if h.Notifier == nil || strings.TrimSpace(name) == "" {
|
||||
return
|
||||
}
|
||||
h.Notifier.NotifyStreamChanged(name, reason)
|
||||
}
|
||||
|
||||
// truthy accepts the spellings a query string realistically carries.
|
||||
func truthy(s string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func readJSON(r *http.Request, dst any) error {
|
||||
defer r.Body.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
|
|
@ -322,8 +508,50 @@ func writeErr(w http.ResponseWriter, code int, msg string) {
|
|||
writeJSON(w, code, map[string]any{"error": msg})
|
||||
}
|
||||
|
||||
// credNote summarises a credential update for the audit trail without
|
||||
// recording any part of the secret.
|
||||
func credNote(st db.Stream) string {
|
||||
switch {
|
||||
case !st.HasKey:
|
||||
return " (clear, no key)"
|
||||
case st.KeyValid:
|
||||
return " (key ok)"
|
||||
default:
|
||||
return " (key present but unparseable)"
|
||||
}
|
||||
}
|
||||
|
||||
// changeNote lists which fields a patch actually touched, for the audit row.
|
||||
func changeNote(before, after db.Stream, in db.PatchStream) string {
|
||||
var changed []string
|
||||
add := func(name string, differs bool) {
|
||||
if differs {
|
||||
changed = append(changed, name)
|
||||
}
|
||||
}
|
||||
add("mpd", in.MPD != nil && before.MPD != after.MPD)
|
||||
// Record that the key changed, never what it changed to.
|
||||
add("key", in.Key != nil && before.Key != after.Key)
|
||||
add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
|
||||
add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
|
||||
add("variants", before.VariantsJSON != after.VariantsJSON)
|
||||
add("outputs", before.OutputsJSON != after.OutputsJSON)
|
||||
add("settings", before.SettingsJSON != after.SettingsJSON)
|
||||
add("enabled", before.Enabled != after.Enabled)
|
||||
add("on_demand", before.OnDemand != after.OnDemand)
|
||||
add("public", before.Public != after.Public)
|
||||
add("drm_mode", before.DRMMode != after.DRMMode)
|
||||
add("title", in.Title != nil && before.Title != after.Title)
|
||||
add("tags", in.Tags != nil && before.Tags != after.Tags)
|
||||
if len(changed) == 0 {
|
||||
return " (no effective change)"
|
||||
}
|
||||
return " [" + strings.Join(changed, ",") + "]"
|
||||
}
|
||||
|
||||
// credentialsChanged is true when the patch touched mpd, key, headers, proxy,
|
||||
// or variants that the live NRE/ffmpeg worker is already using.
|
||||
// variants, outputs or packager settings that the live NRE/ffmpeg worker is
|
||||
// already using.
|
||||
func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
|
||||
if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) {
|
||||
return true
|
||||
|
|
@ -342,5 +570,15 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
|
|||
return true
|
||||
}
|
||||
}
|
||||
// The output set and the packager knobs are both baked into the ffmpeg
|
||||
// command line, so changing either needs a fresh packager.
|
||||
if in.OutputsJSON != nil || len(in.Outputs) > 0 {
|
||||
if strings.TrimSpace(before.OutputsJSON) != strings.TrimSpace(after.OutputsJSON) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if in.SettingsJSON != nil && strings.TrimSpace(before.SettingsJSON) != strings.TrimSpace(after.SettingsJSON) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package api
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/repo"
|
||||
|
|
@ -28,6 +29,9 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
out := []appInfo{}
|
||||
listed, err := modhost.ListAll(repo.Root())
|
||||
if err != nil {
|
||||
|
|
|
|||
620
apps/streamd/internal/api/control.go
Normal file
620
apps/streamd/internal/api/control.go
Normal file
|
|
@ -0,0 +1,620 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// MountControl adds the bulk, duplicate, probe, settings and schedule routes.
|
||||
func (h *Handler) MountControl(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/streams/bulk", h.bulk)
|
||||
mux.HandleFunc("/api/settings", h.settings)
|
||||
mux.HandleFunc("/api/schedules", h.schedules)
|
||||
mux.HandleFunc("/api/schedules/", h.scheduleByID)
|
||||
}
|
||||
|
||||
// ---------- bulk actions ----------
|
||||
|
||||
func (h *Handler) bulk(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
IDs []int64 `json:"ids"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
action := strings.ToLower(strings.TrimSpace(in.Action))
|
||||
switch action {
|
||||
case "start", "stop", "restart":
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "action must be start, stop or restart")
|
||||
return
|
||||
}
|
||||
if len(in.IDs) == 0 {
|
||||
writeErr(w, http.StatusBadRequest, "ids required")
|
||||
return
|
||||
}
|
||||
if len(in.IDs) > 200 {
|
||||
writeErr(w, http.StatusBadRequest, "too many ids in one request (max 200)")
|
||||
return
|
||||
}
|
||||
|
||||
type result struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
OK bool `json:"ok"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
results := make([]result, 0, len(in.IDs))
|
||||
okCount := 0
|
||||
for _, id := range in.IDs {
|
||||
res := result{ID: id}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
res.Error = "not found"
|
||||
results = append(results, res)
|
||||
continue
|
||||
}
|
||||
res.Name = st.Name
|
||||
// One failure must not abort the rest of the batch: an operator
|
||||
// stopping everything during an incident needs the others to stop.
|
||||
if err := h.applyAction(id, action); err != nil {
|
||||
res.Error = err.Error()
|
||||
} else {
|
||||
res.OK = true
|
||||
okCount++
|
||||
h.notify(st.Name, "bulk_"+action)
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
h.audit(r, p, http.StatusOK,
|
||||
fmt.Sprintf("bulk %s on %d stream(s), %d succeeded", action, len(in.IDs), okCount))
|
||||
h.logger().Info("bulk action", "action", action, "requested", len(in.IDs), "ok", okCount, "by", p.Actor())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"action": action, "results": results, "ok_count": okCount})
|
||||
}
|
||||
|
||||
func (h *Handler) applyAction(id int64, action string) error {
|
||||
switch action {
|
||||
case "start":
|
||||
if _, err := h.Store.SetEnabled(id, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Supervisor != nil {
|
||||
return h.Supervisor.Start(id)
|
||||
}
|
||||
case "stop":
|
||||
if h.Supervisor != nil {
|
||||
if err := h.Supervisor.Stop(id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := h.Store.SetEnabled(id, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case "restart":
|
||||
if _, err := h.Store.SetEnabled(id, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Supervisor != nil {
|
||||
return h.Supervisor.Restart(id)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------- duplicate ----------
|
||||
|
||||
func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
src, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
_ = readJSON(r, &in)
|
||||
name := strings.TrimSpace(in.Name)
|
||||
if name == "" {
|
||||
name = src.Name + "-copy"
|
||||
}
|
||||
title := strings.TrimSpace(in.Title)
|
||||
if title == "" {
|
||||
title = src.Title + " (copy)"
|
||||
}
|
||||
// Everything about how the stream is produced and published is copied.
|
||||
// The copy starts disabled: duplicating a live channel should not quietly
|
||||
// double the transcode load.
|
||||
disabled := false
|
||||
st, err := h.Store.CreateStream(db.CreateStream{
|
||||
Name: name,
|
||||
Title: title,
|
||||
Description: src.Description,
|
||||
Tags: src.Tags,
|
||||
App: src.App,
|
||||
Channel: src.Channel,
|
||||
MPD: src.MPD,
|
||||
Key: src.Key,
|
||||
HeadersJSON: src.HeadersJSON,
|
||||
Proxy: src.Proxy,
|
||||
VideoSelect: src.VideoSelect,
|
||||
AudioSelect: src.AudioSelect,
|
||||
Rewriter: src.Rewriter,
|
||||
VariantsJSON: src.VariantsJSON,
|
||||
OutputsJSON: src.OutputsJSON,
|
||||
SettingsJSON: src.SettingsJSON,
|
||||
DRMMode: src.DRMMode,
|
||||
OnDemand: &src.OnDemand,
|
||||
IdleTimeoutS: &src.IdleTimeoutS,
|
||||
Public: &src.Public,
|
||||
Enabled: &disabled,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusCreated, "duplicated stream "+src.Name+" as "+st.Name)
|
||||
h.Store.Eventf(st.ID, db.EventCreated, db.SevInfo, "duplicated from %s", src.Name)
|
||||
h.enrich(&st)
|
||||
h.notify(st.Name, "duplicated")
|
||||
writeJSON(w, http.StatusCreated, st.Redacted())
|
||||
}
|
||||
|
||||
// ---------- manifest probe ----------
|
||||
|
||||
// probe fetches a stream's manifest through its own proxy and headers and
|
||||
// reports what it finds, without starting anything. It answers "is the URL
|
||||
// still good, and does it need keys?" without a capture or a transcode.
|
||||
func (h *Handler) probe(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
target := strings.TrimSpace(st.MPD)
|
||||
// Allow probing a candidate URL before saving it.
|
||||
var in struct {
|
||||
MPD string `json:"mpd"`
|
||||
}
|
||||
_ = readJSON(r, &in)
|
||||
if v := strings.TrimSpace(in.MPD); v != "" {
|
||||
target = v
|
||||
}
|
||||
if target == "" {
|
||||
writeErr(w, http.StatusBadRequest, "this stream has no manifest URL to probe")
|
||||
return
|
||||
}
|
||||
u, err := url.Parse(target)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
writeErr(w, http.StatusBadRequest, "manifest must be an http(s) URL")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
res := h.doProbe(ctx, st, target)
|
||||
|
||||
h.audit(r, p, http.StatusOK, fmt.Sprintf("probed stream %s: %s", st.Name, res.Summary))
|
||||
h.Store.Eventf(st.ID, db.EventProbe, severityFor(res.OK), "probe: %s", res.Summary)
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func severityFor(ok bool) string {
|
||||
if ok {
|
||||
return db.SevInfo
|
||||
}
|
||||
return db.SevWarn
|
||||
}
|
||||
|
||||
// probeResult is what the dashboard shows after a probe.
|
||||
type probeResult struct {
|
||||
OK bool `json:"ok"`
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status,omitempty"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
Bytes int `json:"bytes,omitempty"`
|
||||
ElapsedMS int64 `json:"elapsed_ms"`
|
||||
Kind string `json:"kind,omitempty"` // dash | hls | unknown
|
||||
Periods int `json:"periods,omitempty"`
|
||||
Representors int `json:"representations,omitempty"`
|
||||
Variants int `json:"variants,omitempty"`
|
||||
Live bool `json:"live"`
|
||||
Encrypted bool `json:"encrypted"`
|
||||
DRMSystems []string `json:"drm_systems,omitempty"`
|
||||
DefaultKID string `json:"default_kid,omitempty"`
|
||||
NeedsKeys bool `json:"needs_keys"`
|
||||
HaveKeys bool `json:"have_keys"`
|
||||
Summary string `json:"summary"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// drmSystemIDs are the well-known Common Encryption system IDs, so a probe can
|
||||
// say which DRM a manifest asks for rather than just "encrypted".
|
||||
var drmSystemIDs = map[string]string{
|
||||
"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed": "Widevine",
|
||||
"9a04f079-9840-4286-ab92-e65be0885f95": "PlayReady",
|
||||
"94ce86fb-07ff-4f43-adb8-93d2fa968ca2": "FairPlay",
|
||||
"1077efec-c0b2-4d02-ace3-3c1e52e2fb4b": "ClearKey",
|
||||
}
|
||||
|
||||
func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) probeResult {
|
||||
res := probeResult{URL: target, HaveKeys: st.KeyValid}
|
||||
start := time.Now()
|
||||
|
||||
client := &http.Client{Timeout: 20 * time.Second}
|
||||
// Fetch through the stream's own proxy, so a geo-restricted origin is
|
||||
// probed the same way the downloader would reach it.
|
||||
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
|
||||
if c, err := httpClientWithProxy(proxy); err == nil {
|
||||
client = c
|
||||
} else {
|
||||
res.Error = "proxy: " + err.Error()
|
||||
res.Summary = "proxy configuration is invalid"
|
||||
return res
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
res.Summary = "could not build the request"
|
||||
return res
|
||||
}
|
||||
for k, v := range headerMapOf(st.HeadersJSON) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
if req.Header.Get("User-Agent") == "" {
|
||||
req.Header.Set("User-Agent", "streamd-probe/1.0")
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
res.ElapsedMS = time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
res.Summary = "the origin could not be reached"
|
||||
return res
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
res.Status = resp.StatusCode
|
||||
res.ContentType = resp.Header.Get("Content-Type")
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
res.Bytes = len(body)
|
||||
res.ElapsedMS = time.Since(start).Milliseconds()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
res.Summary = fmt.Sprintf("origin returned %s", resp.Status)
|
||||
return res
|
||||
}
|
||||
text := string(body)
|
||||
switch {
|
||||
case strings.Contains(text, "<MPD"):
|
||||
res.Kind = "dash"
|
||||
res.Periods = strings.Count(text, "<Period")
|
||||
res.Representors = strings.Count(text, "<Representation")
|
||||
res.Live = strings.Contains(text, `type="dynamic"`)
|
||||
res.Encrypted = strings.Contains(text, "ContentProtection")
|
||||
lower := strings.ToLower(text)
|
||||
for id, name := range drmSystemIDs {
|
||||
if strings.Contains(lower, id) {
|
||||
res.DRMSystems = append(res.DRMSystems, name)
|
||||
}
|
||||
}
|
||||
res.DefaultKID = mpd.ExtractDefaultKID(text)
|
||||
case strings.Contains(text, "#EXTM3U"):
|
||||
res.Kind = "hls"
|
||||
res.Variants = strings.Count(text, "#EXT-X-STREAM-INF")
|
||||
res.Live = !strings.Contains(text, "#EXT-X-ENDLIST")
|
||||
res.Encrypted = strings.Contains(text, "#EXT-X-KEY") || strings.Contains(text, "#EXT-X-SESSION-KEY")
|
||||
if strings.Contains(text, "SAMPLE-AES") {
|
||||
res.DRMSystems = append(res.DRMSystems, "SAMPLE-AES")
|
||||
}
|
||||
default:
|
||||
res.Kind = "unknown"
|
||||
res.Summary = "fetched, but the body is neither a DASH manifest nor an HLS playlist"
|
||||
return res
|
||||
}
|
||||
|
||||
res.OK = true
|
||||
res.NeedsKeys = res.Encrypted
|
||||
res.Summary = h.probeSummary(res)
|
||||
return res
|
||||
}
|
||||
|
||||
func (h *Handler) probeSummary(res probeResult) string {
|
||||
var b strings.Builder
|
||||
if res.Kind == "dash" {
|
||||
fmt.Fprintf(&b, "DASH manifest, %d period(s), %d representation(s)", res.Periods, res.Representors)
|
||||
} else {
|
||||
fmt.Fprintf(&b, "HLS playlist, %d variant(s)", res.Variants)
|
||||
}
|
||||
if res.Live {
|
||||
b.WriteString(", live")
|
||||
} else {
|
||||
b.WriteString(", not live")
|
||||
}
|
||||
switch {
|
||||
case !res.Encrypted:
|
||||
b.WriteString(", clear (no keys needed)")
|
||||
case len(res.DRMSystems) > 0:
|
||||
fmt.Fprintf(&b, ", encrypted (%s)", strings.Join(res.DRMSystems, ", "))
|
||||
default:
|
||||
b.WriteString(", encrypted")
|
||||
}
|
||||
if res.Encrypted && !res.HaveKeys {
|
||||
b.WriteString(" — no usable key stored")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// httpClientWithProxy builds a client routed through a SOCKS5 or HTTP proxy.
|
||||
func httpClientWithProxy(proxyURL string) (*http.Client, error) {
|
||||
u, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "http", "https", "socks5", "socks5h":
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
|
||||
}
|
||||
return &http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(u)},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ---------- settings ----------
|
||||
|
||||
func (h *Handler) settings(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
vals, err := h.Store.GetSettings()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"settings": vals,
|
||||
"effective": h.Store.GlobalPackagerSettings(),
|
||||
})
|
||||
case http.MethodPut, http.MethodPatch:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in map[string]string
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// Only known keys, so a typo does not silently become a stored
|
||||
// setting that never takes effect.
|
||||
allowed := map[string]bool{
|
||||
db.SettingHLSTime: true, db.SettingHLSListSize: true,
|
||||
db.SettingLiveWait: true, db.SettingTSReadyBytes: true,
|
||||
db.SettingIdleTimeoutS: true, db.SettingDefaultOutputs: true,
|
||||
db.SettingOnDemand: true,
|
||||
}
|
||||
for k := range in {
|
||||
if !allowed[k] {
|
||||
writeErr(w, http.StatusBadRequest, "unknown setting "+k)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.Store.SetSettings(in); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, fmt.Sprintf("updated %d global setting(s)", len(in)))
|
||||
vals, _ := h.Store.GetSettings()
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"settings": vals,
|
||||
"effective": h.Store.GlobalPackagerSettings(),
|
||||
// These shape the ffmpeg command line, which is built at start
|
||||
// time, so running streams keep their current settings.
|
||||
"note": "applies to each stream the next time it starts",
|
||||
})
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- schedules ----------
|
||||
|
||||
// schedules handles /api/schedules: the cross-stream views.
|
||||
func (h *Handler) schedules(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
if truthy(r.URL.Query().Get("upcoming")) {
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
list, err := h.Store.UpcomingSchedules(limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListSchedules(0)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
// scheduleByID handles PATCH and DELETE on one schedule.
|
||||
func (h *Handler) scheduleByID(w http.ResponseWriter, r *http.Request) {
|
||||
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/schedules/"), "/")
|
||||
if rest == "" {
|
||||
h.schedules(w, r)
|
||||
return
|
||||
}
|
||||
if rest == "upcoming" && r.Method == http.MethodGet {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
list, err := h.Store.UpcomingSchedules(limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(strings.Split(rest, "/")[0], 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid schedule id")
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
sc, err := h.Store.GetSchedule(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, sc)
|
||||
case http.MethodPatch, http.MethodPut:
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
db.Schedule
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
sc, err := h.Store.PatchSchedule(id, in.Schedule, in.Enabled)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "edited schedule "+rest+" on stream "+sc.StreamName)
|
||||
writeJSON(w, http.StatusOK, sc)
|
||||
case http.MethodDelete:
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sc, _ := h.Store.GetSchedule(id)
|
||||
if err := h.Store.DeleteSchedule(id); err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "deleted schedule "+rest+" on stream "+sc.StreamName)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
// streamSchedules handles /api/streams/:id/schedules.
|
||||
func (h *Handler) streamSchedules(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListSchedules(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"schedules": list})
|
||||
case http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in db.Schedule
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
in.StreamID = id
|
||||
in.CreatedBy = p.Actor()
|
||||
sc, err := h.Store.CreateSchedule(in)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusCreated,
|
||||
fmt.Sprintf("scheduled %s for stream %s (%s)", sc.Action, sc.StreamName, scheduleLabel(sc)))
|
||||
h.Store.Eventf(id, db.EventUpdated, db.SevInfo,
|
||||
"schedule added: %s %s", sc.Action, scheduleLabel(sc))
|
||||
writeJSON(w, http.StatusCreated, sc)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func scheduleLabel(sc db.Schedule) string {
|
||||
if sc.Kind == db.KindWeekly {
|
||||
return fmt.Sprintf("%s at %s %s", db.DaysLabel(sc.DaysMask), sc.TimeOfDay, sc.TZ)
|
||||
}
|
||||
return "once at " + sc.AtUTC
|
||||
}
|
||||
|
||||
// headerMapOf parses a stream's headers_json for the probe.
|
||||
func headerMapOf(headersJSON string) map[string]string {
|
||||
out := map[string]string{}
|
||||
headersJSON = strings.TrimSpace(headersJSON)
|
||||
if headersJSON == "" || headersJSON == "{}" {
|
||||
return out
|
||||
}
|
||||
var m map[string]string
|
||||
if err := json.Unmarshal([]byte(headersJSON), &m); err != nil {
|
||||
return out
|
||||
}
|
||||
for k, v := range m {
|
||||
if k = strings.TrimSpace(k); k != "" {
|
||||
out[k] = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
383
apps/streamd/internal/api/events.go
Normal file
383
apps/streamd/internal/api/events.go
Normal file
|
|
@ -0,0 +1,383 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
)
|
||||
|
||||
// logSources maps a caller-supplied source name to the log file suffix the
|
||||
// supervisor writes. It is a fixed allowlist, and the file name is built from
|
||||
// the stream's own name, so no part of the path comes from request input.
|
||||
var logSources = map[string]string{
|
||||
"nre": "-nre.log",
|
||||
"ffmpeg.out": "-ffmpeg.out.log",
|
||||
"ffmpeg.err": "-ffmpeg.err.log",
|
||||
}
|
||||
|
||||
// postEvent records an agent-authored event. This is how a failing phone
|
||||
// capture reaches the dashboard instead of only the agent's console.
|
||||
func (h *Handler) postEvent(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Kind string `json:"kind"`
|
||||
Severity string `json:"severity"`
|
||||
Message string `json:"message"`
|
||||
Detail map[string]any `json:"detail"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
kind := strings.TrimSpace(in.Kind)
|
||||
if kind == "" {
|
||||
writeErr(w, http.StatusBadRequest, "kind required")
|
||||
return
|
||||
}
|
||||
// Agents may only author their own capture events; everything else on the
|
||||
// timeline is written by streamd itself and must stay trustworthy.
|
||||
if !agentEventKinds[kind] {
|
||||
writeErr(w, http.StatusBadRequest,
|
||||
"kind "+kind+" is not one an agent may report (allowed: capture_started, capture_ok, capture_failed)")
|
||||
return
|
||||
}
|
||||
sev := strings.TrimSpace(in.Severity)
|
||||
if sev == "" {
|
||||
sev = db.SevInfo
|
||||
if kind == db.EventCaptureFailed {
|
||||
sev = db.SevError
|
||||
}
|
||||
}
|
||||
var detail json.RawMessage
|
||||
if len(in.Detail) > 0 {
|
||||
if b, err := json.Marshal(in.Detail); err == nil && len(b) < 8192 {
|
||||
detail = b
|
||||
}
|
||||
}
|
||||
h.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id,
|
||||
Kind: kind,
|
||||
Severity: sev,
|
||||
Actor: p.Actor(),
|
||||
Message: in.Message,
|
||||
Detail: detail,
|
||||
})
|
||||
h.logger().Info("agent event", "stream", st.Name, "kind", kind, "actor", p.Actor(), "msg", in.Message)
|
||||
if h.Notifier != nil {
|
||||
h.Notifier.NotifyStreamChanged(st.Name, kind)
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
var agentEventKinds = map[string]bool{
|
||||
db.EventCaptureStarted: true,
|
||||
db.EventCaptureOK: true,
|
||||
db.EventCaptureFailed: true,
|
||||
}
|
||||
|
||||
func (h *Handler) listEvents(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
// Flush first so a caller sees the effect of what they just did.
|
||||
_ = h.Store.FlushHistory()
|
||||
q := r.URL.Query()
|
||||
limit, _ := strconv.Atoi(q.Get("limit"))
|
||||
list, err := h.Store.ListEvents(id, limit, q.Get("kind"), q.Get("since"))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"events": list})
|
||||
}
|
||||
|
||||
func (h *Handler) listMetrics(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
_ = h.Store.FlushHistory()
|
||||
window := parseWindow(r.URL.Query().Get("window"))
|
||||
points, err := h.Store.ListMetrics(id, window)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
uptime, _ := h.Store.UptimeRatio(id, window)
|
||||
out := map[string]any{"metrics": points, "window_s": int(window.Seconds())}
|
||||
if uptime >= 0 {
|
||||
out["uptime_ratio"] = uptime
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func parseWindow(s string) time.Duration {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case "", "1h":
|
||||
return time.Hour
|
||||
case "15m":
|
||||
return 15 * time.Minute
|
||||
case "6h":
|
||||
return 6 * time.Hour
|
||||
case "24h", "1d":
|
||||
return 24 * time.Hour
|
||||
case "7d":
|
||||
return 7 * 24 * time.Hour
|
||||
}
|
||||
if d, err := time.ParseDuration(s); err == nil && d > 0 && d <= 7*24*time.Hour {
|
||||
return d
|
||||
}
|
||||
return time.Hour
|
||||
}
|
||||
|
||||
// logPath resolves a stream + source + optional variant to a log file path.
|
||||
// Returns "" when the source is not on the allowlist.
|
||||
func (h *Handler) logPath(st db.Stream, source, variant string) string {
|
||||
suffix, ok := logSources[strings.ToLower(strings.TrimSpace(source))]
|
||||
if !ok || strings.TrimSpace(h.LogRoot) == "" {
|
||||
return ""
|
||||
}
|
||||
base := st.Name
|
||||
// A variant's packager writes to "<name>-<variant>-ffmpeg.*.log". The
|
||||
// variant id is validated against the stream's own ladder rather than
|
||||
// trusted, so it cannot contribute path characters.
|
||||
if v := strings.TrimSpace(variant); v != "" && v != db.SourceVariantID {
|
||||
known := false
|
||||
for _, spec := range db.ParseVariantsJSON(st.VariantsJSON) {
|
||||
if spec.ID == v {
|
||||
known = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
return ""
|
||||
}
|
||||
base = st.Name + "-" + v
|
||||
}
|
||||
return filepath.Join(h.LogRoot, base+suffix)
|
||||
}
|
||||
|
||||
func (h *Handler) streamLogs(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
source := q.Get("source")
|
||||
if source == "" {
|
||||
source = "nre"
|
||||
}
|
||||
path := h.logPath(st, source, q.Get("variant"))
|
||||
if path == "" {
|
||||
writeErr(w, http.StatusBadRequest, "unknown log source — use one of nre, ffmpeg.out, ffmpeg.err")
|
||||
return
|
||||
}
|
||||
tail, _ := strconv.Atoi(q.Get("tail"))
|
||||
if tail <= 0 {
|
||||
tail = 500
|
||||
}
|
||||
if tail > 5000 {
|
||||
tail = 5000
|
||||
}
|
||||
body, err := logfile.Tail(path, tail)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"source": source, "lines": "", "exists": false,
|
||||
"note": "no log yet — this stream has not run since streamd started",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"source": source,
|
||||
"exists": true,
|
||||
"lines": string(body),
|
||||
})
|
||||
}
|
||||
|
||||
// streamLogsSSE follows a log file and pushes new bytes as they appear, so the
|
||||
// dashboard can show a live tail.
|
||||
func (h *Handler) streamLogsSSE(w http.ResponseWriter, r *http.Request, id int64) {
|
||||
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.GetStream(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
source := q.Get("source")
|
||||
if source == "" {
|
||||
source = "nre"
|
||||
}
|
||||
path := h.logPath(st, source, q.Get("variant"))
|
||||
if path == "" {
|
||||
writeErr(w, http.StatusBadRequest, "unknown log source")
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusInternalServerError, "streaming unsupported")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
// Defeat proxy buffering, which would otherwise hold the whole stream.
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
send := func(event, data string) bool {
|
||||
for _, line := range strings.Split(strings.TrimRight(data, "\n"), "\n") {
|
||||
if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, line); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
flusher.Flush()
|
||||
return true
|
||||
}
|
||||
|
||||
// Start from the tail so the viewer has context, then follow.
|
||||
if initial, err := logfile.Tail(path, 200); err == nil && len(initial) > 0 {
|
||||
if !send("log", string(initial)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
var offset int64
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
offset = fi.Size()
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
keepalive := time.NewTicker(20 * time.Second)
|
||||
defer keepalive.Stop()
|
||||
ctx := r.Context()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-keepalive.C:
|
||||
if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
flusher.Flush()
|
||||
case <-ticker.C:
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
size := fi.Size()
|
||||
if size < offset {
|
||||
// The file rotated under us; start again from its beginning.
|
||||
offset = 0
|
||||
if !send("note", "-- log rotated --") {
|
||||
return
|
||||
}
|
||||
}
|
||||
if size == offset {
|
||||
continue
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
buf := make([]byte, size-offset)
|
||||
n, err := f.ReadAt(buf, offset)
|
||||
_ = f.Close()
|
||||
if n > 0 {
|
||||
if !send("log", string(buf[:n])) {
|
||||
return
|
||||
}
|
||||
offset += int64(n)
|
||||
}
|
||||
if err != nil && n == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// overview is the dashboard's single round trip: totals, viewer counts and
|
||||
// the recent activity feed.
|
||||
func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListStreams()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
var running, down, starting, stopped, onDemandIdle, viewers, needCapture int
|
||||
for i := range list {
|
||||
st := &list[i]
|
||||
if h.Viewers != nil {
|
||||
st.Viewers = h.Viewers.ViewersFor(st.Name)
|
||||
viewers += st.Viewers
|
||||
}
|
||||
if st.NeedsCapture {
|
||||
needCapture++
|
||||
}
|
||||
switch st.Health {
|
||||
case "ok":
|
||||
running++
|
||||
case "down":
|
||||
down++
|
||||
case "starting":
|
||||
starting++
|
||||
default:
|
||||
stopped++
|
||||
if st.OnDemand && st.Enabled {
|
||||
onDemandIdle++
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = h.Store.FlushHistory()
|
||||
recent, _ := h.Store.RecentEvents(25)
|
||||
out := map[string]any{
|
||||
"totals": map[string]any{
|
||||
"streams": len(list),
|
||||
"running": running,
|
||||
"starting": starting,
|
||||
"down": down,
|
||||
"stopped": stopped,
|
||||
"ondemand_idle": onDemandIdle,
|
||||
"viewers": viewers,
|
||||
"needs_capture": needCapture,
|
||||
},
|
||||
"recent_events": recent,
|
||||
}
|
||||
if h.Scheduler != nil {
|
||||
out["upcoming"] = h.Scheduler.Upcoming(10)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import (
|
|||
"regexp"
|
||||
"strings"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
|
@ -29,6 +30,12 @@ func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
|
|||
path := strings.TrimPrefix(r.URL.Path, "/api/modules")
|
||||
path = strings.Trim(path, "/")
|
||||
|
||||
// Module metadata describes the provider plugins installed on this host,
|
||||
// so even reading it needs a principal.
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case path == "" && r.Method == http.MethodGet:
|
||||
h.listModules(w, r)
|
||||
|
|
@ -74,7 +81,10 @@ func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string)
|
|||
}
|
||||
|
||||
func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
|
||||
if !h.auth(w, r) {
|
||||
// Writing a module.yaml changes how streams are captured on this host:
|
||||
// operator, and recorded.
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !moduleNameRe.MatchString(name) {
|
||||
|
|
@ -117,6 +127,8 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string)
|
|||
}
|
||||
|
||||
info := moduleYAMLInfo(modDir, name)
|
||||
h.audit(r, p, http.StatusOK, "uploaded module.yaml for "+name)
|
||||
h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"module": info,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,10 @@ import (
|
|||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// stalePlaylistS is how old a playlist may get before the output counts as
|
||||
// down. It matches the supervisor's own staleness threshold.
|
||||
const stalePlaylistS = 45
|
||||
|
||||
// enrichVariantHealth updates each variant's health from on-disk HLS playlists.
|
||||
func (h *Handler) enrichVariantHealth(st *db.Stream) {
|
||||
if st == nil {
|
||||
|
|
@ -27,28 +31,90 @@ func (h *Handler) enrichVariantHealth(st *db.Stream) {
|
|||
v.Health = "off"
|
||||
continue
|
||||
}
|
||||
if v.Height <= 0 {
|
||||
if v.IsSource() {
|
||||
v.Health = st.Health
|
||||
v.PlaylistAgeS = st.PlaylistAgeS
|
||||
continue
|
||||
}
|
||||
dirName := st.Name + "-" + v.ID
|
||||
index := filepath.Join(www, dirName, "index.m3u8")
|
||||
fi, err := os.Stat(index)
|
||||
if err != nil {
|
||||
if st.Health == "ok" || st.Health == "starting" {
|
||||
v.Health = "starting"
|
||||
dirName := db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly)
|
||||
health, age := h.playlistHealth(filepath.Join(www, dirName, "index.m3u8"), st.Health)
|
||||
v.Health = health
|
||||
v.PlaylistAgeS = age
|
||||
}
|
||||
}
|
||||
|
||||
// enrichLinks resolves every variant x output endpoint and stats each one, so
|
||||
// the dashboard can show that (say) HLS is fine while DASH has died.
|
||||
func (h *Handler) enrichLinks(st *db.Stream) {
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
links := db.BuildPublishLinks(st.Name, st.VariantsJSON, st.OutputsJSON)
|
||||
www := strings.TrimSpace(h.WWWRoot)
|
||||
// Variant health computed above, to fall back on for outputs with no file
|
||||
// of their own (progressive TS is a live pipe, not a playlist).
|
||||
variantHealth := map[string]string{}
|
||||
for _, v := range st.Variants {
|
||||
variantHealth[v.ID] = v.Health
|
||||
}
|
||||
for i := range links {
|
||||
l := &links[i]
|
||||
if www == "" {
|
||||
continue
|
||||
}
|
||||
if l.Format == db.FormatTS {
|
||||
// No file to stat: the pipe is live exactly when its variant is.
|
||||
if hv, ok := variantHealth[l.VariantID]; ok {
|
||||
l.Health = hv
|
||||
} else {
|
||||
v.Health = st.Health
|
||||
l.Health = st.Health
|
||||
}
|
||||
continue
|
||||
}
|
||||
age := time.Since(fi.ModTime()).Seconds()
|
||||
v.PlaylistAgeS = age
|
||||
if age > 45 {
|
||||
v.Health = "down"
|
||||
} else {
|
||||
v.Health = "ok"
|
||||
rel := relFromPlayPath(l.PlayPath)
|
||||
if rel == "" {
|
||||
continue
|
||||
}
|
||||
l.Health, l.PlaylistAgeS = h.playlistHealth(filepath.Join(www, rel), st.Health)
|
||||
}
|
||||
st.Links = links
|
||||
}
|
||||
|
||||
// playlistHealth reports a playlist's health from its mtime. A missing file
|
||||
// while the stream is coming up is "starting", not "down".
|
||||
func (h *Handler) playlistHealth(path, streamHealth string) (string, float64) {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
if streamHealth == "ok" || streamHealth == "starting" {
|
||||
return "starting", 0
|
||||
}
|
||||
return streamHealth, 0
|
||||
}
|
||||
age := time.Since(fi.ModTime()).Seconds()
|
||||
if age > stalePlaylistS {
|
||||
return "down", age
|
||||
}
|
||||
return "ok", age
|
||||
}
|
||||
|
||||
// relFromPlayPath turns a /hls/... URL path back into a path relative to the
|
||||
// www root. It returns "" for anything that escapes that root.
|
||||
func relFromPlayPath(p string) string {
|
||||
const prefix = "/hls/"
|
||||
if !strings.HasPrefix(p, prefix) {
|
||||
return ""
|
||||
}
|
||||
rel := strings.TrimPrefix(p, prefix)
|
||||
// These paths are built by us, but treat them as untrusted anyway: a
|
||||
// stream name is user input and must never climb out of www.
|
||||
clean := filepath.Clean(filepath.FromSlash(rel))
|
||||
if clean == "." || strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
|
||||
return ""
|
||||
}
|
||||
for _, seg := range strings.Split(filepath.ToSlash(clean), "/") {
|
||||
if seg == ".." {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
|
|
|||
174
apps/streamd/internal/auth/auth.go
Normal file
174
apps/streamd/internal/auth/auth.go
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
// Package auth provides accounts, sessions, API keys and role-based access
|
||||
// control for streamd. Password hashing uses crypto/pbkdf2 from the standard
|
||||
// library, so no third-party crypto dependency is needed.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Role is an access level. Roles are ordered: viewer < operator < admin.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleViewer Role = "viewer"
|
||||
RoleOperator Role = "operator"
|
||||
RoleAdmin Role = "admin"
|
||||
)
|
||||
|
||||
var roleRank = map[Role]int{
|
||||
RoleViewer: 1,
|
||||
RoleOperator: 2,
|
||||
RoleAdmin: 3,
|
||||
}
|
||||
|
||||
// ParseRole validates a role name, defaulting to viewer for anything unknown.
|
||||
func ParseRole(s string) (Role, error) {
|
||||
r := Role(strings.ToLower(strings.TrimSpace(s)))
|
||||
if _, ok := roleRank[r]; !ok {
|
||||
return RoleViewer, fmt.Errorf("unknown role %q (want viewer, operator or admin)", s)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// AtLeast reports whether r grants everything min does.
|
||||
func (r Role) AtLeast(min Role) bool {
|
||||
return roleRank[r] >= roleRank[min]
|
||||
}
|
||||
|
||||
func (r Role) Valid() bool {
|
||||
_, ok := roleRank[r]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ActorKind distinguishes a logged-in human from a machine credential.
|
||||
type ActorKind string
|
||||
|
||||
const (
|
||||
ActorUser ActorKind = "user"
|
||||
ActorAPIKey ActorKind = "apikey"
|
||||
ActorSystem ActorKind = "system"
|
||||
)
|
||||
|
||||
// Principal is the authenticated identity behind a request.
|
||||
type Principal struct {
|
||||
Kind ActorKind
|
||||
Role Role
|
||||
// Name is the username or the API key's label, used for audit rows.
|
||||
Name string
|
||||
// UserID is set for session principals only.
|
||||
UserID int64
|
||||
// AgentID is the X-Agent-ID a machine caller volunteered, if any.
|
||||
AgentID string
|
||||
// SessionID is the raw session id for session principals (needed to
|
||||
// resolve the CSRF token); empty for bearer principals.
|
||||
SessionID string
|
||||
// CSRFToken is the token a cookie-authenticated caller must echo back.
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
// Actor is the audit-log label for this principal.
|
||||
func (p *Principal) Actor() string {
|
||||
if p == nil {
|
||||
return "anonymous"
|
||||
}
|
||||
if p.AgentID != "" && p.Kind == ActorAPIKey {
|
||||
return p.Name + "@" + p.AgentID
|
||||
}
|
||||
return p.Name
|
||||
}
|
||||
|
||||
// NeedsCSRF is true for ambient (cookie) credentials only. A bearer token is
|
||||
// never sent automatically by a browser, so it carries no CSRF risk.
|
||||
func (p *Principal) NeedsCSRF() bool {
|
||||
return p != nil && p.Kind == ActorUser && p.SessionID != ""
|
||||
}
|
||||
|
||||
const (
|
||||
pbkdf2Iterations = 600_000
|
||||
pbkdf2KeyLen = 32
|
||||
saltLen = 16
|
||||
tokenLen = 32
|
||||
)
|
||||
|
||||
// HashPassword returns an encoded PBKDF2-HMAC-SHA256 hash:
|
||||
//
|
||||
// pbkdf2-sha256$<iterations>$<base64 salt>$<base64 derived key>
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < 8 {
|
||||
return "", fmt.Errorf("password must be at least 8 characters")
|
||||
}
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hashWithSalt(password, salt, pbkdf2Iterations)
|
||||
}
|
||||
|
||||
func hashWithSalt(password string, salt []byte, iters int) (string, error) {
|
||||
dk, err := pbkdf2.Key(sha256.New, password, salt, iters, pbkdf2KeyLen)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s",
|
||||
iters,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(dk),
|
||||
), nil
|
||||
}
|
||||
|
||||
// VerifyPassword checks a password against an encoded hash in constant time.
|
||||
// A malformed or empty hash always fails, and never panics.
|
||||
func VerifyPassword(encoded, password string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
|
||||
return false
|
||||
}
|
||||
iters, err := strconv.Atoi(parts[1])
|
||||
if err != nil || iters <= 0 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[3])
|
||||
if err != nil || len(want) == 0 {
|
||||
return false
|
||||
}
|
||||
got, err := pbkdf2.Key(sha256.New, password, salt, iters, len(want))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
|
||||
// NewToken returns a URL-safe random secret and its storage hash. Only the
|
||||
// hash is ever persisted, so a database leak does not yield usable credentials.
|
||||
func NewToken() (secret, hash string, err error) {
|
||||
b := make([]byte, tokenLen)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
secret = base64.RawURLEncoding.EncodeToString(b)
|
||||
return secret, HashToken(secret), nil
|
||||
}
|
||||
|
||||
// HashToken is the storage form of a session id or API key.
|
||||
func HashToken(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// SecretEqual compares two secrets in constant time.
|
||||
func SecretEqual(a, b string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
|
||||
}
|
||||
548
apps/streamd/internal/auth/auth_test.go
Normal file
548
apps/streamd/internal/auth/auth_test.go
Normal file
|
|
@ -0,0 +1,548 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestHashPasswordRoundTrip(t *testing.T) {
|
||||
h, err := HashPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatalf("hash: %v", err)
|
||||
}
|
||||
if !VerifyPassword(h, "correct horse battery") {
|
||||
t.Error("correct password rejected")
|
||||
}
|
||||
if VerifyPassword(h, "correct horse batterz") {
|
||||
t.Error("wrong password accepted")
|
||||
}
|
||||
if VerifyPassword(h, "") {
|
||||
t.Error("empty password accepted")
|
||||
}
|
||||
// Two hashes of the same password must differ (unique salt).
|
||||
h2, _ := HashPassword("correct horse battery")
|
||||
if h == h2 {
|
||||
t.Error("salt is not random: identical hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordRejectsShort(t *testing.T) {
|
||||
if _, err := HashPassword("short"); err == nil {
|
||||
t.Error("expected short password to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordMalformed(t *testing.T) {
|
||||
for _, bad := range []string{
|
||||
"", "nonsense", "pbkdf2-sha256$", "pbkdf2-sha256$a$b$c",
|
||||
"pbkdf2-sha256$0$c2FsdA$aGFzaA", "bcrypt$1$x$y",
|
||||
"pbkdf2-sha256$1000$!!!$aGFzaA", "pbkdf2-sha256$1000$c2FsdA$",
|
||||
} {
|
||||
if VerifyPassword(bad, "anything") {
|
||||
t.Errorf("malformed hash %q was accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleOrdering(t *testing.T) {
|
||||
if !RoleAdmin.AtLeast(RoleOperator) || !RoleAdmin.AtLeast(RoleViewer) {
|
||||
t.Error("admin should outrank operator and viewer")
|
||||
}
|
||||
if RoleViewer.AtLeast(RoleOperator) {
|
||||
t.Error("viewer must not satisfy operator")
|
||||
}
|
||||
if RoleOperator.AtLeast(RoleAdmin) {
|
||||
t.Error("operator must not satisfy admin")
|
||||
}
|
||||
if !RoleViewer.AtLeast(RoleViewer) {
|
||||
t.Error("a role should satisfy itself")
|
||||
}
|
||||
if _, err := ParseRole("root"); err == nil {
|
||||
t.Error("unknown role should error")
|
||||
}
|
||||
if r, err := ParseRole(" ADMIN "); err != nil || r != RoleAdmin {
|
||||
t.Errorf("ParseRole should normalise case and space, got %q %v", r, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenHashing(t *testing.T) {
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if secret == "" || hash == "" || secret == hash {
|
||||
t.Fatalf("bad token/hash pair: %q %q", secret, hash)
|
||||
}
|
||||
if HashToken(secret) != hash {
|
||||
t.Error("HashToken disagrees with NewToken")
|
||||
}
|
||||
s2, _, _ := NewToken()
|
||||
if s2 == secret {
|
||||
t.Error("tokens are not random")
|
||||
}
|
||||
}
|
||||
|
||||
func newTestStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
// A private temp file rather than :memory:, because the real store runs
|
||||
// with one connection against a file and we want the same semantics.
|
||||
dsn := "file:" + t.TempDir() + "/auth_test.db?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)"
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
s, err := New(db, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestUserLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
|
||||
if n, err := s.CountUsers(); err != nil || n != 0 {
|
||||
t.Fatalf("fresh store should have no users, got %d %v", n, err)
|
||||
}
|
||||
u, err := s.CreateUser(" Alice ", "hunter2hunter2", RoleAdmin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.Username != "alice" {
|
||||
t.Errorf("username should be normalised, got %q", u.Username)
|
||||
}
|
||||
if _, err := s.CreateUser("alice", "otherpassword", RoleViewer); err == nil {
|
||||
t.Error("duplicate username should be rejected")
|
||||
}
|
||||
|
||||
if _, err := s.Authenticate("ALICE", "hunter2hunter2"); err != nil {
|
||||
t.Errorf("login should succeed case-insensitively: %v", err)
|
||||
}
|
||||
if _, err := s.Authenticate("alice", "wrong"); err == nil {
|
||||
t.Error("wrong password should fail")
|
||||
}
|
||||
if _, err := s.Authenticate("nobody", "whatever"); err == nil {
|
||||
t.Error("unknown user should fail")
|
||||
}
|
||||
|
||||
// Disabling blocks login.
|
||||
dis := true
|
||||
if _, err := s.UpdateUser(u.ID, nil, &dis); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Authenticate("alice", "hunter2hunter2"); err == nil {
|
||||
t.Error("disabled account should not authenticate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
u, err := s.CreateUser("bob", "password1234", RoleOperator)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
secret, csrf, err := s.CreateSession(u.ID, time.Hour, "10.0.0.1", "test-agent")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := s.LookupSession(secret, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if p.Name != "bob" || p.Role != RoleOperator || p.Kind != ActorUser {
|
||||
t.Errorf("unexpected principal %+v", p)
|
||||
}
|
||||
if p.CSRFToken != csrf {
|
||||
t.Error("CSRF token mismatch")
|
||||
}
|
||||
if !p.NeedsCSRF() {
|
||||
t.Error("session principal must require CSRF")
|
||||
}
|
||||
|
||||
// The raw secret must not be stored.
|
||||
var count int
|
||||
if err := s.DB.QueryRow(`SELECT COUNT(*) FROM sessions WHERE id_hash = ?`, secret).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Error("raw session secret found in the database")
|
||||
}
|
||||
|
||||
if _, err := s.LookupSession("not-a-session", time.Hour); err == nil {
|
||||
t.Error("bogus session should not resolve")
|
||||
}
|
||||
|
||||
// Changing the password must revoke sessions.
|
||||
if err := s.SetPassword(u.ID, "newpassword12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupSession(secret, time.Hour); err == nil {
|
||||
t.Error("session should be revoked after a password change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
u, _ := s.CreateUser("carol", "password1234", RoleViewer)
|
||||
secret, _, err := s.CreateSession(u.ID, -time.Hour, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// CreateSession clamps a non-positive TTL to the default, so force the row
|
||||
// into the past to exercise the expiry branch.
|
||||
if _, err := s.DB.Exec(`UPDATE sessions SET expires_at = ?`,
|
||||
time.Now().UTC().Add(-time.Minute).Format(time.RFC3339)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupSession(secret, time.Hour); err == nil {
|
||||
t.Error("expired session should not resolve")
|
||||
}
|
||||
if n, err := s.ExpireSessions(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if n < 0 {
|
||||
t.Error("unexpected negative expiry count")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIKeyLifecycle(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
k, err := s.CreateAPIKey("phone-agent", RoleOperator)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k.Secret == "" {
|
||||
t.Fatal("create must return the secret once")
|
||||
}
|
||||
p, err := s.LookupAPIKey(k.Secret)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if p.Role != RoleOperator || p.Kind != ActorAPIKey || p.Name != "phone-agent" {
|
||||
t.Errorf("unexpected principal %+v", p)
|
||||
}
|
||||
if p.NeedsCSRF() {
|
||||
t.Error("bearer principals must be exempt from CSRF")
|
||||
}
|
||||
|
||||
// Listing never exposes the secret.
|
||||
list, err := s.ListAPIKeys()
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("list: %v %d", err, len(list))
|
||||
}
|
||||
if list[0].Secret != "" {
|
||||
t.Error("list must not expose key secrets")
|
||||
}
|
||||
|
||||
if err := s.RevokeAPIKey(k.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.LookupAPIKey(k.Secret); err == nil {
|
||||
t.Error("revoked key should not authenticate")
|
||||
}
|
||||
if err := s.RevokeAPIKey(k.ID); err == nil {
|
||||
t.Error("revoking twice should report not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyTokenActsAsAdminKey(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
s.LegacyToken = "SECRET-FROM-ENV"
|
||||
p, err := s.LookupAPIKey("SECRET-FROM-ENV")
|
||||
if err != nil {
|
||||
t.Fatalf("legacy token should resolve: %v", err)
|
||||
}
|
||||
if p.Role != RoleAdmin {
|
||||
t.Errorf("legacy token should be admin, got %q", p.Role)
|
||||
}
|
||||
if _, err := s.LookupAPIKey("SECRET-FROM-EN"); err == nil {
|
||||
t.Error("near-miss token should not resolve")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditBufferFlush(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
for i := 0; i < 5; i++ {
|
||||
s.Audit(AuditEntry{Actor: "alice", ActorKind: ActorUser, Method: "POST",
|
||||
Path: "/api/streams", Status: 200, Note: "created"})
|
||||
}
|
||||
// Nothing is written until a flush, by design — the DB has a single
|
||||
// connection and must not be hit per request.
|
||||
var n int
|
||||
_ = s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Errorf("audit rows written before flush: %d", n)
|
||||
}
|
||||
if err := s.FlushAudit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 5 {
|
||||
t.Errorf("want 5 audit rows after flush, got %d", n)
|
||||
}
|
||||
list, err := s.ListAudit(10, "")
|
||||
if err != nil || len(list) != 5 {
|
||||
t.Fatalf("list audit: %v %d", err, len(list))
|
||||
}
|
||||
if list[0].Actor != "alice" {
|
||||
t.Errorf("unexpected actor %q", list[0].Actor)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- middleware ----------
|
||||
|
||||
func testMW(t *testing.T) (*Middleware, *Store) {
|
||||
t.Helper()
|
||||
s := newTestStore(t)
|
||||
mw := NewMiddleware(s, httpx.Trust{}, false)
|
||||
return mw, s
|
||||
}
|
||||
|
||||
// probe is a handler that reports the principal the middleware attached.
|
||||
func probe(w http.ResponseWriter, r *http.Request) {
|
||||
p := From(r)
|
||||
if p == nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("anonymous"))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(p.Name + ":" + string(p.Role)))
|
||||
}
|
||||
|
||||
func TestAttachResolvesBearer(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "agent:operator" {
|
||||
t.Errorf("want agent:operator, got %q", got)
|
||||
}
|
||||
|
||||
// X-Streamd-Token is still honoured.
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("X-Streamd-Token", k.Secret)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "agent:operator" {
|
||||
t.Errorf("X-Streamd-Token: want agent:operator, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The ?token= query parameter used to authenticate. It must not any more: it
|
||||
// leaked the shared secret into proxy access logs and Referer headers.
|
||||
func TestQueryTokenIsRejected(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams?token="+k.Secret, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if got := rec.Body.String(); got != "anonymous" {
|
||||
t.Errorf("?token= must not authenticate, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFRequiredForCookieMutation(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
u, _ := s.CreateUser("dave", "password1234", RoleOperator)
|
||||
secret, csrf, err := s.CreateSession(u.ID, time.Hour, "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
|
||||
// GET needs no CSRF.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("GET with cookie should pass, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST without the header is refused.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("POST without CSRF should be 403, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST with a wrong header is refused.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
req.Header.Set(CSRFHeader, "wrong")
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("POST with bad CSRF should be 403, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// POST with the right header passes.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/streams", nil)
|
||||
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: secret})
|
||||
req.Header.Set(CSRFHeader, csrf)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("POST with valid CSRF should pass, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFNotRequiredForBearerMutation(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("agent", RoleOperator)
|
||||
h := mw.Attach(http.HandlerFunc(probe))
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/streams/1/credentials", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("bearer POST should not need CSRF, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuardRoles(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
k, _ := s.CreateAPIKey("viewer-key", RoleViewer)
|
||||
|
||||
guarded := mw.Attach(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := Guard(w, r, RoleOperator); !ok {
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("allowed"))
|
||||
}))
|
||||
|
||||
// Anonymous → 401.
|
||||
rec := httptest.NewRecorder()
|
||||
guarded.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/streams", nil))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous should be 401, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// Under-privileged → 403.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/streams", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+k.Secret)
|
||||
rec = httptest.NewRecorder()
|
||||
guarded.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("viewer should be 403 for operator route, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleLocksOut(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
if _, err := s.CreateUser("erin", "password1234", RoleAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := NewHandler(s, mw, nil)
|
||||
mux := http.NewServeMux()
|
||||
h.Mount(mux)
|
||||
srv := mw.Attach(mux)
|
||||
|
||||
post := func(body string) int {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.RemoteAddr = "203.0.113.9:1234"
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
sawLockout := false
|
||||
for i := 0; i < 12; i++ {
|
||||
if post(`{"username":"erin","password":"wrong"}`) == http.StatusTooManyRequests {
|
||||
sawLockout = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !sawLockout {
|
||||
t.Error("repeated bad logins should eventually be throttled")
|
||||
}
|
||||
// And the lockout applies to the correct password too, so guessing cannot
|
||||
// be continued by getting lucky.
|
||||
if code := post(`{"username":"erin","password":"password1234"}`); code != http.StatusTooManyRequests {
|
||||
t.Errorf("throttle should also hold off a correct password, got %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSucceedsAndSetsCookies(t *testing.T) {
|
||||
mw, s := testMW(t)
|
||||
if _, err := s.CreateUser("frank", "password1234", RoleAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := NewHandler(s, mw, nil)
|
||||
mux := http.NewServeMux()
|
||||
h.Mount(mux)
|
||||
srv := mw.Attach(mux)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/login", strings.NewReader(`{"username":"frank","password":"password1234"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var sessionCookie, csrfCookie *http.Cookie
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
switch c.Name {
|
||||
case SessionCookie:
|
||||
sessionCookie = c
|
||||
case CSRFCookie:
|
||||
csrfCookie = c
|
||||
}
|
||||
}
|
||||
if sessionCookie == nil || csrfCookie == nil {
|
||||
t.Fatal("login must set both cookies")
|
||||
}
|
||||
if !sessionCookie.HttpOnly {
|
||||
t.Error("session cookie must be HttpOnly")
|
||||
}
|
||||
if csrfCookie.HttpOnly {
|
||||
t.Error("CSRF cookie must be readable by the page script")
|
||||
}
|
||||
if sessionCookie.SameSite != http.SameSiteLaxMode {
|
||||
t.Error("session cookie should be SameSite=Lax")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiterRefills(t *testing.T) {
|
||||
l := NewLimiter(2, 100) // 2 burst, refills fast
|
||||
if !l.Allow("k") || !l.Allow("k") {
|
||||
t.Fatal("burst should allow two")
|
||||
}
|
||||
if l.Allow("k") {
|
||||
t.Error("third call should be denied immediately")
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if !l.Allow("k") {
|
||||
t.Error("bucket should refill")
|
||||
}
|
||||
// Distinct keys are independent.
|
||||
if !l.Allow("other") {
|
||||
t.Error("a different key should have its own bucket")
|
||||
}
|
||||
// Empty key is never limited (used for "no IP known").
|
||||
for i := 0; i < 10; i++ {
|
||||
if !l.Allow("") {
|
||||
t.Fatal("empty key should not be limited")
|
||||
}
|
||||
}
|
||||
}
|
||||
586
apps/streamd/internal/auth/handlers.go
Normal file
586
apps/streamd/internal/auth/handlers.go
Normal file
|
|
@ -0,0 +1,586 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
// Handler serves the auth routes: login/logout/me, user administration, API
|
||||
// keys and the audit log.
|
||||
type Handler struct {
|
||||
Store *Store
|
||||
MW *Middleware
|
||||
Log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
// setupToken gates creation of the very first admin account. It is
|
||||
// generated at startup when the users table is empty and cleared the
|
||||
// moment an account exists.
|
||||
setupToken string
|
||||
}
|
||||
|
||||
func NewHandler(store *Store, mw *Middleware, lg *slog.Logger) *Handler {
|
||||
if lg == nil {
|
||||
lg = slog.Default()
|
||||
}
|
||||
return &Handler{Store: store, MW: mw, Log: lg}
|
||||
}
|
||||
|
||||
// SetSetupToken installs the first-run token. Pass "" to disable setup.
|
||||
func (h *Handler) SetSetupToken(tok string) {
|
||||
h.mu.Lock()
|
||||
h.setupToken = tok
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *Handler) currentSetupToken() string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.setupToken
|
||||
}
|
||||
|
||||
// NeedsSetup reports whether no account exists yet.
|
||||
func (h *Handler) NeedsSetup() bool {
|
||||
n, err := h.Store.CountUsers()
|
||||
return err == nil && n == 0
|
||||
}
|
||||
|
||||
func (h *Handler) Mount(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/login", h.login)
|
||||
mux.HandleFunc("/api/logout", h.logout)
|
||||
mux.HandleFunc("/api/me", h.me)
|
||||
mux.HandleFunc("/api/setup", h.setup)
|
||||
mux.HandleFunc("/api/users", h.users)
|
||||
mux.HandleFunc("/api/users/", h.userByID)
|
||||
mux.HandleFunc("/api/apikeys", h.apiKeys)
|
||||
mux.HandleFunc("/api/apikeys/", h.apiKeyByID)
|
||||
mux.HandleFunc("/api/audit", h.audit)
|
||||
}
|
||||
|
||||
// ---------- session routes ----------
|
||||
|
||||
func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
ip := h.MW.Trust.ClientIP(r)
|
||||
user := normalizeUsername(in.Username)
|
||||
// Two buckets: one per source address, one per account, so neither a
|
||||
// single host nor a single account can be hammered.
|
||||
keys := []string{"ip:" + ip, "user:" + user}
|
||||
for _, k := range keys {
|
||||
if !h.MW.LoginLimiter.Allow(k) {
|
||||
retry := h.MW.LoginLimiter.RetryAfter(k)
|
||||
w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
|
||||
h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
|
||||
Method: r.Method, Path: r.URL.Path, Status: http.StatusTooManyRequests,
|
||||
Note: "login throttled"})
|
||||
writeErr(w, http.StatusTooManyRequests, "too many login attempts — wait and try again")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
u, err := h.Store.Authenticate(in.Username, in.Password)
|
||||
if err != nil {
|
||||
// Burn extra budget on a failure so guessing is expensive.
|
||||
for _, k := range keys {
|
||||
h.MW.LoginLimiter.Penalise(k, 2)
|
||||
}
|
||||
h.Store.Audit(AuditEntry{Actor: user, ActorKind: ActorUser, IP: ip,
|
||||
Method: r.Method, Path: r.URL.Path, Status: http.StatusUnauthorized,
|
||||
Note: "login failed"})
|
||||
h.Log.Info("login failed", "user", user, "ip", ip)
|
||||
writeErr(w, http.StatusUnauthorized, "invalid username or password")
|
||||
return
|
||||
}
|
||||
|
||||
secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
for _, k := range keys {
|
||||
h.MW.LoginLimiter.Reset(k)
|
||||
}
|
||||
h.MW.SetSessionCookies(w, r, secret, csrf)
|
||||
h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
|
||||
Method: r.Method, Path: r.URL.Path, Status: http.StatusOK, Note: "login ok"})
|
||||
h.Log.Info("login", "user", u.Username, "role", string(u.Role), "ip", ip)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": u, "csrf_token": csrf})
|
||||
}
|
||||
|
||||
func (h *Handler) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if secret := SessionSecret(r); secret != "" {
|
||||
_ = h.Store.DeleteSession(secret)
|
||||
}
|
||||
h.MW.ClearSessionCookies(w, r)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// me is the agent's and the dashboard's credential preflight: it says who you
|
||||
// are, or 401s clearly if your credential is bad or revoked.
|
||||
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
p := From(r)
|
||||
if p == nil {
|
||||
resp := map[string]any{"error": "authentication required"}
|
||||
if h.NeedsSetup() {
|
||||
resp["needs_setup"] = true
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
return
|
||||
}
|
||||
out := map[string]any{
|
||||
"name": p.Name,
|
||||
"role": string(p.Role),
|
||||
"actor_kind": string(p.Kind),
|
||||
}
|
||||
if p.Kind == ActorUser {
|
||||
out["user_id"] = p.UserID
|
||||
out["csrf_token"] = p.CSRFToken
|
||||
}
|
||||
if p.AgentID != "" {
|
||||
out["agent_id"] = p.AgentID
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// setup creates the first admin account, gated by the one-time token printed
|
||||
// to the server log at startup.
|
||||
func (h *Handler) setup(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
writeJSON(w, http.StatusOK, map[string]any{"needs_setup": h.NeedsSetup()})
|
||||
case http.MethodPost:
|
||||
if !h.NeedsSetup() {
|
||||
writeErr(w, http.StatusConflict, "setup already complete")
|
||||
return
|
||||
}
|
||||
tok := h.currentSetupToken()
|
||||
if tok == "" {
|
||||
writeErr(w, http.StatusForbidden, "setup is disabled on this server")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
SetupToken string `json:"setup_token"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
ip := h.MW.Trust.ClientIP(r)
|
||||
if !h.MW.LoginLimiter.Allow("setup:" + ip) {
|
||||
writeErr(w, http.StatusTooManyRequests, "too many attempts")
|
||||
return
|
||||
}
|
||||
if !SecretEqual(strings.TrimSpace(in.SetupToken), tok) {
|
||||
h.MW.LoginLimiter.Penalise("setup:"+ip, 3)
|
||||
writeErr(w, http.StatusForbidden, "invalid setup token — see the streamd startup log")
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(in.Username, in.Password, RoleAdmin)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.SetSetupToken("")
|
||||
secret, csrf, err := h.Store.CreateSession(u.ID, h.MW.SessionTTL, ip, r.UserAgent())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
h.MW.SetSessionCookies(w, r, secret, csrf)
|
||||
h.Store.Audit(AuditEntry{Actor: u.Username, ActorKind: ActorUser, IP: ip,
|
||||
Method: r.Method, Path: r.URL.Path, Status: http.StatusCreated,
|
||||
Note: "first admin created"})
|
||||
h.Log.Info("first admin account created", "user", u.Username)
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"user": u, "csrf_token": csrf})
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- users ----------
|
||||
|
||||
func (h *Handler) users(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := Guard(w, r, RoleAdmin); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListUsers()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"users": list})
|
||||
case http.MethodPost:
|
||||
p, ok := Guard(w, r, RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
role, err := ParseRole(in.Role)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(in.Username, in.Password, role)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusCreated, "created user "+u.Username+" as "+string(u.Role))
|
||||
writeJSON(w, http.StatusCreated, u)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) userByID(w http.ResponseWriter, r *http.Request) {
|
||||
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/users/"), "/")
|
||||
if rest == "" {
|
||||
h.users(w, r)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(rest, "/")
|
||||
id, err := strconv.ParseInt(parts[0], 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid user id")
|
||||
return
|
||||
}
|
||||
action := ""
|
||||
if len(parts) > 1 {
|
||||
action = parts[1]
|
||||
}
|
||||
|
||||
// Changing your own password needs only a valid session; everything else
|
||||
// about an account is admin-only.
|
||||
if action == "password" && r.Method == http.MethodPost {
|
||||
p := From(r)
|
||||
if p == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "authentication required")
|
||||
return
|
||||
}
|
||||
self := p.Kind == ActorUser && p.UserID == id
|
||||
if !self && !p.Role.AtLeast(RoleAdmin) {
|
||||
writeErr(w, http.StatusForbidden, "only an admin can change another account's password")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Current string `json:"current_password"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// A user changing their own password must prove they know the old one,
|
||||
// so a stolen session cannot be made permanent.
|
||||
if self {
|
||||
if _, err := h.Store.Authenticate(p.Name, in.Current); err != nil {
|
||||
writeErr(w, http.StatusForbidden, "current password is incorrect")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.Store.SetPassword(id, in.Password); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusOK, "password changed for user id "+parts[0])
|
||||
// Every session for that user was dropped, including this one if it
|
||||
// was their own, so the dashboard must log in again.
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sessions_revoked": true})
|
||||
return
|
||||
}
|
||||
|
||||
p, ok := Guard(w, r, RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case action == "" && r.Method == http.MethodGet:
|
||||
u, err := h.Store.GetUser(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, u)
|
||||
|
||||
case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut):
|
||||
var in struct {
|
||||
Role *string `json:"role"`
|
||||
Disabled *bool `json:"disabled"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
var role *Role
|
||||
if in.Role != nil {
|
||||
rr, err := ParseRole(*in.Role)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
role = &rr
|
||||
}
|
||||
// Refuse to strand the installation with no usable admin.
|
||||
demoting := role != nil && *role != RoleAdmin
|
||||
disabling := in.Disabled != nil && *in.Disabled
|
||||
if demoting || disabling {
|
||||
if err := h.ensureAnotherAdmin(id); err != nil {
|
||||
writeErr(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
u, err := h.Store.UpdateUser(id, role, in.Disabled)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusOK, "updated user "+u.Username)
|
||||
writeJSON(w, http.StatusOK, u)
|
||||
|
||||
case action == "" && r.Method == http.MethodDelete:
|
||||
if err := h.ensureAnotherAdmin(id); err != nil {
|
||||
writeErr(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.Store.DeleteUser(id); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusOK, "deleted user id "+parts[0])
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
|
||||
default:
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
}
|
||||
}
|
||||
|
||||
// ensureAnotherAdmin fails when id is the last enabled admin.
|
||||
func (h *Handler) ensureAnotherAdmin(id int64) error {
|
||||
u, err := h.Store.GetUser(id)
|
||||
if err != nil {
|
||||
return nil // let the caller's own lookup report "not found"
|
||||
}
|
||||
if u.Role != RoleAdmin || u.Disabled {
|
||||
return nil
|
||||
}
|
||||
n, err := h.Store.CountOtherAdmins(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return errors.New("this is the last enabled admin — promote another account first")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------- api keys ----------
|
||||
|
||||
func (h *Handler) apiKeys(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := Guard(w, r, RoleAdmin); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListAPIKeys()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"api_keys": list})
|
||||
case http.MethodPost:
|
||||
p, ok := Guard(w, r, RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(in.Role) == "" {
|
||||
in.Role = string(RoleOperator)
|
||||
}
|
||||
role, err := ParseRole(in.Role)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
k, err := h.Store.CreateAPIKey(in.Name, role)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusCreated, "created api key "+k.Name+" as "+string(k.Role))
|
||||
h.Log.Info("api key created", "name", k.Name, "role", string(k.Role), "by", p.Actor())
|
||||
// The secret appears in this response only, and is never stored.
|
||||
writeJSON(w, http.StatusCreated, k)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) apiKeyByID(w http.ResponseWriter, r *http.Request) {
|
||||
rest := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/apikeys/"), "/")
|
||||
if rest == "" {
|
||||
h.apiKeys(w, r)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(strings.Split(rest, "/")[0], 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid key id")
|
||||
return
|
||||
}
|
||||
p, ok := Guard(w, r, RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodDelete {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if err := h.Store.RevokeAPIKey(id); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "key not found or already revoked")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
h.auditAction(r, p, http.StatusOK, "revoked api key id "+rest)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// ---------- audit ----------
|
||||
|
||||
func (h *Handler) audit(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if _, ok := Guard(w, r, RoleAdmin); !ok {
|
||||
return
|
||||
}
|
||||
// Flush first so the caller sees their own just-made changes.
|
||||
_ = h.Store.FlushAudit()
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
list, err := h.Store.ListAudit(limit, r.URL.Query().Get("actor"))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"audit": list})
|
||||
}
|
||||
|
||||
// AuditRequest records one mutating request against the calling principal.
|
||||
func (s *Store) AuditRequest(p *Principal, trust httpx.Trust, r *http.Request, status int, note string) {
|
||||
kind := ActorKind("")
|
||||
if p != nil {
|
||||
kind = p.Kind
|
||||
}
|
||||
s.Audit(AuditEntry{
|
||||
Actor: p.Actor(),
|
||||
ActorKind: kind,
|
||||
IP: trust.ClientIP(r),
|
||||
Method: r.Method,
|
||||
Path: r.URL.Path,
|
||||
Status: status,
|
||||
Note: note,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) auditAction(r *http.Request, p *Principal, status int, note string) {
|
||||
h.Store.AuditRequest(p, h.MW.Trust, r, status, note)
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
func readJSON(r *http.Request, dst any) error {
|
||||
defer r.Body.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return errors.New("empty body")
|
||||
}
|
||||
return json.Unmarshal(b, dst)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, code int, msg string) {
|
||||
writeJSON(w, code, map[string]any{"error": msg})
|
||||
}
|
||||
|
||||
// NewSetupToken makes the one-time first-run token.
|
||||
func NewSetupToken() string {
|
||||
secret, _, err := NewToken()
|
||||
if err != nil {
|
||||
return "setup-" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return secret
|
||||
}
|
||||
238
apps/streamd/internal/auth/middleware.go
Normal file
238
apps/streamd/internal/auth/middleware.go
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
const (
|
||||
// SessionCookie holds the session secret. HttpOnly, so page scripts
|
||||
// cannot read it.
|
||||
SessionCookie = "streamd_session"
|
||||
// CSRFCookie mirrors the session's CSRF token for the double-submit
|
||||
// check. Deliberately readable by scripts.
|
||||
CSRFCookie = "streamd_csrf"
|
||||
// CSRFHeader is where the dashboard echoes the token back.
|
||||
CSRFHeader = "X-CSRF-Token"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const principalKey ctxKey = 1
|
||||
|
||||
// Middleware resolves the principal for each request, enforces CSRF on
|
||||
// cookie-authenticated mutations, and rate-limits the API.
|
||||
type Middleware struct {
|
||||
Store *Store
|
||||
SessionTTL time.Duration
|
||||
Trust httpx.Trust
|
||||
// CookieSecure forces the Secure attribute even when the request itself
|
||||
// arrived over plain HTTP (the usual case behind a TLS-terminating proxy
|
||||
// that does not set X-Forwarded-Proto).
|
||||
CookieSecure bool
|
||||
|
||||
// APILimiter throttles mutating API calls per client IP.
|
||||
APILimiter *Limiter
|
||||
// LoginLimiter throttles login attempts per IP and per username.
|
||||
LoginLimiter *Limiter
|
||||
}
|
||||
|
||||
func NewMiddleware(store *Store, trust httpx.Trust, cookieSecure bool) *Middleware {
|
||||
return &Middleware{
|
||||
Store: store,
|
||||
SessionTTL: DefaultSessionTTL,
|
||||
Trust: trust,
|
||||
CookieSecure: cookieSecure,
|
||||
APILimiter: NewLimiter(120, 20),
|
||||
LoginLimiter: NewLimiter(8, 0.2),
|
||||
}
|
||||
}
|
||||
|
||||
// From returns the principal attached by Attach, or nil when the caller is
|
||||
// anonymous.
|
||||
func From(r *http.Request) *Principal {
|
||||
p, _ := r.Context().Value(principalKey).(*Principal)
|
||||
return p
|
||||
}
|
||||
|
||||
// WithPrincipal is exported for tests and for internal callers that need to
|
||||
// synthesise an identity.
|
||||
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
|
||||
return context.WithValue(ctx, principalKey, p)
|
||||
}
|
||||
|
||||
// Attach resolves the principal and stores it on the request context. It does
|
||||
// not reject anonymous callers — individual routes decide that via Guard — so
|
||||
// that the login page and the public media paths keep working.
|
||||
func (m *Middleware) Attach(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := m.resolve(r)
|
||||
if p != nil {
|
||||
r = r.WithContext(WithPrincipal(r.Context(), p))
|
||||
}
|
||||
|
||||
if isUnsafe(r.Method) {
|
||||
ip := m.Trust.ClientIP(r)
|
||||
// Rate-limit mutations per client. Login has its own tighter
|
||||
// limiter applied in the handler.
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") && !m.APILimiter.Allow(ip) {
|
||||
retry := m.APILimiter.RetryAfter(ip)
|
||||
w.Header().Set("Retry-After", strconv.Itoa(max(retry, 1)))
|
||||
writeJSONError(w, http.StatusTooManyRequests, "too many requests")
|
||||
return
|
||||
}
|
||||
// CSRF applies only to ambient cookie credentials. A bearer token
|
||||
// is never attached automatically by a browser.
|
||||
if p.NeedsCSRF() && !m.csrfOK(r, p) {
|
||||
writeJSONError(w, http.StatusForbidden, "missing or invalid "+CSRFHeader)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) resolve(r *http.Request) *Principal {
|
||||
// 1. Session cookie.
|
||||
if c, err := r.Cookie(SessionCookie); err == nil && c.Value != "" {
|
||||
if p, err := m.Store.LookupSession(c.Value, m.SessionTTL); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
// 2. Bearer token / X-Streamd-Token. Note there is deliberately no
|
||||
// ?token= fallback any more: it leaked the secret into access logs and
|
||||
// referrers. Agents send the header already.
|
||||
secret := bearer(r)
|
||||
if secret == "" {
|
||||
return nil
|
||||
}
|
||||
p, err := m.Store.LookupAPIKey(secret)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
p.AgentID = sanitiseAgentID(r.Header.Get("X-Agent-ID"))
|
||||
return p
|
||||
}
|
||||
|
||||
func bearer(r *http.Request) string {
|
||||
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
|
||||
if len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") {
|
||||
return strings.TrimSpace(auth[7:])
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(r.Header.Get("X-Streamd-Token"))
|
||||
}
|
||||
|
||||
// sanitiseAgentID keeps a volunteered agent label printable and bounded before
|
||||
// it reaches an audit row.
|
||||
func sanitiseAgentID(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) > 64 {
|
||||
s = s[:64]
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
|
||||
r == '-', r == '_', r == '.':
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *Middleware) csrfOK(r *http.Request, p *Principal) bool {
|
||||
sent := strings.TrimSpace(r.Header.Get(CSRFHeader))
|
||||
if sent == "" {
|
||||
return false
|
||||
}
|
||||
return SecretEqual(sent, p.CSRFToken)
|
||||
}
|
||||
|
||||
func isUnsafe(method string) bool {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Guard enforces a minimum role, writing the error response itself. It returns
|
||||
// the principal and false when the request must not proceed.
|
||||
func Guard(w http.ResponseWriter, r *http.Request, min Role) (*Principal, bool) {
|
||||
p := From(r)
|
||||
if p == nil {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
|
||||
writeJSONError(w, http.StatusUnauthorized, "authentication required")
|
||||
return nil, false
|
||||
}
|
||||
if !p.Role.AtLeast(min) {
|
||||
writeJSONError(w, http.StatusForbidden, "role "+string(p.Role)+" cannot perform this action (needs "+string(min)+")")
|
||||
return nil, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// SetSessionCookies issues the session and CSRF cookies after a login.
|
||||
func (m *Middleware) SetSessionCookies(w http.ResponseWriter, r *http.Request, secret, csrf string) {
|
||||
secure := m.CookieSecure || m.Trust.IsHTTPS(r)
|
||||
maxAge := int(m.SessionTTL.Seconds())
|
||||
if maxAge <= 0 {
|
||||
maxAge = int(DefaultSessionTTL.Seconds())
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookie,
|
||||
Value: secret,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: maxAge,
|
||||
})
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: CSRFCookie,
|
||||
Value: csrf,
|
||||
Path: "/",
|
||||
// Readable on purpose: the dashboard copies it into X-CSRF-Token.
|
||||
HttpOnly: false,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: maxAge,
|
||||
})
|
||||
}
|
||||
|
||||
// ClearSessionCookies expires both cookies on logout.
|
||||
func (m *Middleware) ClearSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
secure := m.CookieSecure || m.Trust.IsHTTPS(r)
|
||||
for _, name := range []string{SessionCookie, CSRFCookie} {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: name == SessionCookie,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// SessionSecret returns the raw session cookie value, for logout.
|
||||
func SessionSecret(r *http.Request) string {
|
||||
if c, err := r.Cookie(SessionCookie); err == nil {
|
||||
return c.Value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, code int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": msg})
|
||||
}
|
||||
140
apps/streamd/internal/auth/ratelimit.go
Normal file
140
apps/streamd/internal/auth/ratelimit.go
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limiter is a keyed token bucket. Keys are usually a client IP, or an
|
||||
// IP+username pair for login attempts.
|
||||
type Limiter struct {
|
||||
// Burst is the bucket capacity.
|
||||
Burst float64
|
||||
// PerSecond is the refill rate.
|
||||
PerSecond float64
|
||||
|
||||
mu sync.Mutex
|
||||
buckets map[string]*bucket
|
||||
lastGC time.Time
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
seen time.Time
|
||||
}
|
||||
|
||||
func NewLimiter(burst, perSecond float64) *Limiter {
|
||||
if burst <= 0 {
|
||||
burst = 1
|
||||
}
|
||||
if perSecond <= 0 {
|
||||
perSecond = 1
|
||||
}
|
||||
return &Limiter{
|
||||
Burst: burst,
|
||||
PerSecond: perSecond,
|
||||
buckets: map[string]*bucket{},
|
||||
lastGC: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// Allow consumes a token for key, reporting whether the request may proceed.
|
||||
func (l *Limiter) Allow(key string) bool {
|
||||
return l.AllowN(key, 1)
|
||||
}
|
||||
|
||||
// AllowN consumes n tokens, for operations that should cost more than one.
|
||||
func (l *Limiter) AllowN(key string, n float64) bool {
|
||||
if l == nil || key == "" {
|
||||
return true
|
||||
}
|
||||
nowT := time.Now()
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.gcLocked(nowT)
|
||||
|
||||
b, ok := l.buckets[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: l.Burst, seen: nowT}
|
||||
l.buckets[key] = b
|
||||
}
|
||||
// Refill for the elapsed time, capped at Burst.
|
||||
elapsed := nowT.Sub(b.seen).Seconds()
|
||||
if elapsed > 0 {
|
||||
b.tokens += elapsed * l.PerSecond
|
||||
if b.tokens > l.Burst {
|
||||
b.tokens = l.Burst
|
||||
}
|
||||
}
|
||||
b.seen = nowT
|
||||
if b.tokens < n {
|
||||
return false
|
||||
}
|
||||
b.tokens -= n
|
||||
return true
|
||||
}
|
||||
|
||||
// Penalise drains a bucket so repeated failures cost more than one attempt.
|
||||
func (l *Limiter) Penalise(key string, tokens float64) {
|
||||
if l == nil || key == "" {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
b, ok := l.buckets[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: l.Burst, seen: time.Now()}
|
||||
l.buckets[key] = b
|
||||
}
|
||||
b.tokens -= tokens
|
||||
if b.tokens < -l.Burst {
|
||||
b.tokens = -l.Burst
|
||||
}
|
||||
}
|
||||
|
||||
// Reset clears a key, used after a successful login.
|
||||
func (l *Limiter) Reset(key string) {
|
||||
if l == nil || key == "" {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
delete(l.buckets, key)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// RetryAfter estimates the seconds until key has a token again.
|
||||
func (l *Limiter) RetryAfter(key string) int {
|
||||
if l == nil {
|
||||
return 0
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
b, ok := l.buckets[key]
|
||||
if !ok || b.tokens >= 1 {
|
||||
return 0
|
||||
}
|
||||
need := 1 - b.tokens
|
||||
secs := int(need/l.PerSecond) + 1
|
||||
if secs < 1 {
|
||||
secs = 1
|
||||
}
|
||||
return secs
|
||||
}
|
||||
|
||||
// gcLocked drops idle buckets so the map cannot grow without bound under a
|
||||
// spray of distinct source addresses.
|
||||
func (l *Limiter) gcLocked(nowT time.Time) {
|
||||
if nowT.Sub(l.lastGC) < time.Minute {
|
||||
return
|
||||
}
|
||||
l.lastGC = nowT
|
||||
idle := time.Duration(float64(time.Second) * (2 * l.Burst / l.PerSecond))
|
||||
if idle < 5*time.Minute {
|
||||
idle = 5 * time.Minute
|
||||
}
|
||||
for k, b := range l.buckets {
|
||||
if nowT.Sub(b.seen) > idle {
|
||||
delete(l.buckets, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
639
apps/streamd/internal/auth/store.go
Normal file
639
apps/streamd/internal/auth/store.go
Normal file
|
|
@ -0,0 +1,639 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultSessionTTL is how long a login lasts without activity.
|
||||
const DefaultSessionTTL = 12 * time.Hour
|
||||
|
||||
// ErrNotFound is returned when a user, key or session does not exist.
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// Store owns the auth tables. It shares streamd's single *sql.DB, so every
|
||||
// write here serialises with the stream writes — audit rows and key
|
||||
// last-used stamps are therefore buffered rather than written per request.
|
||||
type Store struct {
|
||||
DB *sql.DB
|
||||
|
||||
// LegacyToken keeps --token / STREAMD_TOKEN working as an implicit admin
|
||||
// API key so existing agents and scripts do not break.
|
||||
LegacyToken string
|
||||
|
||||
mu sync.Mutex
|
||||
// auditBuf accumulates rows between flushes.
|
||||
auditBuf []AuditEntry
|
||||
// keyTouch throttles api_keys.last_used_at writes to one per minute.
|
||||
keyTouch map[int64]time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role Role `json:"role"`
|
||||
Disabled bool `json:"disabled"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastLoginAt string `json:"last_login_at,omitempty"`
|
||||
}
|
||||
|
||||
type APIKey struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Role Role `json:"role"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastUsedAt string `json:"last_used_at,omitempty"`
|
||||
RevokedAt string `json:"revoked_at,omitempty"`
|
||||
// Secret is populated only in the response that creates the key; it is
|
||||
// never stored and never shown again.
|
||||
Secret string `json:"secret,omitempty"`
|
||||
}
|
||||
|
||||
type AuditEntry struct {
|
||||
ID int64 `json:"id"`
|
||||
At string `json:"at"`
|
||||
Actor string `json:"actor"`
|
||||
ActorKind ActorKind `json:"actor_kind"`
|
||||
IP string `json:"ip"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Status int `json:"status"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
func New(db *sql.DB, legacyToken string) (*Store, error) {
|
||||
s := &Store{DB: db, LegacyToken: strings.TrimSpace(legacyToken), keyTouch: map[int64]time.Time{}}
|
||||
if err := s.Migrate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func now() string { return time.Now().UTC().Format(time.RFC3339) }
|
||||
|
||||
func (s *Store) Migrate() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
pass_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'viewer',
|
||||
disabled INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
last_login_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id_hash TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
csrf TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL DEFAULT '',
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
user_agent TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL UNIQUE,
|
||||
role TEXT NOT NULL DEFAULT 'operator',
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL DEFAULT '',
|
||||
revoked_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
actor_kind TEXT NOT NULL DEFAULT '',
|
||||
ip TEXT NOT NULL DEFAULT '',
|
||||
method TEXT NOT NULL DEFAULT '',
|
||||
path TEXT NOT NULL DEFAULT '',
|
||||
status INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_at ON audit_log(at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// ---------- users ----------
|
||||
|
||||
func (s *Store) CountUsers() (int, error) {
|
||||
var n int
|
||||
err := s.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func normalizeUsername(u string) string {
|
||||
return strings.ToLower(strings.TrimSpace(u))
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(username, password string, role Role) (User, error) {
|
||||
username = normalizeUsername(username)
|
||||
if username == "" {
|
||||
return User{}, fmt.Errorf("username required")
|
||||
}
|
||||
if !role.Valid() {
|
||||
return User{}, fmt.Errorf("invalid role %q", role)
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
res, err := s.DB.Exec(`INSERT INTO users(username,pass_hash,role,disabled,created_at) VALUES(?,?,?,0,?)`,
|
||||
username, hash, string(role), now())
|
||||
if err != nil {
|
||||
if strings.Contains(strings.ToLower(err.Error()), "unique") {
|
||||
return User{}, fmt.Errorf("user %q already exists", username)
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
const userSelect = `SELECT id, username, role, disabled, created_at, last_login_at FROM users`
|
||||
|
||||
type rowScanner interface{ Scan(...any) error }
|
||||
|
||||
func scanUser(row rowScanner) (User, error) {
|
||||
var u User
|
||||
var disabled int
|
||||
var role string
|
||||
if err := row.Scan(&u.ID, &u.Username, &role, &disabled, &u.CreatedAt, &u.LastLoginAt); err != nil {
|
||||
return u, err
|
||||
}
|
||||
u.Role = Role(role)
|
||||
u.Disabled = disabled != 0
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUser(id int64) (User, error) {
|
||||
u, err := scanUser(s.DB.QueryRow(userSelect+` WHERE id=?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return u, ErrNotFound
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
func (s *Store) ListUsers() ([]User, error) {
|
||||
rows, err := s.DB.Query(userSelect + ` ORDER BY username`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []User{}
|
||||
for rows.Next() {
|
||||
u, err := scanUser(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, u)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Authenticate verifies a username and password. It always performs a hash
|
||||
// comparison, even for an unknown user, so a missing account and a wrong
|
||||
// password take the same time.
|
||||
func (s *Store) Authenticate(username, password string) (User, error) {
|
||||
username = normalizeUsername(username)
|
||||
var id int64
|
||||
var hash, role string
|
||||
var disabled int
|
||||
err := s.DB.QueryRow(`SELECT id, pass_hash, role, disabled FROM users WHERE username=?`, username).
|
||||
Scan(&id, &hash, &role, &disabled)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
// Decoy verify against a well-formed hash to equalise timing.
|
||||
VerifyPassword(decoyHash, password)
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !VerifyPassword(hash, password) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
if disabled != 0 {
|
||||
return User{}, fmt.Errorf("account disabled")
|
||||
}
|
||||
_, _ = s.DB.Exec(`UPDATE users SET last_login_at=? WHERE id=?`, now(), id)
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
// decoyHash is a real PBKDF2 hash of an unguessable value, used only to burn
|
||||
// the same CPU on a missing account as on a wrong password.
|
||||
var decoyHash = func() string {
|
||||
secret, _, err := NewToken()
|
||||
if err != nil {
|
||||
secret = "streamd-decoy-value"
|
||||
}
|
||||
h, err := hashWithSalt(secret, []byte("streamd-decoy-sa"), pbkdf2Iterations)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return h
|
||||
}()
|
||||
|
||||
func (s *Store) SetPassword(id int64, password string) error {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := s.DB.Exec(`UPDATE users SET pass_hash=? WHERE id=?`, hash, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
// Changing a password invalidates every existing session for that user.
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateUser(id int64, role *Role, disabled *bool) (User, error) {
|
||||
cur, err := s.GetUser(id)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if role != nil {
|
||||
if !role.Valid() {
|
||||
return User{}, fmt.Errorf("invalid role %q", *role)
|
||||
}
|
||||
cur.Role = *role
|
||||
}
|
||||
if disabled != nil {
|
||||
cur.Disabled = *disabled
|
||||
}
|
||||
d := 0
|
||||
if cur.Disabled {
|
||||
d = 1
|
||||
}
|
||||
if _, err := s.DB.Exec(`UPDATE users SET role=?, disabled=? WHERE id=?`, string(cur.Role), d, id); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if cur.Disabled {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
}
|
||||
return s.GetUser(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteUser(id int64) error {
|
||||
res, err := s.DB.Exec(`DELETE FROM users WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE user_id=?`, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountOtherAdmins counts enabled admins other than excludeID. Used to refuse
|
||||
// deleting, disabling or demoting the last admin.
|
||||
func (s *Store) CountOtherAdmins(excludeID int64) (int, error) {
|
||||
var n int
|
||||
err := s.DB.QueryRow(
|
||||
`SELECT COUNT(*) FROM users WHERE role = 'admin' AND disabled = 0 AND id <> ?`,
|
||||
excludeID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ---------- sessions ----------
|
||||
|
||||
// CreateSession returns the raw session secret and its CSRF token. Only
|
||||
// hashes of the secret reach the database.
|
||||
func (s *Store) CreateSession(userID int64, ttl time.Duration, ip, ua string) (secret, csrf string, err error) {
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultSessionTTL
|
||||
}
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
csrf, _, err = NewToken()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
_, err = s.DB.Exec(`
|
||||
INSERT INTO sessions(id_hash,user_id,csrf,created_at,expires_at,last_seen_at,ip,user_agent)
|
||||
VALUES(?,?,?,?,?,?,?,?)`,
|
||||
hash, userID, csrf, nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339),
|
||||
nowT.Format(time.RFC3339), ip, truncate(ua, 200))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return secret, csrf, nil
|
||||
}
|
||||
|
||||
// LookupSession resolves a raw session secret to a principal, sliding the
|
||||
// expiry forward on use.
|
||||
func (s *Store) LookupSession(secret string, ttl time.Duration) (*Principal, error) {
|
||||
if secret == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultSessionTTL
|
||||
}
|
||||
hash := HashToken(secret)
|
||||
var userID int64
|
||||
var csrf, expires, username, role string
|
||||
var disabled int
|
||||
err := s.DB.QueryRow(`
|
||||
SELECT s.user_id, s.csrf, s.expires_at, u.username, u.role, u.disabled
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.id_hash = ?`, hash).Scan(&userID, &csrf, &expires, &username, &role, &disabled)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if disabled != 0 {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if exp, e := time.Parse(time.RFC3339, expires); e == nil && !exp.After(time.Now().UTC()) {
|
||||
_, _ = s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, hash)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
_, _ = s.DB.Exec(`UPDATE sessions SET last_seen_at=?, expires_at=? WHERE id_hash=?`,
|
||||
nowT.Format(time.RFC3339), nowT.Add(ttl).Format(time.RFC3339), hash)
|
||||
return &Principal{
|
||||
Kind: ActorUser,
|
||||
Role: Role(role),
|
||||
Name: username,
|
||||
UserID: userID,
|
||||
SessionID: secret,
|
||||
CSRFToken: csrf,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(secret string) error {
|
||||
if secret == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := s.DB.Exec(`DELETE FROM sessions WHERE id_hash=?`, HashToken(secret))
|
||||
return err
|
||||
}
|
||||
|
||||
// ExpireSessions drops sessions past their expiry. Returns rows removed.
|
||||
func (s *Store) ExpireSessions() (int64, error) {
|
||||
res, err := s.DB.Exec(`DELETE FROM sessions WHERE expires_at <> '' AND expires_at < ?`, now())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// ---------- api keys ----------
|
||||
|
||||
func (s *Store) CreateAPIKey(name string, role Role) (APIKey, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return APIKey{}, fmt.Errorf("name required")
|
||||
}
|
||||
if !role.Valid() {
|
||||
return APIKey{}, fmt.Errorf("invalid role %q", role)
|
||||
}
|
||||
secret, hash, err := NewToken()
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
res, err := s.DB.Exec(`INSERT INTO api_keys(name,key_hash,role,created_at) VALUES(?,?,?,?)`,
|
||||
name, hash, string(role), now())
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
k, err := s.getAPIKey(id)
|
||||
if err != nil {
|
||||
return APIKey{}, err
|
||||
}
|
||||
k.Secret = secret
|
||||
return k, nil
|
||||
}
|
||||
|
||||
const keySelect = `SELECT id, name, role, created_at, last_used_at, revoked_at FROM api_keys`
|
||||
|
||||
func scanKey(row rowScanner) (APIKey, error) {
|
||||
var k APIKey
|
||||
var role string
|
||||
if err := row.Scan(&k.ID, &k.Name, &role, &k.CreatedAt, &k.LastUsedAt, &k.RevokedAt); err != nil {
|
||||
return k, err
|
||||
}
|
||||
k.Role = Role(role)
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (s *Store) getAPIKey(id int64) (APIKey, error) {
|
||||
k, err := scanKey(s.DB.QueryRow(keySelect+` WHERE id=?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return k, ErrNotFound
|
||||
}
|
||||
return k, err
|
||||
}
|
||||
|
||||
func (s *Store) ListAPIKeys() ([]APIKey, error) {
|
||||
rows, err := s.DB.Query(keySelect + ` ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []APIKey{}
|
||||
for rows.Next() {
|
||||
k, err := scanKey(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RevokeAPIKey(id int64) error {
|
||||
res, err := s.DB.Exec(`UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at = ''`, now(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LookupAPIKey resolves a bearer secret to a principal. The legacy shared
|
||||
// token is accepted first, as an implicit admin key.
|
||||
func (s *Store) LookupAPIKey(secret string) (*Principal, error) {
|
||||
if secret == "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if s.LegacyToken != "" && SecretEqual(secret, s.LegacyToken) {
|
||||
return &Principal{Kind: ActorAPIKey, Role: RoleAdmin, Name: "legacy-token"}, nil
|
||||
}
|
||||
var id int64
|
||||
var name, role, revoked string
|
||||
err := s.DB.QueryRow(`SELECT id, name, role, revoked_at FROM api_keys WHERE key_hash=?`,
|
||||
HashToken(secret)).Scan(&id, &name, &role, &revoked)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if revoked != "" {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
s.touchKey(id)
|
||||
return &Principal{Kind: ActorAPIKey, Role: Role(role), Name: name}, nil
|
||||
}
|
||||
|
||||
// touchKey records last_used_at at most once a minute per key, so a polling
|
||||
// agent does not serialise a write behind every request.
|
||||
func (s *Store) touchKey(id int64) {
|
||||
s.mu.Lock()
|
||||
last, ok := s.keyTouch[id]
|
||||
if ok && time.Since(last) < time.Minute {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.keyTouch[id] = time.Now()
|
||||
s.mu.Unlock()
|
||||
_, _ = s.DB.Exec(`UPDATE api_keys SET last_used_at=? WHERE id=?`, now(), id)
|
||||
}
|
||||
|
||||
// ---------- audit ----------
|
||||
|
||||
// maxAuditBuffer bounds the in-memory audit queue so a wedged flush loop
|
||||
// cannot grow without limit.
|
||||
const maxAuditBuffer = 10_000
|
||||
|
||||
// Audit buffers one audit row. Call FlushAudit to persist.
|
||||
func (s *Store) Audit(e AuditEntry) {
|
||||
if e.At == "" {
|
||||
e.At = now()
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.auditBuf) >= maxAuditBuffer {
|
||||
s.auditBuf = s.auditBuf[1:]
|
||||
}
|
||||
s.auditBuf = append(s.auditBuf, e)
|
||||
}
|
||||
|
||||
// FlushAudit writes buffered audit rows in one transaction.
|
||||
func (s *Store) FlushAudit() error {
|
||||
s.mu.Lock()
|
||||
batch := s.auditBuf
|
||||
s.auditBuf = nil
|
||||
s.mu.Unlock()
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
requeue := func() {
|
||||
s.mu.Lock()
|
||||
s.auditBuf = append(batch, s.auditBuf...)
|
||||
if len(s.auditBuf) > maxAuditBuffer {
|
||||
s.auditBuf = s.auditBuf[len(s.auditBuf)-maxAuditBuffer:]
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
stmt, err := tx.Prepare(`INSERT INTO audit_log(at,actor,actor_kind,ip,method,path,status,note) VALUES(?,?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
for _, e := range batch {
|
||||
if _, err := stmt.Exec(e.At, e.Actor, string(e.ActorKind), e.IP, e.Method, e.Path, e.Status, truncate(e.Note, 500)); err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunMaintenance flushes audit rows, expires sessions and prunes old audit
|
||||
// history until stop is closed.
|
||||
func (s *Store) RunMaintenance(stop <-chan struct{}, retain time.Duration) {
|
||||
t := time.NewTicker(5 * time.Second)
|
||||
defer t.Stop()
|
||||
prune := time.NewTicker(1 * time.Hour)
|
||||
defer prune.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
_ = s.FlushAudit()
|
||||
return
|
||||
case <-t.C:
|
||||
_ = s.FlushAudit()
|
||||
_, _ = s.ExpireSessions()
|
||||
case <-prune.C:
|
||||
if retain > 0 {
|
||||
cutoff := time.Now().UTC().Add(-retain).Format(time.RFC3339)
|
||||
_, _ = s.DB.Exec(`DELETE FROM audit_log WHERE at < ?`, cutoff)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) ListAudit(limit int, actor string) ([]AuditEntry, error) {
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
q := `SELECT id,at,actor,actor_kind,ip,method,path,status,note FROM audit_log`
|
||||
args := []any{}
|
||||
if strings.TrimSpace(actor) != "" {
|
||||
q += ` WHERE actor = ?`
|
||||
args = append(args, strings.TrimSpace(actor))
|
||||
}
|
||||
q += ` ORDER BY id DESC LIMIT ?`
|
||||
args = append(args, limit)
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AuditEntry{}
|
||||
for rows.Next() {
|
||||
var e AuditEntry
|
||||
var kind string
|
||||
if err := rows.Scan(&e.ID, &e.At, &e.Actor, &kind, &e.IP, &e.Method, &e.Path, &e.Status, &e.Note); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.ActorKind = ActorKind(kind)
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
|
@ -14,12 +14,28 @@ import (
|
|||
|
||||
type Store struct {
|
||||
DB *sql.DB
|
||||
// hist buffers event and metric writes; see events.go.
|
||||
hist history
|
||||
}
|
||||
|
||||
// DRM mode values for Stream.DRMMode. "auto" infers from whether the stream
|
||||
// currently holds a key, so a clear channel is not treated as broken for
|
||||
// having none.
|
||||
const (
|
||||
DRMAuto = "auto"
|
||||
DRMYes = "yes"
|
||||
DRMNo = "no"
|
||||
)
|
||||
|
||||
// DefaultIdleTimeoutS is how long an on-demand stream runs with no viewers.
|
||||
const DefaultIdleTimeoutS = 300
|
||||
|
||||
type Stream struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Tags string `json:"tags"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
|
|
@ -31,6 +47,12 @@ type Stream struct {
|
|||
Enabled bool `json:"enabled"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
VariantsJSON string `json:"variants_json"` // FHD/HD/SD ladder config
|
||||
OutputsJSON string `json:"outputs_json"` // HLS/CMAF/DASH/TS output config
|
||||
SettingsJSON string `json:"settings_json"` // per-stream packager knobs
|
||||
DRMMode string `json:"drm_mode"` // auto | yes | no
|
||||
OnDemand bool `json:"on_demand"`
|
||||
IdleTimeoutS int `json:"idle_timeout_s"`
|
||||
Public bool `json:"public"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
|
||||
|
|
@ -45,42 +67,80 @@ type Stream struct {
|
|||
|
||||
// Variants is filled for API responses (play paths + optional live health).
|
||||
Variants []VariantStatus `json:"variants,omitempty"`
|
||||
// Outputs is the resolved output format list for API responses.
|
||||
Outputs []OutputStatus `json:"outputs,omitempty"`
|
||||
// Links is every playable endpoint (variant x output, plus the ABR
|
||||
// master), filled by the API layer which can see the files on disk.
|
||||
Links []PublishLink `json:"links,omitempty"`
|
||||
|
||||
ClaimedBy string `json:"claimed_by,omitempty"`
|
||||
ClaimExp string `json:"claim_expires_at,omitempty"`
|
||||
|
||||
// Derived, never stored. These exist so clients — above all the capture
|
||||
// agent — can reason about credentials without being handed the secrets.
|
||||
HasKey bool `json:"has_key"`
|
||||
HasHeaders bool `json:"has_headers"`
|
||||
HasProxy bool `json:"has_proxy"`
|
||||
KeyValid bool `json:"key_valid"`
|
||||
// DRMRequired is DRMMode resolved: whether this stream needs keys at all.
|
||||
DRMRequired bool `json:"drm_required"`
|
||||
// NeedsCapture is the server's verdict on whether the agent should fetch
|
||||
// fresh credentials. The agent must use this rather than inspecting keys,
|
||||
// which are redacted out of API responses.
|
||||
NeedsCapture bool `json:"needs_capture"`
|
||||
// Viewers is the live client count, filled by the HLS gate.
|
||||
Viewers int `json:"viewers,omitempty"`
|
||||
}
|
||||
|
||||
type CreateStream struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"`
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Tags string `json:"tags"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"`
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
OutputsJSON string `json:"outputs_json"`
|
||||
Outputs []OutputSpec `json:"outputs"`
|
||||
SettingsJSON string `json:"settings_json"`
|
||||
DRMMode string `json:"drm_mode"`
|
||||
OnDemand *bool `json:"on_demand"`
|
||||
IdleTimeoutS *int `json:"idle_timeout_s"`
|
||||
Public *bool `json:"public"`
|
||||
}
|
||||
|
||||
type PatchStream struct {
|
||||
Title *string `json:"title"`
|
||||
App *string `json:"app"`
|
||||
Channel *string `json:"channel"`
|
||||
MPD *string `json:"mpd"`
|
||||
Key *string `json:"key"`
|
||||
HeadersJSON *string `json:"headers_json"`
|
||||
Proxy *string `json:"proxy"`
|
||||
VideoSelect *string `json:"video_select"`
|
||||
AudioSelect *string `json:"audio_select"`
|
||||
Rewriter *string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON *string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
Title *string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Tags *string `json:"tags"`
|
||||
App *string `json:"app"`
|
||||
Channel *string `json:"channel"`
|
||||
MPD *string `json:"mpd"`
|
||||
Key *string `json:"key"`
|
||||
HeadersJSON *string `json:"headers_json"`
|
||||
Proxy *string `json:"proxy"`
|
||||
VideoSelect *string `json:"video_select"`
|
||||
AudioSelect *string `json:"audio_select"`
|
||||
Rewriter *string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON *string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
OutputsJSON *string `json:"outputs_json"`
|
||||
Outputs []OutputSpec `json:"outputs"`
|
||||
SettingsJSON *string `json:"settings_json"`
|
||||
DRMMode *string `json:"drm_mode"`
|
||||
OnDemand *bool `json:"on_demand"`
|
||||
IdleTimeoutS *int `json:"idle_timeout_s"`
|
||||
Public *bool `json:"public"`
|
||||
}
|
||||
|
||||
type Credentials struct {
|
||||
|
|
@ -156,10 +216,30 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Older DBs created before proxy / variants existed.
|
||||
_, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`)
|
||||
_, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`)
|
||||
return nil
|
||||
// Columns added after the original schema. SQLite has no "ADD COLUMN IF
|
||||
// NOT EXISTS", so these are best-effort and fail harmlessly when the
|
||||
// column is already there.
|
||||
for _, stmt := range []string{
|
||||
`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN description TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN tags TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN outputs_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN settings_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN drm_mode TEXT NOT NULL DEFAULT 'auto'`,
|
||||
`ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
|
||||
`ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
|
||||
} {
|
||||
_, _ = s.DB.Exec(stmt)
|
||||
}
|
||||
if err := s.migrateHistory(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.migrateSettings(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateSchedules()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -185,9 +265,13 @@ func slug(name string) string {
|
|||
}
|
||||
|
||||
const streamSelect = `
|
||||
SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
|
||||
SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
|
||||
s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
|
||||
COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
|
||||
COALESCE(s.variants_json,''), s.created_at, s.updated_at,
|
||||
COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
|
||||
COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
|
||||
COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
|
||||
s.created_at, s.updated_at,
|
||||
COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
|
||||
COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
|
||||
COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
|
||||
|
|
@ -218,16 +302,25 @@ func (s *Store) GetStream(id int64) (Stream, error) {
|
|||
return scanStream(row)
|
||||
}
|
||||
|
||||
// GetStreamByName resolves a stream by its slug name, used by the HLS gate.
|
||||
func (s *Store) GetStreamByName(name string) (Stream, error) {
|
||||
row := s.DB.QueryRow(streamSelect+` WHERE s.name = ?`, name)
|
||||
return scanStream(row)
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanStream(row rowScanner) (Stream, error) {
|
||||
var st Stream
|
||||
var enabled int
|
||||
var enabled, onDemand, public int
|
||||
err := row.Scan(
|
||||
&st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
|
||||
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.VariantsJSON,
|
||||
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
|
||||
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
|
||||
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
|
||||
&st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
|
||||
&st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
|
||||
&st.CreatedAt, &st.UpdatedAt,
|
||||
&st.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS,
|
||||
&st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp,
|
||||
|
|
@ -236,6 +329,11 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
return st, err
|
||||
}
|
||||
st.Enabled = enabled != 0
|
||||
st.OnDemand = onDemand != 0
|
||||
st.Public = public != 0
|
||||
if st.IdleTimeoutS <= 0 {
|
||||
st.IdleTimeoutS = DefaultIdleTimeoutS
|
||||
}
|
||||
if st.Health == "" {
|
||||
st.Health = "stopped"
|
||||
}
|
||||
|
|
@ -243,6 +341,7 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
st.PlayPath = "/hls/" + st.Name + "/index.m3u8"
|
||||
}
|
||||
st.Variants = AttachVariantStatuses(st.Name, st.VariantsJSON, st.Health, st.PlaylistAgeS)
|
||||
st.Outputs = AttachOutputStatuses(st.Name, st.OutputsJSON)
|
||||
// Hide expired claims in API responses (ExpireClaims cleans them shortly after).
|
||||
if st.ClaimExp != "" {
|
||||
if exp, e := time.Parse(time.RFC3339, st.ClaimExp); e == nil && !exp.After(time.Now().UTC()) {
|
||||
|
|
@ -250,9 +349,127 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
st.ClaimExp = ""
|
||||
}
|
||||
}
|
||||
st.fillDerived()
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// fillDerived computes the non-secret flags clients use in place of the
|
||||
// credentials themselves.
|
||||
func (st *Stream) fillDerived() {
|
||||
st.HasKey = strings.TrimSpace(st.Key) != ""
|
||||
st.KeyValid = ValidKeyPairs(st.Key)
|
||||
hdr := strings.TrimSpace(st.HeadersJSON)
|
||||
st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
|
||||
st.HasProxy = strings.TrimSpace(st.Proxy) != ""
|
||||
switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
|
||||
case DRMYes:
|
||||
st.DRMRequired = true
|
||||
case DRMNo:
|
||||
st.DRMRequired = false
|
||||
default:
|
||||
// auto: a stream that holds a key is encrypted; one that never had a
|
||||
// key is assumed clear, matching streamd's support for clear content.
|
||||
st.DRMMode = DRMAuto
|
||||
st.DRMRequired = st.HasKey
|
||||
}
|
||||
st.NeedsCapture = st.computeNeedsCapture()
|
||||
}
|
||||
|
||||
// Redact removes credentials from a Stream destined for an API response.
|
||||
// The derived flags survive, so a caller can still tell that a key exists and
|
||||
// whether it parses, without being handed the key itself.
|
||||
func (st *Stream) Redact() {
|
||||
st.Key = ""
|
||||
st.HeadersJSON = ""
|
||||
st.Proxy = ""
|
||||
}
|
||||
|
||||
// Redacted returns a copy with credentials stripped.
|
||||
func (st Stream) Redacted() Stream {
|
||||
st.Redact()
|
||||
return st
|
||||
}
|
||||
|
||||
// bootstrapGraceS is how long a stream may sit in "starting" before we treat
|
||||
// it as needing fresh credentials. It matches the supervisor's own bootstrap
|
||||
// deadline: capturing sooner would restart a stream that is still coming up,
|
||||
// which is a slow restart loop.
|
||||
const bootstrapGraceS = 180
|
||||
|
||||
// computeNeedsCapture reports whether an enabled stream looks down or is
|
||||
// missing the credentials it needs.
|
||||
func (st Stream) computeNeedsCapture() bool {
|
||||
if !st.Enabled {
|
||||
return false
|
||||
}
|
||||
// No manifest at all: only a capture can supply one.
|
||||
if strings.TrimSpace(st.MPD) == "" {
|
||||
return true
|
||||
}
|
||||
// Encrypted streams need usable keys. Clear streams do not, which is why
|
||||
// this is gated on DRMRequired rather than on the key being empty.
|
||||
if st.DRMRequired && !st.KeyValid {
|
||||
return true
|
||||
}
|
||||
// An on-demand stream that is deliberately idle is not broken. Its
|
||||
// credentials are refreshed when a viewer wakes it.
|
||||
if st.OnDemand && (st.Health == "stopped" || st.Health == "") {
|
||||
return false
|
||||
}
|
||||
switch st.Health {
|
||||
case "down", "stopped", "":
|
||||
return true
|
||||
case "starting":
|
||||
// Give the supervisor its bootstrap window before interfering.
|
||||
return st.UptimeS > bootstrapGraceS
|
||||
}
|
||||
return st.PlaylistAgeS > 30
|
||||
}
|
||||
|
||||
// ValidKeyPairs reports whether raw holds at least one KID:KEY pair and every
|
||||
// pair present is a 32-hex:32-hex pair. Separators may be newlines, commas or
|
||||
// semicolons, matching what the supervisor writes to NRE's key file — a
|
||||
// multi-KID stream is valid, which a single-pair check would wrongly reject.
|
||||
func ValidKeyPairs(raw string) bool {
|
||||
lines := SplitKeyLines(raw)
|
||||
if len(lines) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, line := range lines {
|
||||
kid, key, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(hexOnly(kid)) != 32 || len(hexOnly(key)) != 32 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SplitKeyLines normalises a key field into one KID:KEY entry per line.
|
||||
func SplitKeyLines(raw string) []string {
|
||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
||||
var out []string
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hexOnly(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// AttachVariantStatuses builds the variants array for API responses.
|
||||
// Source (FHD) inherits the stream health; scaled variants stay "configured"
|
||||
// until the supervisor refreshes them via EnrichVariantHealth.
|
||||
|
|
@ -266,7 +483,7 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli
|
|||
}
|
||||
if !v.Enabled {
|
||||
vs.Health = "off"
|
||||
} else if v.Height <= 0 {
|
||||
} else if v.Height <= 0 && !v.AudioOnly {
|
||||
vs.Health = streamHealth
|
||||
vs.PlaylistAgeS = playlistAge
|
||||
} else {
|
||||
|
|
@ -277,6 +494,17 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli
|
|||
return out
|
||||
}
|
||||
|
||||
func normalizeDRMMode(s string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case DRMYes:
|
||||
return DRMYes
|
||||
case DRMNo:
|
||||
return DRMNo
|
||||
default:
|
||||
return DRMAuto
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) CreateStream(in CreateStream) (Stream, error) {
|
||||
name := slug(in.Name)
|
||||
if name == "" {
|
||||
|
|
@ -288,38 +516,55 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
|
|||
if !json.Valid([]byte(in.HeadersJSON)) {
|
||||
return Stream{}, fmt.Errorf("headers_json must be valid JSON")
|
||||
}
|
||||
// Installation-wide defaults for on_demand / idle / outputs when the
|
||||
// caller left those fields unset. Explicit body values still win.
|
||||
s.ApplyCreateDefaults(&in)
|
||||
// video_select / audio_select / rewriter are left empty on purpose: the
|
||||
// supervisor resolves them from the stream's app module at start time, so no
|
||||
// provider's preferences are baked into the schema.
|
||||
if in.Title == "" {
|
||||
in.Title = name
|
||||
}
|
||||
variantsJSON := strings.TrimSpace(in.VariantsJSON)
|
||||
if len(in.Variants) > 0 {
|
||||
encoded, err := EncodeVariantsJSON(in.Variants)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
variantsJSON = encoded
|
||||
} else if variantsJSON == "" {
|
||||
variantsJSON, _ = EncodeVariantsJSON(DefaultVariants())
|
||||
} else {
|
||||
encoded, err := EncodeVariantsJSON(ParseVariantsJSON(variantsJSON))
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
variantsJSON = encoded
|
||||
variantsJSON, err := resolveVariantsJSON(in.VariantsJSON, in.Variants, true)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
outputsJSON, err := resolveOutputsJSON(in.OutputsJSON, in.Outputs, true)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
settingsJSON := strings.TrimSpace(in.SettingsJSON)
|
||||
if settingsJSON != "" && !json.Valid([]byte(settingsJSON)) {
|
||||
return Stream{}, fmt.Errorf("settings_json must be valid JSON")
|
||||
}
|
||||
enabled := 0
|
||||
if in.Enabled != nil && *in.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
onDemand := 0
|
||||
if in.OnDemand != nil && *in.OnDemand {
|
||||
onDemand = 1
|
||||
}
|
||||
// Public by default: that is today's behaviour, and an on-demand stream
|
||||
// that nobody may fetch could never be woken.
|
||||
public := 1
|
||||
if in.Public != nil && !*in.Public {
|
||||
public = 0
|
||||
}
|
||||
idle := DefaultIdleTimeoutS
|
||||
if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
|
||||
idle = *in.IdleTimeoutS
|
||||
}
|
||||
ts := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,proxy,video_select,audio_select,enabled,rewriter,variants_json,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
|
||||
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, ts, ts)
|
||||
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,
|
||||
video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
|
||||
settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
|
||||
in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
|
||||
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
|
||||
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
|
|
@ -329,6 +574,51 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|||
return s.GetStream(id)
|
||||
}
|
||||
|
||||
// resolveVariantsJSON normalises the ladder from either the typed list or the
|
||||
// raw JSON field. onCreate fills the default ladder when both are empty.
|
||||
func resolveVariantsJSON(raw string, list []VariantSpec, onCreate bool) (string, error) {
|
||||
if len(list) > 0 {
|
||||
return EncodeVariantsJSON(list)
|
||||
}
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
if onCreate {
|
||||
return EncodeVariantsJSON(DefaultVariants())
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
return EncodeVariantsJSON(ParseVariantsJSON(raw))
|
||||
}
|
||||
|
||||
func resolveOutputsJSON(raw string, list []OutputSpec, onCreate bool) (string, error) {
|
||||
if len(list) > 0 {
|
||||
return EncodeOutputsJSON(list)
|
||||
}
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
if onCreate {
|
||||
return EncodeOutputsJSON(DefaultOutputs())
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
return EncodeOutputsJSON(ParseOutputsJSON(raw))
|
||||
}
|
||||
|
||||
// normalizeTags lowercases and de-duplicates a comma-separated tag list.
|
||||
func normalizeTags(raw string) string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, t := range strings.Split(raw, ",") {
|
||||
t = slug(t)
|
||||
if t == "" || seen[t] {
|
||||
continue
|
||||
}
|
||||
seen[t] = true
|
||||
out = append(out, t)
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
|
||||
func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
||||
cur, err := s.GetStream(id)
|
||||
if err != nil {
|
||||
|
|
@ -337,6 +627,12 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
if in.Title != nil {
|
||||
cur.Title = *in.Title
|
||||
}
|
||||
if in.Description != nil {
|
||||
cur.Description = strings.TrimSpace(*in.Description)
|
||||
}
|
||||
if in.Tags != nil {
|
||||
cur.Tags = normalizeTags(*in.Tags)
|
||||
}
|
||||
if in.App != nil {
|
||||
cur.App = *in.App
|
||||
}
|
||||
|
|
@ -367,18 +663,50 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
if in.Rewriter != nil {
|
||||
cur.Rewriter = *in.Rewriter
|
||||
}
|
||||
if len(in.Variants) > 0 {
|
||||
encoded, err := EncodeVariantsJSON(in.Variants)
|
||||
if in.DRMMode != nil {
|
||||
cur.DRMMode = normalizeDRMMode(*in.DRMMode)
|
||||
}
|
||||
if in.OnDemand != nil {
|
||||
cur.OnDemand = *in.OnDemand
|
||||
}
|
||||
if in.Public != nil {
|
||||
cur.Public = *in.Public
|
||||
}
|
||||
if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
|
||||
cur.IdleTimeoutS = *in.IdleTimeoutS
|
||||
}
|
||||
if in.SettingsJSON != nil {
|
||||
v := strings.TrimSpace(*in.SettingsJSON)
|
||||
if v != "" && !json.Valid([]byte(v)) {
|
||||
return Stream{}, fmt.Errorf("settings_json must be valid JSON")
|
||||
}
|
||||
cur.SettingsJSON = v
|
||||
}
|
||||
if len(in.Variants) > 0 || in.VariantsJSON != nil {
|
||||
raw := ""
|
||||
if in.VariantsJSON != nil {
|
||||
raw = *in.VariantsJSON
|
||||
}
|
||||
encoded, err := resolveVariantsJSON(raw, in.Variants, false)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
cur.VariantsJSON = encoded
|
||||
} else if in.VariantsJSON != nil {
|
||||
encoded, err := EncodeVariantsJSON(ParseVariantsJSON(*in.VariantsJSON))
|
||||
if encoded != "" {
|
||||
cur.VariantsJSON = encoded
|
||||
}
|
||||
}
|
||||
if len(in.Outputs) > 0 || in.OutputsJSON != nil {
|
||||
raw := ""
|
||||
if in.OutputsJSON != nil {
|
||||
raw = *in.OutputsJSON
|
||||
}
|
||||
encoded, err := resolveOutputsJSON(raw, in.Outputs, false)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
cur.VariantsJSON = encoded
|
||||
if encoded != "" {
|
||||
cur.OutputsJSON = encoded
|
||||
}
|
||||
}
|
||||
enabled := 0
|
||||
if cur.Enabled {
|
||||
|
|
@ -391,12 +719,24 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
enabled = 0
|
||||
}
|
||||
}
|
||||
onDemand := 0
|
||||
if cur.OnDemand {
|
||||
onDemand = 1
|
||||
}
|
||||
public := 0
|
||||
if cur.Public {
|
||||
public = 1
|
||||
}
|
||||
ts := now()
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?, proxy=?,
|
||||
video_select=?, audio_select=?, enabled=?, rewriter=?, variants_json=?, updated_at=? WHERE id=?`,
|
||||
cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, cur.Proxy,
|
||||
cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, cur.VariantsJSON, ts, id)
|
||||
UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
|
||||
headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
|
||||
variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
|
||||
idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
|
||||
cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
|
||||
cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
|
||||
cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
|
||||
cur.IdleTimeoutS, public, ts, id)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
|
|
@ -554,21 +894,3 @@ ON CONFLICT(stream_id) DO UPDATE SET
|
|||
id, p.Health, p.PID, play, p.UptimeS, p.BitrateMbps, p.PlaylistAgeS, p.LastError, now())
|
||||
return err
|
||||
}
|
||||
|
||||
// NeedsCapture reports whether an enabled stream looks down / missing creds.
|
||||
func (st Stream) NeedsCapture() bool {
|
||||
if !st.Enabled {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
|
||||
return true
|
||||
}
|
||||
switch st.Health {
|
||||
case "down", "stopped", "starting", "":
|
||||
return true
|
||||
}
|
||||
if st.PlaylistAgeS > 30 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
438
apps/streamd/internal/db/events.go
Normal file
438
apps/streamd/internal/db/events.go
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Event kinds recorded against a stream. Together they are the stream's
|
||||
// timeline: who or what acted, and what the supervisor saw happen.
|
||||
const (
|
||||
EventCreated = "created"
|
||||
EventUpdated = "updated"
|
||||
EventDeleted = "deleted"
|
||||
EventStarted = "started"
|
||||
EventStopped = "stopped"
|
||||
EventRestarted = "restarted"
|
||||
EventCrashed = "crashed"
|
||||
EventFFRestart = "ff_restart"
|
||||
EventVariantUp = "variant_up"
|
||||
EventVariantDown = "variant_down"
|
||||
EventOnDemandWake = "ondemand_wake"
|
||||
EventIdleStop = "idle_stop"
|
||||
EventScheduledStart = "scheduled_start"
|
||||
EventScheduledStop = "scheduled_stop"
|
||||
EventCredsSet = "creds_set"
|
||||
EventClaimed = "claimed"
|
||||
EventReleased = "released"
|
||||
EventProbe = "probe"
|
||||
EventCaptureStarted = "capture_started"
|
||||
EventCaptureOK = "capture_ok"
|
||||
EventCaptureFailed = "capture_failed"
|
||||
)
|
||||
|
||||
// Severities.
|
||||
const (
|
||||
SevInfo = "info"
|
||||
SevWarn = "warn"
|
||||
SevError = "error"
|
||||
)
|
||||
|
||||
// ActorSystem is the actor for anything streamd did by itself.
|
||||
const ActorSystem = "system"
|
||||
|
||||
// StreamEvent is one entry on a stream's timeline.
|
||||
type StreamEvent struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
At string `json:"at"`
|
||||
Kind string `json:"kind"`
|
||||
Severity string `json:"severity"`
|
||||
Actor string `json:"actor"`
|
||||
Message string `json:"message"`
|
||||
// Detail is raw JSON, passed through to the client as-is.
|
||||
Detail json.RawMessage `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// MetricPoint is one health sample for a stream.
|
||||
type MetricPoint struct {
|
||||
At string `json:"at"`
|
||||
Health string `json:"health"`
|
||||
BitrateMbps float64 `json:"bitrate_mbps"`
|
||||
PlaylistAgeS float64 `json:"playlist_age_s"`
|
||||
Viewers int `json:"viewers"`
|
||||
// Bucket is 0 for a raw sample and the rollup width in seconds for an
|
||||
// aggregate (60 for the one-minute rollups kept beyond the raw window).
|
||||
Bucket int `json:"bucket,omitempty"`
|
||||
}
|
||||
|
||||
// Retention windows.
|
||||
const (
|
||||
// RawMetricWindow is how long per-tick samples are kept before being
|
||||
// rolled up into one-minute averages.
|
||||
RawMetricWindow = time.Hour
|
||||
// RollupRetention is how long the one-minute rollups are kept.
|
||||
RollupRetention = 7 * 24 * time.Hour
|
||||
// EventRetention is how long a stream's timeline is kept.
|
||||
EventRetention = 90 * 24 * time.Hour
|
||||
rollupBucketS = 60
|
||||
)
|
||||
|
||||
// history holds the buffered event and metric writes. The store runs on a
|
||||
// single database connection shared with every stream write, so neither a
|
||||
// 5-second metric tick nor a crash loop may write per occurrence.
|
||||
type history struct {
|
||||
mu sync.Mutex
|
||||
events []StreamEvent
|
||||
metrics []bufferedMetric
|
||||
}
|
||||
|
||||
type bufferedMetric struct {
|
||||
streamID int64
|
||||
point MetricPoint
|
||||
}
|
||||
|
||||
const maxHistoryBuffer = 20_000
|
||||
|
||||
func (s *Store) migrateHistory() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS stream_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
at TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
severity TEXT NOT NULL DEFAULT 'info',
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
detail_json TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_stream_at ON stream_events(stream_id, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_at ON stream_events(at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stream_metrics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
at TEXT NOT NULL,
|
||||
health TEXT NOT NULL DEFAULT '',
|
||||
bitrate_mbps REAL NOT NULL DEFAULT 0,
|
||||
playlist_age_s REAL NOT NULL DEFAULT 0,
|
||||
viewers INTEGER NOT NULL DEFAULT 0,
|
||||
bucket INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_metrics_stream_at ON stream_metrics(stream_id, at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddEvent buffers one timeline entry.
|
||||
func (s *Store) AddEvent(e StreamEvent) {
|
||||
if e.StreamID == 0 || e.Kind == "" {
|
||||
return
|
||||
}
|
||||
if e.At == "" {
|
||||
e.At = now()
|
||||
}
|
||||
if e.Severity == "" {
|
||||
e.Severity = SevInfo
|
||||
}
|
||||
if e.Actor == "" {
|
||||
e.Actor = ActorSystem
|
||||
}
|
||||
e.Message = truncateStr(e.Message, 2000)
|
||||
s.hist.mu.Lock()
|
||||
defer s.hist.mu.Unlock()
|
||||
if len(s.hist.events) >= maxHistoryBuffer {
|
||||
s.hist.events = s.hist.events[1:]
|
||||
}
|
||||
s.hist.events = append(s.hist.events, e)
|
||||
}
|
||||
|
||||
// Eventf is the common case: a system event with a formatted message.
|
||||
func (s *Store) Eventf(streamID int64, kind, severity, format string, args ...any) {
|
||||
s.AddEvent(StreamEvent{
|
||||
StreamID: streamID,
|
||||
Kind: kind,
|
||||
Severity: severity,
|
||||
Actor: ActorSystem,
|
||||
Message: fmt.Sprintf(format, args...),
|
||||
})
|
||||
}
|
||||
|
||||
// AddMetric buffers one health sample.
|
||||
func (s *Store) AddMetric(streamID int64, p MetricPoint) {
|
||||
if streamID == 0 {
|
||||
return
|
||||
}
|
||||
if p.At == "" {
|
||||
p.At = now()
|
||||
}
|
||||
s.hist.mu.Lock()
|
||||
defer s.hist.mu.Unlock()
|
||||
if len(s.hist.metrics) >= maxHistoryBuffer {
|
||||
s.hist.metrics = s.hist.metrics[1:]
|
||||
}
|
||||
s.hist.metrics = append(s.hist.metrics, bufferedMetric{streamID: streamID, point: p})
|
||||
}
|
||||
|
||||
// FlushHistory writes buffered events and metrics in one transaction.
|
||||
func (s *Store) FlushHistory() error {
|
||||
s.hist.mu.Lock()
|
||||
events := s.hist.events
|
||||
metrics := s.hist.metrics
|
||||
s.hist.events = nil
|
||||
s.hist.metrics = nil
|
||||
s.hist.mu.Unlock()
|
||||
|
||||
if len(events) == 0 && len(metrics) == 0 {
|
||||
return nil
|
||||
}
|
||||
requeue := func() {
|
||||
s.hist.mu.Lock()
|
||||
s.hist.events = append(events, s.hist.events...)
|
||||
s.hist.metrics = append(metrics, s.hist.metrics...)
|
||||
if len(s.hist.events) > maxHistoryBuffer {
|
||||
s.hist.events = s.hist.events[len(s.hist.events)-maxHistoryBuffer:]
|
||||
}
|
||||
if len(s.hist.metrics) > maxHistoryBuffer {
|
||||
s.hist.metrics = s.hist.metrics[len(s.hist.metrics)-maxHistoryBuffer:]
|
||||
}
|
||||
s.hist.mu.Unlock()
|
||||
}
|
||||
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
if len(events) > 0 {
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO stream_events(stream_id,at,kind,severity,actor,message,detail_json)
|
||||
VALUES(?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
for _, e := range events {
|
||||
// A stream deleted between buffering and flushing takes its
|
||||
// events with it; the foreign key makes that insert fail, which
|
||||
// must not abort the whole batch.
|
||||
_, _ = stmt.Exec(e.StreamID, e.At, e.Kind, e.Severity, e.Actor, e.Message, string(e.Detail))
|
||||
}
|
||||
_ = stmt.Close()
|
||||
}
|
||||
if len(metrics) > 0 {
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
||||
VALUES(?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
for _, m := range metrics {
|
||||
_, _ = stmt.Exec(m.streamID, m.point.At, m.point.Health,
|
||||
m.point.BitrateMbps, m.point.PlaylistAgeS, m.point.Viewers, m.point.Bucket)
|
||||
}
|
||||
_ = stmt.Close()
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListEvents returns a stream's timeline, newest first.
|
||||
func (s *Store) ListEvents(streamID int64, limit int, kind, since string) ([]StreamEvent, error) {
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
q := `SELECT id,stream_id,at,kind,severity,actor,message,detail_json
|
||||
FROM stream_events WHERE stream_id = ?`
|
||||
args := []any{streamID}
|
||||
if k := strings.TrimSpace(kind); k != "" {
|
||||
// Accept a comma-separated kind filter.
|
||||
kinds := strings.Split(k, ",")
|
||||
ph := make([]string, 0, len(kinds))
|
||||
for _, one := range kinds {
|
||||
if one = strings.TrimSpace(one); one != "" {
|
||||
ph = append(ph, "?")
|
||||
args = append(args, one)
|
||||
}
|
||||
}
|
||||
if len(ph) > 0 {
|
||||
q += ` AND kind IN (` + strings.Join(ph, ",") + `)`
|
||||
}
|
||||
}
|
||||
if sv := strings.TrimSpace(since); sv != "" {
|
||||
q += ` AND at >= ?`
|
||||
args = append(args, sv)
|
||||
}
|
||||
q += ` ORDER BY id DESC LIMIT ?`
|
||||
args = append(args, limit)
|
||||
return s.queryEvents(q, args...)
|
||||
}
|
||||
|
||||
// RecentEvents returns the newest events across every stream, for the
|
||||
// dashboard's activity feed.
|
||||
func (s *Store) RecentEvents(limit int) ([]StreamEvent, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 50
|
||||
}
|
||||
return s.queryEvents(`
|
||||
SELECT e.id, e.stream_id, e.at, e.kind, e.severity, e.actor, e.message, e.detail_json, s.name
|
||||
FROM stream_events e LEFT JOIN streams s ON s.id = e.stream_id
|
||||
ORDER BY e.id DESC LIMIT ?`, limit)
|
||||
}
|
||||
|
||||
func (s *Store) queryEvents(q string, args ...any) ([]StreamEvent, error) {
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
withName := len(cols) > 8
|
||||
out := []StreamEvent{}
|
||||
for rows.Next() {
|
||||
var e StreamEvent
|
||||
var detail string
|
||||
var name *string
|
||||
dest := []any{&e.ID, &e.StreamID, &e.At, &e.Kind, &e.Severity, &e.Actor, &e.Message, &detail}
|
||||
if withName {
|
||||
dest = append(dest, &name)
|
||||
}
|
||||
if err := rows.Scan(dest...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if detail != "" && json.Valid([]byte(detail)) {
|
||||
e.Detail = json.RawMessage(detail)
|
||||
}
|
||||
if name != nil {
|
||||
e.StreamName = *name
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListMetrics returns samples for a stream within the window, oldest first.
|
||||
func (s *Store) ListMetrics(streamID int64, window time.Duration) ([]MetricPoint, error) {
|
||||
if window <= 0 {
|
||||
window = time.Hour
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT at,health,bitrate_mbps,playlist_age_s,viewers,bucket
|
||||
FROM stream_metrics WHERE stream_id = ? AND at >= ?
|
||||
ORDER BY at ASC`, streamID, cutoff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []MetricPoint{}
|
||||
for rows.Next() {
|
||||
var p MetricPoint
|
||||
if err := rows.Scan(&p.At, &p.Health, &p.BitrateMbps, &p.PlaylistAgeS, &p.Viewers, &p.Bucket); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UptimeRatio is the fraction of samples in the window where the stream was
|
||||
// healthy. Returns -1 when there is nothing to judge from.
|
||||
func (s *Store) UptimeRatio(streamID int64, window time.Duration) (float64, error) {
|
||||
if window <= 0 {
|
||||
window = 24 * time.Hour
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
||||
var total, ok int
|
||||
err := s.DB.QueryRow(`
|
||||
SELECT COUNT(*), COALESCE(SUM(CASE WHEN health = 'ok' THEN 1 ELSE 0 END),0)
|
||||
FROM stream_metrics WHERE stream_id = ? AND at >= ?`, streamID, cutoff).Scan(&total, &ok)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
if total == 0 {
|
||||
return -1, nil
|
||||
}
|
||||
return float64(ok) / float64(total), nil
|
||||
}
|
||||
|
||||
// RollupMetrics collapses raw samples older than RawMetricWindow into
|
||||
// one-minute averages, then drops rollups and events past their retention.
|
||||
// Keeping every 5-second sample for a week would be millions of rows per
|
||||
// stream for no benefit at that zoom level.
|
||||
func (s *Store) RollupMetrics() error {
|
||||
rawCutoff := time.Now().UTC().Add(-RawMetricWindow).Format(time.RFC3339)
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// SQLite has no date_trunc, but the timestamps are fixed-width RFC3339
|
||||
// (…THH:MM:SSZ), so truncating to the minute is a substring.
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
||||
SELECT stream_id,
|
||||
substr(at, 1, 17) || '00Z',
|
||||
-- the worst health in the minute, so an outage is never averaged away
|
||||
CASE WHEN SUM(CASE WHEN health <> 'ok' THEN 1 ELSE 0 END) > 0 THEN 'degraded' ELSE 'ok' END,
|
||||
AVG(bitrate_mbps), AVG(playlist_age_s), MAX(viewers), ?
|
||||
FROM stream_metrics
|
||||
WHERE bucket = 0 AND at < ?
|
||||
GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE bucket = 0 AND at < ?`, rawCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
rollupCutoff := time.Now().UTC().Add(-RollupRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE at < ?`, rollupCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
eventCutoff := time.Now().UTC().Add(-EventRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`DELETE FROM stream_events WHERE at < ?`, eventCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// RunHistoryMaintenance flushes buffered history and prunes on a schedule.
|
||||
func (s *Store) RunHistoryMaintenance(stop <-chan struct{}) {
|
||||
flush := time.NewTicker(5 * time.Second)
|
||||
defer flush.Stop()
|
||||
prune := time.NewTicker(15 * time.Minute)
|
||||
defer prune.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
_ = s.FlushHistory()
|
||||
return
|
||||
case <-flush.C:
|
||||
_ = s.FlushHistory()
|
||||
case <-prune.C:
|
||||
_ = s.RollupMetrics()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func truncateStr(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
285
apps/streamd/internal/db/outputs.go
Normal file
285
apps/streamd/internal/db/outputs.go
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Output formats. These are the muxers the packager can be asked to emit for
|
||||
// each enabled variant. They are orthogonal to the resolution ladder: the set
|
||||
// actually published is variants x outputs.
|
||||
const (
|
||||
// FormatHLS is mpegts HLS — the original and only output, kept as the
|
||||
// default so an upgraded install publishes exactly what it did before.
|
||||
FormatHLS = "hls"
|
||||
// FormatCMAF is fMP4/CMAF HLS: init.mp4 plus .m4s segments.
|
||||
FormatCMAF = "hls_fmp4"
|
||||
// FormatDASH is MPEG-DASH.
|
||||
FormatDASH = "dash"
|
||||
// FormatTS is a progressive, endless MPEG-TS stream served from a shared
|
||||
// ring buffer rather than from disk.
|
||||
FormatTS = "mpegts"
|
||||
)
|
||||
|
||||
// OutputSpec is one configured output format for a stream.
|
||||
type OutputSpec struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Format string `json:"format"`
|
||||
Enabled bool `json:"enabled"`
|
||||
// SegmentDuration and ListSize override the stream's packager settings for
|
||||
// this output only. Zero means "inherit".
|
||||
SegmentDuration int `json:"segment_duration,omitempty"`
|
||||
ListSize int `json:"list_size,omitempty"`
|
||||
}
|
||||
|
||||
// OutputStatus is an OutputSpec as reported by the API.
|
||||
type OutputStatus struct {
|
||||
OutputSpec
|
||||
}
|
||||
|
||||
// PublishLink is one playable endpoint: a variant crossed with an output
|
||||
// format, or the ABR master playlist. The dashboard renders one row per link.
|
||||
type PublishLink struct {
|
||||
VariantID string `json:"variant_id"`
|
||||
VariantLabel string `json:"variant_label"`
|
||||
OutputID string `json:"output_id"`
|
||||
OutputLabel string `json:"output_label"`
|
||||
Format string `json:"format"`
|
||||
PlayPath string `json:"play_path"`
|
||||
Health string `json:"health,omitempty"`
|
||||
PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
|
||||
// Master marks the ABR master playlist, which spans every variant.
|
||||
Master bool `json:"master,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultOutputs is the output set for a new stream: mpegts HLS only. The
|
||||
// other formats exist but stay off, so turning one on is always a deliberate
|
||||
// act and an upgraded install does not silently start transcoding more.
|
||||
func DefaultOutputs() []OutputSpec {
|
||||
return []OutputSpec{
|
||||
{ID: "hls", Label: "HLS", Format: FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Label: "CMAF", Format: FormatCMAF, Enabled: false},
|
||||
{ID: "dash", Label: "DASH", Format: FormatDASH, Enabled: false},
|
||||
{ID: "ts", Label: "TS", Format: FormatTS, Enabled: false},
|
||||
}
|
||||
}
|
||||
|
||||
// knownFormats maps a format to its default id and label.
|
||||
var knownFormats = map[string]struct{ id, label, container string }{
|
||||
FormatHLS: {"hls", "HLS", "mpegts"},
|
||||
FormatCMAF: {"cmaf", "CMAF", "fmp4"},
|
||||
FormatDASH: {"dash", "DASH", "fmp4"},
|
||||
FormatTS: {"ts", "TS", "mpegts"},
|
||||
}
|
||||
|
||||
// normalizeFormat maps user input onto a known format, tolerating the shorter
|
||||
// aliases the UI and API are likely to send.
|
||||
func normalizeFormat(f string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(f)) {
|
||||
case FormatHLS, "m3u8", "hls_mpegts", "hls-ts":
|
||||
return FormatHLS
|
||||
case FormatCMAF, "cmaf", "fmp4", "hls-fmp4":
|
||||
return FormatCMAF
|
||||
case FormatDASH, "mpd":
|
||||
return FormatDASH
|
||||
case FormatTS, "ts", "progressive":
|
||||
return FormatTS
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ParseOutputsJSON reads outputs_json. Empty or unparseable falls back to the
|
||||
// defaults, matching how the variant ladder behaves.
|
||||
func ParseOutputsJSON(raw string) []OutputSpec {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "[]" || raw == "null" {
|
||||
return DefaultOutputs()
|
||||
}
|
||||
var list []OutputSpec
|
||||
if err := json.Unmarshal([]byte(raw), &list); err != nil || len(list) == 0 {
|
||||
return DefaultOutputs()
|
||||
}
|
||||
return NormalizeOutputs(list)
|
||||
}
|
||||
|
||||
// NormalizeOutputs fills ids and labels, drops unknown formats, de-duplicates
|
||||
// by format, and guarantees every known format has an entry so a client can
|
||||
// toggle one without having to know the full list.
|
||||
func NormalizeOutputs(in []OutputSpec) []OutputSpec {
|
||||
byFormat := map[string]OutputSpec{}
|
||||
for _, o := range in {
|
||||
f := normalizeFormat(o.Format)
|
||||
if f == "" {
|
||||
// Allow a client to identify an output by id alone.
|
||||
f = normalizeFormat(o.ID)
|
||||
}
|
||||
if f == "" {
|
||||
continue
|
||||
}
|
||||
meta := knownFormats[f]
|
||||
o.Format = f
|
||||
if o.ID = slug(o.ID); o.ID == "" {
|
||||
o.ID = meta.id
|
||||
}
|
||||
if strings.TrimSpace(o.Label) == "" {
|
||||
o.Label = meta.label
|
||||
}
|
||||
if o.SegmentDuration < 0 {
|
||||
o.SegmentDuration = 0
|
||||
}
|
||||
if o.ListSize < 0 {
|
||||
o.ListSize = 0
|
||||
}
|
||||
// A later entry for the same format wins, so a partial patch applies
|
||||
// cleanly over the defaults.
|
||||
byFormat[f] = o
|
||||
}
|
||||
out := make([]OutputSpec, 0, len(knownFormats))
|
||||
for _, def := range DefaultOutputs() {
|
||||
if got, ok := byFormat[def.Format]; ok {
|
||||
out = append(out, got)
|
||||
continue
|
||||
}
|
||||
out = append(out, def)
|
||||
}
|
||||
// An output set with nothing enabled would publish nothing at all and
|
||||
// leave the stream unreachable; fall back to HLS.
|
||||
anyOn := false
|
||||
for _, o := range out {
|
||||
if o.Enabled {
|
||||
anyOn = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !anyOn {
|
||||
for i := range out {
|
||||
if out[i].Format == FormatHLS {
|
||||
out[i].Enabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func EncodeOutputsJSON(list []OutputSpec) (string, error) {
|
||||
list = NormalizeOutputs(list)
|
||||
b, err := json.Marshal(list)
|
||||
if err != nil {
|
||||
return "[]", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// EnabledOutputs returns the outputs that should be muxed.
|
||||
func EnabledOutputs(list []OutputSpec) []OutputSpec {
|
||||
var out []OutputSpec
|
||||
for _, o := range list {
|
||||
if o.Enabled {
|
||||
out = append(out, o)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AttachOutputStatuses builds the outputs array for API responses.
|
||||
func AttachOutputStatuses(streamName, outputsJSON string) []OutputStatus {
|
||||
specs := ParseOutputsJSON(outputsJSON)
|
||||
out := make([]OutputStatus, 0, len(specs))
|
||||
for _, o := range specs {
|
||||
out = append(out, OutputStatus{OutputSpec: o})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// VariantDir is the www subdirectory for one variant: the stream name for the
|
||||
// source rung, and "<name>-<id>" for every other rung. This is the single
|
||||
// definition of that layout; the HLS gate parses it back.
|
||||
func VariantDir(streamName, variantID string, height int, audioOnly bool) string {
|
||||
variantID = slug(variantID)
|
||||
if !audioOnly && (height <= 0 || variantID == "" || variantID == SourceVariantID) {
|
||||
return streamName
|
||||
}
|
||||
return streamName + "-" + variantID
|
||||
}
|
||||
|
||||
// OutputSubPath is the path of an output's playlist relative to its variant
|
||||
// directory. The mpegts HLS playlist stays at the root of the directory so
|
||||
// existing /hls/<name>/index.m3u8 URLs never move.
|
||||
func OutputSubPath(format string) string {
|
||||
switch normalizeFormat(format) {
|
||||
case FormatHLS:
|
||||
return "index.m3u8"
|
||||
case FormatCMAF:
|
||||
return "cmaf/index.m3u8"
|
||||
case FormatDASH:
|
||||
return "dash/index.mpd"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// OutputPlayPath is the URL for one variant x output pair. Progressive TS is
|
||||
// served from /live/ because it is a live pipe, not a file on disk.
|
||||
func OutputPlayPath(streamName, variantID string, height int, audioOnly bool, format string) string {
|
||||
dir := VariantDir(streamName, variantID, height, audioOnly)
|
||||
if normalizeFormat(format) == FormatTS {
|
||||
return "/live/" + dir + ".ts"
|
||||
}
|
||||
sub := OutputSubPath(format)
|
||||
if sub == "" {
|
||||
return ""
|
||||
}
|
||||
return "/hls/" + dir + "/" + sub
|
||||
}
|
||||
|
||||
// MasterPlayPath is the ABR master playlist spanning every enabled variant.
|
||||
func MasterPlayPath(streamName string) string {
|
||||
return "/hls/" + streamName + "/master.m3u8"
|
||||
}
|
||||
|
||||
// BuildPublishLinks is the cross product of enabled variants and enabled
|
||||
// outputs, with the ABR master first when there is more than one rung to
|
||||
// choose between. Health is left empty here and filled by the API layer, which
|
||||
// is the part that can see the files on disk.
|
||||
func BuildPublishLinks(streamName, variantsJSON, outputsJSON string) []PublishLink {
|
||||
variants := EnabledVariants(ParseVariantsJSON(variantsJSON))
|
||||
outputs := EnabledOutputs(ParseOutputsJSON(outputsJSON))
|
||||
links := make([]PublishLink, 0, len(variants)*len(outputs)+1)
|
||||
|
||||
// The master is only meaningful when HLS is on and there is a real choice.
|
||||
hlsOn := false
|
||||
for _, o := range outputs {
|
||||
if o.Format == FormatHLS || o.Format == FormatCMAF {
|
||||
hlsOn = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hlsOn && len(variants) > 1 {
|
||||
links = append(links, PublishLink{
|
||||
VariantID: "all",
|
||||
VariantLabel: "ABR",
|
||||
OutputID: "master",
|
||||
OutputLabel: "Master",
|
||||
Format: FormatHLS,
|
||||
PlayPath: MasterPlayPath(streamName),
|
||||
Master: true,
|
||||
})
|
||||
}
|
||||
for _, v := range variants {
|
||||
for _, o := range outputs {
|
||||
p := OutputPlayPath(streamName, v.ID, v.Height, v.AudioOnly, o.Format)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
links = append(links, PublishLink{
|
||||
VariantID: v.ID,
|
||||
VariantLabel: v.Label,
|
||||
OutputID: o.ID,
|
||||
OutputLabel: o.Label,
|
||||
Format: o.Format,
|
||||
PlayPath: p,
|
||||
})
|
||||
}
|
||||
}
|
||||
return links
|
||||
}
|
||||
459
apps/streamd/internal/db/schedules.go
Normal file
459
apps/streamd/internal/db/schedules.go
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Schedule actions and kinds.
|
||||
const (
|
||||
ActionStart = "start"
|
||||
ActionStop = "stop"
|
||||
|
||||
KindOnce = "once"
|
||||
KindWeekly = "weekly"
|
||||
)
|
||||
|
||||
// Schedule is one timed action on a stream: a council meeting at 19:00 every
|
||||
// Tuesday, or a one-off match on Saturday.
|
||||
type Schedule struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Kind string `json:"kind"`
|
||||
// AtUTC is the moment a "once" schedule fires, RFC3339.
|
||||
AtUTC string `json:"at_utc,omitempty"`
|
||||
// DaysMask is a bitmask of weekdays for a "weekly" schedule, with
|
||||
// Sunday as bit 0 through Saturday as bit 6.
|
||||
DaysMask int `json:"days_mask,omitempty"`
|
||||
// TimeOfDay is "HH:MM" in TZ, for a "weekly" schedule.
|
||||
TimeOfDay string `json:"time_of_day,omitempty"`
|
||||
// TZ is an IANA zone name. Local wall-clock time is what an operator
|
||||
// means by "19:00", so the zone is stored rather than a UTC offset: an
|
||||
// offset would drift by an hour across a DST boundary.
|
||||
TZ string `json:"tz,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
LastFiredAt string `json:"last_fired_at,omitempty"`
|
||||
NextFireAt string `json:"next_fire_at,omitempty"`
|
||||
CreatedBy string `json:"created_by,omitempty"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
// PrerollFiredFor records the NextFireAt a pre-roll capture was already
|
||||
// requested for, so it happens once per occurrence.
|
||||
PrerollFiredFor string `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Store) migrateSchedules() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS schedules (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
action TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
at_utc TEXT NOT NULL DEFAULT '',
|
||||
days_mask INTEGER NOT NULL DEFAULT 0,
|
||||
time_of_day TEXT NOT NULL DEFAULT '',
|
||||
tz TEXT NOT NULL DEFAULT 'UTC',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
last_fired_at TEXT NOT NULL DEFAULT '',
|
||||
next_fire_at TEXT NOT NULL DEFAULT '',
|
||||
preroll_fired_for TEXT NOT NULL DEFAULT '',
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_schedules_next ON schedules(enabled, next_fire_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_schedules_stream ON schedules(stream_id);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate checks a schedule and normalises its fields.
|
||||
func (sc *Schedule) Validate() error {
|
||||
sc.Action = strings.ToLower(strings.TrimSpace(sc.Action))
|
||||
switch sc.Action {
|
||||
case ActionStart, ActionStop:
|
||||
default:
|
||||
return fmt.Errorf("action must be %q or %q", ActionStart, ActionStop)
|
||||
}
|
||||
sc.Kind = strings.ToLower(strings.TrimSpace(sc.Kind))
|
||||
if sc.TZ = strings.TrimSpace(sc.TZ); sc.TZ == "" {
|
||||
sc.TZ = "UTC"
|
||||
}
|
||||
if _, err := time.LoadLocation(sc.TZ); err != nil {
|
||||
return fmt.Errorf("unknown timezone %q", sc.TZ)
|
||||
}
|
||||
switch sc.Kind {
|
||||
case KindOnce:
|
||||
t, err := ParseScheduleTime(sc.AtUTC, sc.TZ)
|
||||
if err != nil {
|
||||
return fmt.Errorf("at_utc: %w", err)
|
||||
}
|
||||
sc.AtUTC = t.UTC().Format(time.RFC3339)
|
||||
case KindWeekly:
|
||||
if _, _, err := parseHHMM(sc.TimeOfDay); err != nil {
|
||||
return fmt.Errorf("time_of_day: %w", err)
|
||||
}
|
||||
if sc.DaysMask&0x7F == 0 {
|
||||
return errors.New("days_mask must select at least one weekday")
|
||||
}
|
||||
sc.DaysMask &= 0x7F
|
||||
default:
|
||||
return fmt.Errorf("kind must be %q or %q", KindOnce, KindWeekly)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseScheduleTime accepts an RFC3339 instant, or a local "YYYY-MM-DD HH:MM"
|
||||
// interpreted in tz — which is how a person types a meeting time.
|
||||
func ParseScheduleTime(s, tz string) (time.Time, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, errors.New("a time is required")
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
loc, err := time.LoadLocation(tz)
|
||||
if err != nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
for _, layout := range []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02 15:04:05"} {
|
||||
if t, err := time.ParseInLocation(layout, s, loc); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("could not parse %q as a time", s)
|
||||
}
|
||||
|
||||
func parseHHMM(s string) (hour, minute int, err error) {
|
||||
s = strings.TrimSpace(s)
|
||||
t, err := time.Parse("15:04", s)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("want HH:MM, got %q", s)
|
||||
}
|
||||
return t.Hour(), t.Minute(), nil
|
||||
}
|
||||
|
||||
// NextFire computes the next time this schedule should fire, strictly after
|
||||
// the given moment. The zero time means "never again".
|
||||
func (sc Schedule) NextFire(after time.Time) time.Time {
|
||||
if !sc.Enabled {
|
||||
return time.Time{}
|
||||
}
|
||||
switch sc.Kind {
|
||||
case KindOnce:
|
||||
t, err := time.Parse(time.RFC3339, sc.AtUTC)
|
||||
if err != nil || !t.After(after) {
|
||||
return time.Time{}
|
||||
}
|
||||
return t.UTC()
|
||||
case KindWeekly:
|
||||
hour, minute, err := parseHHMM(sc.TimeOfDay)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
loc, err := time.LoadLocation(sc.TZ)
|
||||
if err != nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
// Walk forward day by day in the target zone. Constructing the time
|
||||
// per local day is what makes this correct across a DST change: the
|
||||
// event stays at 19:00 wall clock rather than drifting an hour.
|
||||
local := after.In(loc)
|
||||
for i := 0; i <= 8; i++ {
|
||||
day := local.AddDate(0, 0, i)
|
||||
if sc.DaysMask&(1<<uint(day.Weekday())) == 0 {
|
||||
continue
|
||||
}
|
||||
cand := time.Date(day.Year(), day.Month(), day.Day(), hour, minute, 0, 0, loc)
|
||||
if cand.After(after) {
|
||||
return cand.UTC()
|
||||
}
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
const scheduleSelect = `
|
||||
SELECT sc.id, sc.stream_id, sc.action, sc.kind, sc.at_utc, sc.days_mask,
|
||||
sc.time_of_day, sc.tz, sc.enabled, sc.last_fired_at, sc.next_fire_at,
|
||||
sc.preroll_fired_for, sc.created_by, sc.created_at, COALESCE(s.name,'')
|
||||
FROM schedules sc LEFT JOIN streams s ON s.id = sc.stream_id`
|
||||
|
||||
func scanSchedule(row rowScanner) (Schedule, error) {
|
||||
var sc Schedule
|
||||
var enabled int
|
||||
err := row.Scan(&sc.ID, &sc.StreamID, &sc.Action, &sc.Kind, &sc.AtUTC, &sc.DaysMask,
|
||||
&sc.TimeOfDay, &sc.TZ, &enabled, &sc.LastFiredAt, &sc.NextFireAt,
|
||||
&sc.PrerollFiredFor, &sc.CreatedBy, &sc.CreatedAt, &sc.StreamName)
|
||||
if err != nil {
|
||||
return sc, err
|
||||
}
|
||||
sc.Enabled = enabled != 0
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateSchedule(sc Schedule) (Schedule, error) {
|
||||
if err := sc.Validate(); err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
if _, err := s.GetStream(sc.StreamID); err != nil {
|
||||
return Schedule{}, fmt.Errorf("stream %d not found", sc.StreamID)
|
||||
}
|
||||
sc.Enabled = true
|
||||
next := sc.NextFire(time.Now().UTC())
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO schedules(stream_id,action,kind,at_utc,days_mask,time_of_day,tz,enabled,
|
||||
next_fire_at,created_by,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,1,?,?,?)`,
|
||||
sc.StreamID, sc.Action, sc.Kind, sc.AtUTC, sc.DaysMask, sc.TimeOfDay, sc.TZ,
|
||||
nextStr, sc.CreatedBy, now())
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetSchedule(id)
|
||||
}
|
||||
|
||||
func (s *Store) GetSchedule(id int64) (Schedule, error) {
|
||||
sc, err := scanSchedule(s.DB.QueryRow(scheduleSelect+` WHERE sc.id = ?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return sc, errors.New("schedule not found")
|
||||
}
|
||||
return sc, err
|
||||
}
|
||||
|
||||
func (s *Store) ListSchedules(streamID int64) ([]Schedule, error) {
|
||||
q := scheduleSelect
|
||||
var args []any
|
||||
if streamID > 0 {
|
||||
q += ` WHERE sc.stream_id = ?`
|
||||
args = append(args, streamID)
|
||||
}
|
||||
q += ` ORDER BY sc.next_fire_at = '', sc.next_fire_at, sc.id`
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpcomingSchedules lists the soonest pending occurrences across all streams.
|
||||
func (s *Store) UpcomingSchedules(limit int) ([]Schedule, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at >= ?
|
||||
ORDER BY sc.next_fire_at LIMIT ?`, now(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DueSchedules returns enabled schedules whose moment has arrived.
|
||||
func (s *Store) DueSchedules(at time.Time) ([]Schedule, error) {
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at <= ?
|
||||
ORDER BY sc.next_fire_at`, at.UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PendingPreroll returns start schedules firing within the lead time, whose
|
||||
// pre-roll has not been requested yet.
|
||||
func (s *Store) PendingPreroll(at time.Time, lead time.Duration) ([]Schedule, error) {
|
||||
until := at.Add(lead).UTC().Format(time.RFC3339)
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.action = 'start' AND sc.next_fire_at <> ''
|
||||
AND sc.next_fire_at <= ? AND sc.next_fire_at > ?
|
||||
AND sc.preroll_fired_for <> sc.next_fire_at
|
||||
ORDER BY sc.next_fire_at`, until, at.UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MarkPrerolled records that a pre-roll was requested for this occurrence.
|
||||
func (s *Store) MarkPrerolled(id int64, forTime string) error {
|
||||
_, err := s.DB.Exec(`UPDATE schedules SET preroll_fired_for=? WHERE id=?`, forTime, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkFired advances a schedule after it has run. A "once" schedule is
|
||||
// disabled, since its moment has passed.
|
||||
func (s *Store) MarkFired(sc Schedule, at time.Time) error {
|
||||
next := sc.NextFire(at.Add(time.Second))
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
enabled := 1
|
||||
if sc.Kind == KindOnce || nextStr == "" {
|
||||
enabled = 0
|
||||
}
|
||||
_, err := s.DB.Exec(`
|
||||
UPDATE schedules SET last_fired_at=?, next_fire_at=?, enabled=? WHERE id=?`,
|
||||
at.UTC().Format(time.RFC3339), nextStr, enabled, sc.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// PatchSchedule updates a schedule and recomputes when it next fires.
|
||||
func (s *Store) PatchSchedule(id int64, in Schedule, setEnabled *bool) (Schedule, error) {
|
||||
cur, err := s.GetSchedule(id)
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
if in.Action != "" {
|
||||
cur.Action = in.Action
|
||||
}
|
||||
if in.Kind != "" {
|
||||
cur.Kind = in.Kind
|
||||
}
|
||||
if in.AtUTC != "" {
|
||||
cur.AtUTC = in.AtUTC
|
||||
}
|
||||
if in.TimeOfDay != "" {
|
||||
cur.TimeOfDay = in.TimeOfDay
|
||||
}
|
||||
if in.TZ != "" {
|
||||
cur.TZ = in.TZ
|
||||
}
|
||||
if in.DaysMask != 0 {
|
||||
cur.DaysMask = in.DaysMask
|
||||
}
|
||||
if setEnabled != nil {
|
||||
cur.Enabled = *setEnabled
|
||||
}
|
||||
if err := cur.Validate(); err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
next := cur.NextFire(time.Now().UTC())
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
en := 0
|
||||
if cur.Enabled {
|
||||
en = 1
|
||||
}
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE schedules SET action=?, kind=?, at_utc=?, days_mask=?, time_of_day=?, tz=?,
|
||||
enabled=?, next_fire_at=?, preroll_fired_for='' WHERE id=?`,
|
||||
cur.Action, cur.Kind, cur.AtUTC, cur.DaysMask, cur.TimeOfDay, cur.TZ,
|
||||
en, nextStr, id)
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
return s.GetSchedule(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSchedule(id int64) error {
|
||||
res, err := s.DB.Exec(`DELETE FROM schedules WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return errors.New("schedule not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecomputeNextFire refreshes next_fire_at for every enabled schedule, called
|
||||
// at startup so a server that was down over an occurrence does not fire a
|
||||
// stale one and then sit with a past timestamp.
|
||||
func (s *Store) RecomputeNextFire() error {
|
||||
list, err := s.ListSchedules(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
for _, sc := range list {
|
||||
if !sc.Enabled {
|
||||
continue
|
||||
}
|
||||
next := sc.NextFire(nowT)
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
enabled := 1
|
||||
if nextStr == "" {
|
||||
// A "once" schedule whose moment has passed is spent.
|
||||
enabled = 0
|
||||
}
|
||||
_, _ = s.DB.Exec(`UPDATE schedules SET next_fire_at=?, enabled=? WHERE id=?`,
|
||||
nextStr, enabled, sc.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WeekdayMask builds a days_mask from weekday numbers (0 = Sunday).
|
||||
func WeekdayMask(days ...int) int {
|
||||
m := 0
|
||||
for _, d := range days {
|
||||
if d >= 0 && d <= 6 {
|
||||
m |= 1 << uint(d)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// DaysLabel renders a mask as "Mon,Tue".
|
||||
func DaysLabel(mask int) string {
|
||||
names := []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
|
||||
var out []string
|
||||
for i := range names {
|
||||
if mask&(1<<uint(i)) != 0 {
|
||||
out = append(out, names[i])
|
||||
}
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
370
apps/streamd/internal/db/schedules_test.go
Normal file
370
apps/streamd/internal/db/schedules_test.go
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "time/tzdata"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestScheduleValidate(t *testing.T) {
|
||||
bad := []Schedule{
|
||||
{Action: "burn", Kind: KindOnce, AtUTC: "2026-01-01T10:00:00Z"},
|
||||
{Action: ActionStart, Kind: "hourly"},
|
||||
{Action: ActionStart, Kind: KindOnce, AtUTC: "not a time"},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "25:00", DaysMask: 2},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 0},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 2, TZ: "Mars/Olympus"},
|
||||
}
|
||||
for _, sc := range bad {
|
||||
if err := sc.Validate(); err == nil {
|
||||
t.Errorf("expected %+v to be rejected", sc)
|
||||
}
|
||||
}
|
||||
good := Schedule{Action: " START ", Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(2), TZ: "Europe/Dublin"}
|
||||
if err := good.Validate(); err != nil {
|
||||
t.Fatalf("valid schedule rejected: %v", err)
|
||||
}
|
||||
if good.Action != ActionStart {
|
||||
t.Errorf("action should be normalised, got %q", good.Action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseScheduleTimeAcceptsLocalWallClock(t *testing.T) {
|
||||
// A person types a local time; it must be read in the stream's zone, not
|
||||
// as UTC, or the event fires at the wrong hour.
|
||||
got, err := ParseScheduleTime("2026-07-01 19:00", "Europe/Dublin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Dublin is UTC+1 in July.
|
||||
if got.UTC().Hour() != 18 {
|
||||
t.Errorf("19:00 Dublin in July should be 18:00 UTC, got %s", got.UTC())
|
||||
}
|
||||
if _, err := ParseScheduleTime("", "UTC"); err == nil {
|
||||
t.Error("an empty time should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireOnce(t *testing.T) {
|
||||
at := time.Date(2026, 3, 10, 19, 0, 0, 0, time.UTC)
|
||||
sc := Schedule{Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339), Enabled: true}
|
||||
|
||||
before := at.Add(-time.Hour)
|
||||
if got := sc.NextFire(before); !got.Equal(at) {
|
||||
t.Errorf("NextFire = %s, want %s", got, at)
|
||||
}
|
||||
// Once the moment has passed there is no next occurrence.
|
||||
if got := sc.NextFire(at.Add(time.Second)); !got.IsZero() {
|
||||
t.Errorf("a spent once-schedule should not fire again, got %s", got)
|
||||
}
|
||||
// A disabled schedule never fires.
|
||||
sc.Enabled = false
|
||||
if got := sc.NextFire(before); !got.IsZero() {
|
||||
t.Errorf("a disabled schedule should not fire, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireWeekly(t *testing.T) {
|
||||
// Tuesdays at 19:00 UTC.
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(int(time.Tuesday)), TZ: "UTC", Enabled: true,
|
||||
}
|
||||
// A Monday.
|
||||
mon := time.Date(2026, 3, 9, 12, 0, 0, 0, time.UTC)
|
||||
got := sc.NextFire(mon)
|
||||
if got.Weekday() != time.Tuesday || got.Hour() != 19 {
|
||||
t.Errorf("next fire = %s, want Tuesday 19:00", got)
|
||||
}
|
||||
if d := got.Sub(mon); d < 0 || d > 48*time.Hour {
|
||||
t.Errorf("next fire %s is not within two days of %s", got, mon)
|
||||
}
|
||||
// From Tuesday 19:00:01 it must roll to the following week, not fire
|
||||
// again the same evening.
|
||||
justAfter := time.Date(2026, 3, 10, 19, 0, 1, 0, time.UTC)
|
||||
next := sc.NextFire(justAfter)
|
||||
if next.Weekday() != time.Tuesday {
|
||||
t.Errorf("next = %s, want the following Tuesday", next)
|
||||
}
|
||||
if next.Sub(justAfter) < 6*24*time.Hour {
|
||||
t.Errorf("next = %s, should be about a week after %s", next, justAfter)
|
||||
}
|
||||
}
|
||||
|
||||
// A weekly event is a wall-clock commitment: a 19:00 meeting stays at 19:00
|
||||
// local across a DST change. Storing a fixed UTC offset would drift an hour.
|
||||
func TestNextFireWeeklyAcrossDST(t *testing.T) {
|
||||
const zone = "Europe/Dublin"
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
t.Skipf("zone data unavailable: %v", err)
|
||||
}
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(int(time.Sunday)), TZ: zone, Enabled: true,
|
||||
}
|
||||
// Ireland springs forward at 01:00 on Sunday 29 March 2026. Starting on
|
||||
// the 21st puts the first occurrence on 22 March (still GMT) and the
|
||||
// second on 29 March (already IST), so the pair straddles the change.
|
||||
beforeChange := time.Date(2026, 3, 21, 12, 0, 0, 0, loc)
|
||||
first := sc.NextFire(beforeChange)
|
||||
afterChange := sc.NextFire(first.Add(time.Second))
|
||||
if first.In(loc).Day() != 22 || afterChange.In(loc).Day() != 29 {
|
||||
t.Fatalf("test set-up is wrong: occurrences are %s and %s, want 22 and 29 March",
|
||||
first.In(loc), afterChange.In(loc))
|
||||
}
|
||||
|
||||
// Both occurrences must read 19:00 in local time...
|
||||
for _, got := range []time.Time{first, afterChange} {
|
||||
local := got.In(loc)
|
||||
if local.Hour() != 19 || local.Minute() != 0 {
|
||||
t.Errorf("occurrence %s is %02d:%02d local, want 19:00", got, local.Hour(), local.Minute())
|
||||
}
|
||||
}
|
||||
// ...which means their UTC hours differ across the change. That
|
||||
// difference is the proof the zone is being honoured.
|
||||
if first.UTC().Hour() == afterChange.UTC().Hour() {
|
||||
t.Errorf("UTC hour did not shift across the DST boundary (%s vs %s) — "+
|
||||
"the schedule is drifting rather than tracking local time",
|
||||
first.UTC(), afterChange.UTC())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireWeeklyMultipleDays(t *testing.T) {
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "08:30",
|
||||
DaysMask: WeekdayMask(int(time.Monday), int(time.Wednesday), int(time.Friday)),
|
||||
TZ: "UTC", Enabled: true,
|
||||
}
|
||||
// From Monday 09:00, the next is Wednesday.
|
||||
from := time.Date(2026, 3, 9, 9, 0, 0, 0, time.UTC)
|
||||
got := sc.NextFire(from)
|
||||
if got.Weekday() != time.Wednesday || got.Hour() != 8 || got.Minute() != 30 {
|
||||
t.Errorf("got %s, want Wednesday 08:30", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleCRUDAndFiring(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, err := store.CreateStream(CreateStream{Name: "council", MPD: "https://x/a.mpd"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A one-off two minutes out.
|
||||
at := time.Now().UTC().Add(2 * time.Minute).Truncate(time.Second)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339), CreatedBy: "tester",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sc.NextFireAt == "" {
|
||||
t.Error("a new schedule should have a next_fire_at")
|
||||
}
|
||||
if sc.StreamName != "council" {
|
||||
t.Errorf("stream name = %q", sc.StreamName)
|
||||
}
|
||||
|
||||
// Not due yet.
|
||||
if due, err := store.DueSchedules(time.Now().UTC()); err != nil || len(due) != 0 {
|
||||
t.Fatalf("should not be due yet: %v %d", err, len(due))
|
||||
}
|
||||
// Due once its moment arrives.
|
||||
due, err := store.DueSchedules(at.Add(time.Second))
|
||||
if err != nil || len(due) != 1 {
|
||||
t.Fatalf("want 1 due, got %d (%v)", len(due), err)
|
||||
}
|
||||
|
||||
// Firing a once-schedule spends it.
|
||||
if err := store.MarkFired(due[0], at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := store.GetSchedule(sc.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Enabled {
|
||||
t.Error("a fired once-schedule should be disabled")
|
||||
}
|
||||
if after.LastFiredAt == "" {
|
||||
t.Error("last_fired_at should be set")
|
||||
}
|
||||
if later, _ := store.DueSchedules(at.Add(time.Hour)); len(later) != 0 {
|
||||
t.Error("a spent schedule must not fire twice")
|
||||
}
|
||||
|
||||
// A weekly schedule keeps going.
|
||||
weekly, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
|
||||
TimeOfDay: "19:00", DaysMask: WeekdayMask(0, 1, 2, 3, 4, 5, 6), TZ: "UTC",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstNext := weekly.NextFireAt
|
||||
firedAt, err := time.Parse(time.RFC3339, firstNext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.MarkFired(weekly, firedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, _ := store.GetSchedule(weekly.ID)
|
||||
if !again.Enabled {
|
||||
t.Error("a weekly schedule should stay enabled after firing")
|
||||
}
|
||||
if again.NextFireAt == "" || again.NextFireAt == firstNext {
|
||||
t.Errorf("weekly next_fire_at should have advanced, was %q now %q", firstNext, again.NextFireAt)
|
||||
}
|
||||
|
||||
// Listing and deleting.
|
||||
list, err := store.ListSchedules(st.ID)
|
||||
if err != nil || len(list) != 2 {
|
||||
t.Fatalf("want 2 schedules, got %d (%v)", len(list), err)
|
||||
}
|
||||
if err := store.DeleteSchedule(weekly.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.DeleteSchedule(weekly.ID); err == nil {
|
||||
t.Error("deleting twice should report not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulePrerollOnlyOncePerOccurrence(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "match", MPD: "https://x/a.mpd"})
|
||||
at := time.Now().UTC().Add(2 * time.Minute)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
pending, err := store.PendingPreroll(nowT, 5*time.Minute)
|
||||
if err != nil || len(pending) != 1 {
|
||||
t.Fatalf("want 1 pre-roll pending, got %d (%v)", len(pending), err)
|
||||
}
|
||||
if err := store.MarkPrerolled(sc.ID, pending[0].NextFireAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Already requested: must not ask again every tick.
|
||||
pending, err = store.PendingPreroll(nowT, 5*time.Minute)
|
||||
if err != nil || len(pending) != 0 {
|
||||
t.Fatalf("pre-roll should not repeat, got %d (%v)", len(pending), err)
|
||||
}
|
||||
|
||||
// A stop schedule never pre-rolls: there is nothing to prepare.
|
||||
_, err = store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStop, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, _ = store.PendingPreroll(nowT, 5*time.Minute)
|
||||
for _, p := range pending {
|
||||
if p.Action == ActionStop {
|
||||
t.Error("a stop schedule should not be pre-rolled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A server that was down over an occurrence must not fire it late.
|
||||
func TestRecomputeNextFireDropsMissedOnce(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "gone", MPD: "https://x/a.mpd"})
|
||||
past := time.Now().UTC().Add(-2 * time.Hour)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: past.Add(time.Hour).Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
// CreateSchedule accepts a past time; NextFire just yields nothing.
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.RecomputeNextFire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := store.GetSchedule(sc.ID)
|
||||
if got.Enabled {
|
||||
t.Error("a missed once-schedule should be disabled, not fired late")
|
||||
}
|
||||
if due, _ := store.DueSchedules(time.Now().UTC()); len(due) != 0 {
|
||||
t.Error("a missed schedule must not be due")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpcomingSchedulesOrdering(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "events", MPD: "https://x/a.mpd"})
|
||||
far := time.Now().UTC().Add(3 * time.Hour)
|
||||
near := time.Now().UTC().Add(10 * time.Minute)
|
||||
if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
|
||||
Kind: KindOnce, AtUTC: far.Format(time.RFC3339)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
|
||||
Kind: KindOnce, AtUTC: near.Format(time.RFC3339)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
up, err := store.UpcomingSchedules(10)
|
||||
if err != nil || len(up) != 2 {
|
||||
t.Fatalf("want 2 upcoming, got %d (%v)", len(up), err)
|
||||
}
|
||||
if up[0].NextFireAt > up[1].NextFireAt {
|
||||
t.Errorf("upcoming should be soonest first, got %q then %q", up[0].NextFireAt, up[1].NextFireAt)
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting a stream must take its schedules with it, or the scheduler would
|
||||
// keep trying to start something that no longer exists.
|
||||
func TestSchedulesCascadeOnStreamDelete(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "temp", MPD: "https://x/a.mpd"})
|
||||
if _, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
|
||||
TimeOfDay: "19:00", DaysMask: WeekdayMask(1), TZ: "UTC",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.DeleteStream(st.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := store.ListSchedules(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(list) != 0 {
|
||||
t.Errorf("schedules outlived their stream: %+v", list)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaysLabel(t *testing.T) {
|
||||
if got := DaysLabel(WeekdayMask(1, 3, 5)); got != "Mon,Wed,Fri" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
if got := DaysLabel(0); got != "" {
|
||||
t.Errorf("empty mask = %q", got)
|
||||
}
|
||||
if got := DaysLabel(WeekdayMask(0, 6)); got != "Sun,Sat" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
}
|
||||
179
apps/streamd/internal/db/settings.go
Normal file
179
apps/streamd/internal/db/settings.go
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Setting keys. These are the installation-wide defaults that sit at the
|
||||
// bottom of the resolution chain: stream row -> app module -> these -> the
|
||||
// compiled-in defaults.
|
||||
const (
|
||||
SettingHLSTime = "hls_time"
|
||||
SettingHLSListSize = "hls_list_size"
|
||||
SettingLiveWait = "live_wait"
|
||||
SettingTSReadyBytes = "ts_ready_bytes"
|
||||
SettingIdleTimeoutS = "idle_timeout_s"
|
||||
SettingDefaultOutputs = "default_outputs"
|
||||
SettingOnDemand = "default_on_demand"
|
||||
)
|
||||
|
||||
func (s *Store) migrateSettings() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL DEFAULT ''
|
||||
);`)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetSettings returns every stored setting.
|
||||
func (s *Store) GetSettings() (map[string]string, error) {
|
||||
rows, err := s.DB.Query(`SELECT key, value FROM settings`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[k] = v
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetSettings upserts the given keys in one transaction. A key with an empty
|
||||
// value is deleted, which returns it to the built-in default.
|
||||
func (s *Store) SetSettings(in map[string]string) error {
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, v := range in {
|
||||
k = strings.TrimSpace(k)
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(v) == "" {
|
||||
if _, err := tx.Exec(`DELETE FROM settings WHERE key=?`, k); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO settings(key,value,updated_at) VALUES(?,?,?)
|
||||
ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at`,
|
||||
k, v, now()); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// PackagerSettings are the knobs that shape the ffmpeg command line. A zero
|
||||
// field means "not set at this level", so the next level down applies.
|
||||
type PackagerSettings struct {
|
||||
HLSTime int `json:"hls_time,omitempty"`
|
||||
HLSListSize int `json:"hls_list_size,omitempty"`
|
||||
LiveWait int `json:"live_wait,omitempty"`
|
||||
TSReadyBytes int `json:"ts_ready_bytes,omitempty"`
|
||||
}
|
||||
|
||||
// ParsePackagerSettings reads a stream's settings_json. Unparseable JSON
|
||||
// yields the zero value, which simply defers to the levels below.
|
||||
func ParsePackagerSettings(raw string) PackagerSettings {
|
||||
var p PackagerSettings
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "null" {
|
||||
return p
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
return p.sane()
|
||||
}
|
||||
|
||||
// sane drops nonsense values rather than passing them to ffmpeg, where a
|
||||
// zero segment duration would produce an unplayable stream.
|
||||
func (p PackagerSettings) sane() PackagerSettings {
|
||||
if p.HLSTime < 1 || p.HLSTime > 30 {
|
||||
p.HLSTime = 0
|
||||
}
|
||||
if p.HLSListSize < 1 || p.HLSListSize > 500 {
|
||||
p.HLSListSize = 0
|
||||
}
|
||||
if p.LiveWait < 0 || p.LiveWait > 120 {
|
||||
p.LiveWait = 0
|
||||
}
|
||||
if p.TSReadyBytes < 0 || p.TSReadyBytes > (256<<20) {
|
||||
p.TSReadyBytes = 0
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// GlobalPackagerSettings reads the installation-wide packager defaults.
|
||||
func (s *Store) GlobalPackagerSettings() PackagerSettings {
|
||||
vals, err := s.GetSettings()
|
||||
if err != nil {
|
||||
return PackagerSettings{}
|
||||
}
|
||||
atoi := func(k string) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(vals[k]))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
return PackagerSettings{
|
||||
HLSTime: atoi(SettingHLSTime),
|
||||
HLSListSize: atoi(SettingHLSListSize),
|
||||
LiveWait: atoi(SettingLiveWait),
|
||||
TSReadyBytes: atoi(SettingTSReadyBytes),
|
||||
}.sane()
|
||||
}
|
||||
|
||||
// settingTruthy accepts the spellings operators realistically type into the
|
||||
// settings form for boolean defaults.
|
||||
func settingTruthy(v string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ApplyCreateDefaults fills CreateStream fields that the caller left unset
|
||||
// from the installation-wide settings table. Explicit request fields win.
|
||||
// Packager knobs (hls_time etc.) are resolved at start time, not at create.
|
||||
func (s *Store) ApplyCreateDefaults(in *CreateStream) {
|
||||
if in == nil {
|
||||
return
|
||||
}
|
||||
vals, err := s.GetSettings()
|
||||
if err != nil || len(vals) == 0 {
|
||||
return
|
||||
}
|
||||
if in.OnDemand == nil {
|
||||
if v, ok := vals[SettingOnDemand]; ok && strings.TrimSpace(v) != "" {
|
||||
b := settingTruthy(v)
|
||||
in.OnDemand = &b
|
||||
}
|
||||
}
|
||||
if in.IdleTimeoutS == nil {
|
||||
if v := strings.TrimSpace(vals[SettingIdleTimeoutS]); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
in.IdleTimeoutS = &n
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(in.Outputs) == 0 && strings.TrimSpace(in.OutputsJSON) == "" {
|
||||
if v := strings.TrimSpace(vals[SettingDefaultOutputs]); v != "" {
|
||||
in.OutputsJSON = v
|
||||
}
|
||||
}
|
||||
}
|
||||
57
apps/streamd/internal/db/settings_test.go
Normal file
57
apps/streamd/internal/db/settings_test.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplyCreateDefaultsFillsUnsetFields(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
if err := s.SetSettings(map[string]string{
|
||||
SettingOnDemand: "true",
|
||||
SettingIdleTimeoutS: "120",
|
||||
SettingDefaultOutputs: `[{"id":"hls","label":"HLS","format":"hls","enabled":true}]`,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
in := CreateStream{Name: "news"}
|
||||
s.ApplyCreateDefaults(&in)
|
||||
if in.OnDemand == nil || !*in.OnDemand {
|
||||
t.Fatalf("expected on_demand=true from settings, got %+v", in.OnDemand)
|
||||
}
|
||||
if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 120 {
|
||||
t.Fatalf("expected idle_timeout_s=120, got %+v", in.IdleTimeoutS)
|
||||
}
|
||||
if in.OutputsJSON == "" {
|
||||
t.Fatal("expected default_outputs JSON to be copied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCreateDefaultsDoesNotOverrideExplicit(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
_ = s.SetSettings(map[string]string{
|
||||
SettingOnDemand: "true",
|
||||
SettingIdleTimeoutS: "120",
|
||||
})
|
||||
off := false
|
||||
idle := 600
|
||||
in := CreateStream{Name: "news", OnDemand: &off, IdleTimeoutS: &idle}
|
||||
s.ApplyCreateDefaults(&in)
|
||||
if in.OnDemand == nil || *in.OnDemand {
|
||||
t.Fatal("explicit on_demand=false must win over settings")
|
||||
}
|
||||
if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 600 {
|
||||
t.Fatal("explicit idle_timeout_s must win over settings")
|
||||
}
|
||||
}
|
||||
170
apps/streamd/internal/db/stream_test.go
Normal file
170
apps/streamd/internal/db/stream_test.go
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
const (
|
||||
testKID = "0123456789abcdef0123456789abcdef"
|
||||
testKey = "fedcba9876543210fedcba9876543210"
|
||||
)
|
||||
|
||||
var goodKey = testKID + ":" + testKey
|
||||
|
||||
// withDerived runs the same derivation scanStream does, so these tests
|
||||
// exercise exactly what the API serialises.
|
||||
func withDerived(st Stream) Stream {
|
||||
st.fillDerived()
|
||||
return st
|
||||
}
|
||||
|
||||
func TestNeedsCaptureDisabledStreamNever(t *testing.T) {
|
||||
st := withDerived(Stream{Enabled: false, MPD: "", Health: "down"})
|
||||
if st.NeedsCapture {
|
||||
t.Error("a disabled stream must never be queued for capture")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureMissingManifest(t *testing.T) {
|
||||
st := withDerived(Stream{Enabled: true, MPD: "", Health: "ok"})
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a stream with no manifest needs a capture")
|
||||
}
|
||||
}
|
||||
|
||||
// The regression the key redaction would otherwise cause: a healthy encrypted
|
||||
// stream must not look like it needs a capture just because the API response
|
||||
// no longer carries the key. The server decides, using the derived flags.
|
||||
func TestNeedsCaptureHealthyDRMStream(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/manifest.mpd", Key: goodKey,
|
||||
Health: "ok", PlaylistAgeS: 2,
|
||||
})
|
||||
if !st.DRMRequired {
|
||||
t.Error("a stream holding a key should resolve to DRM required")
|
||||
}
|
||||
if !st.KeyValid {
|
||||
t.Error("a well-formed key should be valid")
|
||||
}
|
||||
if st.NeedsCapture {
|
||||
t.Error("a healthy DRM stream must not be queued for capture")
|
||||
}
|
||||
// And after redaction the verdict is unchanged and the key is gone.
|
||||
red := st.Redacted()
|
||||
if red.Key != "" || red.HeadersJSON != "" || red.Proxy != "" {
|
||||
t.Errorf("Redacted left secrets behind: %+v", red)
|
||||
}
|
||||
if red.NeedsCapture != st.NeedsCapture || red.HasKey != true || red.KeyValid != true {
|
||||
t.Error("redaction must preserve the derived flags")
|
||||
}
|
||||
}
|
||||
|
||||
// A clear stream legitimately has no keys. streamd supports clear content, so
|
||||
// this must not spin the capture queue forever — the bug the old
|
||||
// "key == empty means capture" rule caused.
|
||||
func TestNeedsCaptureClearStreamWithNoKey(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/manifest.mpd", Key: "",
|
||||
DRMMode: DRMNo, Health: "ok", PlaylistAgeS: 2,
|
||||
})
|
||||
if st.DRMRequired {
|
||||
t.Error("drm_mode=no must resolve to DRM not required")
|
||||
}
|
||||
if st.NeedsCapture {
|
||||
t.Error("a healthy clear stream must not be queued for capture")
|
||||
}
|
||||
}
|
||||
|
||||
// In auto mode a stream that has never held a key is assumed clear.
|
||||
func TestNeedsCaptureAutoModeInfersFromKey(t *testing.T) {
|
||||
clear := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Health: "ok"})
|
||||
if clear.DRMRequired {
|
||||
t.Error("auto with no key should infer clear")
|
||||
}
|
||||
if clear.DRMMode != DRMAuto {
|
||||
t.Errorf("auto should be normalised to %q, got %q", DRMAuto, clear.DRMMode)
|
||||
}
|
||||
encrypted := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Key: goodKey, Health: "ok"})
|
||||
if !encrypted.DRMRequired {
|
||||
t.Error("auto with a key should infer DRM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureInvalidKey(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: "garbage",
|
||||
DRMMode: DRMYes, Health: "ok",
|
||||
})
|
||||
if st.KeyValid {
|
||||
t.Error("garbage should not be a valid key")
|
||||
}
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a DRM stream with an unusable key needs a capture")
|
||||
}
|
||||
}
|
||||
|
||||
// An on-demand stream sitting idle is doing its job, not failing. Treating
|
||||
// "stopped" as broken would queue a capture for every idle channel.
|
||||
func TestNeedsCaptureOnDemandIdleIsNotBroken(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
OnDemand: true, Health: "stopped",
|
||||
})
|
||||
if st.NeedsCapture {
|
||||
t.Error("an idle on-demand stream must not be queued for capture")
|
||||
}
|
||||
// The same stream that is not on-demand is genuinely down.
|
||||
always := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
OnDemand: false, Health: "stopped",
|
||||
})
|
||||
if !always.NeedsCapture {
|
||||
t.Error("an always-on stream that is stopped should be refreshed")
|
||||
}
|
||||
}
|
||||
|
||||
// A stream still inside its bootstrap window must be left alone: capturing
|
||||
// would POST credentials and restart it, which is a slow restart loop.
|
||||
func TestNeedsCaptureStartingRespectsBootstrapGrace(t *testing.T) {
|
||||
young := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "starting", UptimeS: 10,
|
||||
})
|
||||
if young.NeedsCapture {
|
||||
t.Error("a stream still starting up must not be restarted by a capture")
|
||||
}
|
||||
stuck := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "starting", UptimeS: bootstrapGraceS + 1,
|
||||
})
|
||||
if !stuck.NeedsCapture {
|
||||
t.Error("a stream stuck in starting past the grace window needs help")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureStalePlaylist(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "ok", PlaylistAgeS: 120,
|
||||
})
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a stale playlist should trigger a refresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDerivedHeaderAndProxyFlags(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
headers string
|
||||
want bool
|
||||
}{
|
||||
{"", false}, {"{}", false}, {"null", false},
|
||||
{`{"Cookie":"x"}`, true},
|
||||
} {
|
||||
st := withDerived(Stream{HeadersJSON: c.headers})
|
||||
if st.HasHeaders != c.want {
|
||||
t.Errorf("HasHeaders(%q) = %v want %v", c.headers, st.HasHeaders, c.want)
|
||||
}
|
||||
}
|
||||
st := withDerived(Stream{Proxy: "socks5://127.0.0.1:1080"})
|
||||
if !st.HasProxy {
|
||||
t.Error("a configured proxy should set HasProxy")
|
||||
}
|
||||
}
|
||||
|
|
@ -6,9 +6,14 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
// SourceVariantID is the id of the pass-through rung: the source copy
|
||||
// published at /hls/<name>/index.m3u8.
|
||||
const SourceVariantID = "fhd"
|
||||
|
||||
// VariantSpec is one configured output ladder rung for a stream.
|
||||
// Height 0 (or id "fhd") is the source copy published at /hls/<name>/index.m3u8.
|
||||
// Other heights are ffmpeg-scaled sibling playlists at /hls/<name>-<id>/index.m3u8.
|
||||
// An AudioOnly rung is also height 0 but is a separate, re-encoded rung.
|
||||
type VariantSpec struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
|
|
@ -16,6 +21,10 @@ type VariantSpec struct {
|
|||
Height int `json:"height"`
|
||||
VideoBitrate string `json:"video_bitrate,omitempty"`
|
||||
AudioBitrate string `json:"audio_bitrate,omitempty"`
|
||||
// AudioOnly drops video entirely. It is checked before the height-zero
|
||||
// source-rung rule, because an audio rung is height zero too and would
|
||||
// otherwise be rewritten into the source copy.
|
||||
AudioOnly bool `json:"audio_only,omitempty"`
|
||||
}
|
||||
|
||||
// VariantStatus is VariantSpec plus live play path / health for the API/UI.
|
||||
|
|
@ -26,12 +35,19 @@ type VariantStatus struct {
|
|||
PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultVariants returns the FHD + optional HD/SD ladder with only FHD enabled.
|
||||
// IsSource reports whether this rung is the pass-through copy of the input.
|
||||
func (v VariantSpec) IsSource() bool {
|
||||
return !v.AudioOnly && v.Height <= 0
|
||||
}
|
||||
|
||||
// DefaultVariants returns the FHD + optional HD/SD/audio ladder with only FHD
|
||||
// enabled.
|
||||
func DefaultVariants() []VariantSpec {
|
||||
return []VariantSpec{
|
||||
{ID: "fhd", Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: "hd", Label: "HD", Enabled: false, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"},
|
||||
{ID: "sd", Label: "SD", Enabled: false, Height: 480, VideoBitrate: "1200k", AudioBitrate: "96k"},
|
||||
{ID: "audio", Label: "Audio", Enabled: false, AudioOnly: true, AudioBitrate: "96k"},
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -48,16 +64,37 @@ func ParseVariantsJSON(raw string) []VariantSpec {
|
|||
return NormalizeVariants(list)
|
||||
}
|
||||
|
||||
// NormalizeVariants fills ids/labels/bitrates and ensures an FHD/source entry exists.
|
||||
// NormalizeVariants fills ids/labels/bitrates and ensures a source entry exists.
|
||||
func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
||||
out := make([]VariantSpec, 0, len(in))
|
||||
seen := map[string]bool{}
|
||||
hasSource := false
|
||||
for _, v := range in {
|
||||
v.ID = slug(v.ID)
|
||||
// An audio rung is resolved first: it is height zero like the source
|
||||
// copy, and the source rule below would otherwise swallow it.
|
||||
if v.AudioOnly {
|
||||
v.Height = 0
|
||||
if v.ID == "" || v.ID == SourceVariantID {
|
||||
v.ID = "audio"
|
||||
}
|
||||
if v.Label == "" {
|
||||
v.Label = "Audio"
|
||||
}
|
||||
if v.AudioBitrate == "" {
|
||||
v.AudioBitrate = "96k"
|
||||
}
|
||||
v.VideoBitrate = ""
|
||||
if seen[v.ID] {
|
||||
continue
|
||||
}
|
||||
seen[v.ID] = true
|
||||
out = append(out, v)
|
||||
continue
|
||||
}
|
||||
if v.ID == "" {
|
||||
if v.Height <= 0 {
|
||||
v.ID = "fhd"
|
||||
v.ID = SourceVariantID
|
||||
} else {
|
||||
v.ID = fmt.Sprintf("%dp", v.Height)
|
||||
}
|
||||
|
|
@ -74,8 +111,8 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
|||
}
|
||||
if v.Height == 0 {
|
||||
hasSource = true
|
||||
v.ID = "fhd"
|
||||
if v.Label == "" || strings.EqualFold(v.Label, "fhd") {
|
||||
v.ID = SourceVariantID
|
||||
if v.Label == "" || strings.EqualFold(v.Label, SourceVariantID) {
|
||||
v.Label = "FHD"
|
||||
}
|
||||
v.Enabled = true // source copy always published when the stream runs
|
||||
|
|
@ -103,7 +140,7 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
|||
out = append(out, v)
|
||||
}
|
||||
if !hasSource {
|
||||
out = append([]VariantSpec{{ID: "fhd", Label: "FHD", Enabled: true, Height: 0}}, out...)
|
||||
out = append([]VariantSpec{{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0}}, out...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -121,19 +158,71 @@ func EncodeVariantsJSON(list []VariantSpec) (string, error) {
|
|||
// VariantPlayPath is the HLS URL path for one variant of stream name.
|
||||
func VariantPlayPath(streamName, variantID string, height int) string {
|
||||
variantID = slug(variantID)
|
||||
if height <= 0 || variantID == "" || variantID == "fhd" {
|
||||
if height <= 0 || variantID == "" || variantID == SourceVariantID {
|
||||
return "/hls/" + streamName + "/index.m3u8"
|
||||
}
|
||||
return "/hls/" + streamName + "-" + variantID + "/index.m3u8"
|
||||
}
|
||||
|
||||
// ScaledVariants returns enabled non-source (transcode) variants.
|
||||
// ScaledVariants returns enabled rungs that need their own encoder: every
|
||||
// non-source rung, including audio-only.
|
||||
func ScaledVariants(list []VariantSpec) []VariantSpec {
|
||||
var out []VariantSpec
|
||||
for _, v := range list {
|
||||
if v.Enabled && v.Height > 0 {
|
||||
if v.Enabled && !v.IsSource() {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// EnabledVariants returns every enabled rung, source included.
|
||||
func EnabledVariants(list []VariantSpec) []VariantSpec {
|
||||
var out []VariantSpec
|
||||
for _, v := range list {
|
||||
if v.Enabled {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// VariantWidth estimates a rung's pixel width for the ABR master playlist.
|
||||
// The packager scales with scale=-2:<height>, so width follows the source
|
||||
// aspect; 16:9 is the right assumption for broadcast content and the only
|
||||
// thing available before the stream has been probed.
|
||||
func VariantWidth(height int) int {
|
||||
if height <= 0 {
|
||||
return 0
|
||||
}
|
||||
w := height * 16 / 9
|
||||
// H.264 needs even dimensions, which is what -2 in the scale filter gives.
|
||||
if w%2 == 1 {
|
||||
w++
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// BitrateBps parses an ffmpeg bitrate string such as "2800k" into bits per
|
||||
// second, for the BANDWIDTH attribute in the master playlist.
|
||||
func BitrateBps(s string) int {
|
||||
s = strings.TrimSpace(strings.ToLower(s))
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
mult := 1
|
||||
switch {
|
||||
case strings.HasSuffix(s, "k"):
|
||||
mult, s = 1000, strings.TrimSuffix(s, "k")
|
||||
case strings.HasSuffix(s, "m"):
|
||||
mult, s = 1000000, strings.TrimSuffix(s, "m")
|
||||
}
|
||||
n := 0
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return 0
|
||||
}
|
||||
n = n*10 + int(r-'0')
|
||||
}
|
||||
return n * mult
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,11 +22,296 @@ func TestNormalizeVariantsEnsuresFHD(t *testing.T) {
|
|||
|
||||
func TestParseVariantsJSONDefault(t *testing.T) {
|
||||
got := ParseVariantsJSON("")
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("default len=%d", len(got))
|
||||
// The default ladder offers the rungs but turns none of the encoding ones
|
||||
// on, so a new stream costs exactly one pass-through copy.
|
||||
if len(got) != len(DefaultVariants()) {
|
||||
t.Fatalf("default len=%d want %d", len(got), len(DefaultVariants()))
|
||||
}
|
||||
scaled := ScaledVariants(got)
|
||||
if len(scaled) != 0 {
|
||||
t.Fatalf("default scaled=%v", scaled)
|
||||
if scaled := ScaledVariants(got); len(scaled) != 0 {
|
||||
t.Fatalf("default should encode nothing, got %v", scaled)
|
||||
}
|
||||
enabled := EnabledVariants(got)
|
||||
if len(enabled) != 1 || !enabled[0].IsSource() {
|
||||
t.Fatalf("default should enable only the source rung, got %+v", enabled)
|
||||
}
|
||||
}
|
||||
|
||||
// An audio-only rung is height 0, exactly like the source copy. The source
|
||||
// rule must not swallow it, or enabling audio would silently overwrite the
|
||||
// pass-through rung.
|
||||
func TestAudioOnlyRungSurvivesNormalize(t *testing.T) {
|
||||
got := NormalizeVariants([]VariantSpec{
|
||||
{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: "audio", Label: "Audio", Enabled: true, AudioOnly: true},
|
||||
})
|
||||
var source, audio *VariantSpec
|
||||
for i := range got {
|
||||
switch {
|
||||
case got[i].AudioOnly:
|
||||
audio = &got[i]
|
||||
case got[i].IsSource():
|
||||
source = &got[i]
|
||||
}
|
||||
}
|
||||
if source == nil {
|
||||
t.Fatal("source rung disappeared")
|
||||
}
|
||||
if audio == nil {
|
||||
t.Fatal("audio rung was absorbed into the source rung")
|
||||
}
|
||||
if audio.ID == SourceVariantID {
|
||||
t.Errorf("audio rung must not take the source id, got %q", audio.ID)
|
||||
}
|
||||
if audio.VideoBitrate != "" {
|
||||
t.Errorf("audio rung should carry no video bitrate, got %q", audio.VideoBitrate)
|
||||
}
|
||||
if audio.AudioBitrate == "" {
|
||||
t.Error("audio rung should get a default audio bitrate")
|
||||
}
|
||||
// It needs its own encoder, so it must count as scaled.
|
||||
scaled := ScaledVariants(got)
|
||||
foundAudio := false
|
||||
for _, v := range scaled {
|
||||
if v.AudioOnly {
|
||||
foundAudio = true
|
||||
}
|
||||
}
|
||||
if !foundAudio {
|
||||
t.Error("audio rung should be in ScaledVariants (it needs an encoder)")
|
||||
}
|
||||
}
|
||||
|
||||
// An audio rung sent without an explicit id must not claim the source id.
|
||||
func TestAudioOnlyWithoutIDGetsOwnID(t *testing.T) {
|
||||
got := NormalizeVariants([]VariantSpec{{Enabled: true, AudioOnly: true}})
|
||||
var audio, source int
|
||||
for _, v := range got {
|
||||
if v.AudioOnly {
|
||||
audio++
|
||||
if v.ID != "audio" {
|
||||
t.Errorf("want id audio, got %q", v.ID)
|
||||
}
|
||||
}
|
||||
if v.IsSource() {
|
||||
source++
|
||||
}
|
||||
}
|
||||
if audio != 1 || source != 1 {
|
||||
t.Fatalf("want one audio and one source rung, got audio=%d source=%d (%+v)", audio, source, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantDirAndOutputPaths(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, id string
|
||||
height int
|
||||
audio bool
|
||||
format string
|
||||
want string
|
||||
}{
|
||||
// The original mpegts HLS URL must never move.
|
||||
{"rte-one", "fhd", 0, false, FormatHLS, "/hls/rte-one/index.m3u8"},
|
||||
{"rte-one", "hd", 720, false, FormatHLS, "/hls/rte-one-hd/index.m3u8"},
|
||||
{"rte-one", "fhd", 0, false, FormatCMAF, "/hls/rte-one/cmaf/index.m3u8"},
|
||||
{"rte-one", "hd", 720, false, FormatCMAF, "/hls/rte-one-hd/cmaf/index.m3u8"},
|
||||
{"rte-one", "fhd", 0, false, FormatDASH, "/hls/rte-one/dash/index.mpd"},
|
||||
{"rte-one", "fhd", 0, false, FormatTS, "/live/rte-one.ts"},
|
||||
{"rte-one", "hd", 720, false, FormatTS, "/live/rte-one-hd.ts"},
|
||||
{"rte-one", "audio", 0, true, FormatHLS, "/hls/rte-one-audio/index.m3u8"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := OutputPlayPath(c.name, c.id, c.height, c.audio, c.format); got != c.want {
|
||||
t.Errorf("OutputPlayPath(%s,%s,%d,%v,%s) = %q want %q",
|
||||
c.name, c.id, c.height, c.audio, c.format, got, c.want)
|
||||
}
|
||||
}
|
||||
// A stream name containing a dash must keep its own directory.
|
||||
if got := VariantDir("city-news", "fhd", 0, false); got != "city-news" {
|
||||
t.Errorf("source dir = %q", got)
|
||||
}
|
||||
if got := VariantDir("city-news", "hd", 720, false); got != "city-news-hd" {
|
||||
t.Errorf("variant dir = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultOutputsOnlyHLS(t *testing.T) {
|
||||
got := ParseOutputsJSON("")
|
||||
on := EnabledOutputs(got)
|
||||
if len(on) != 1 || on[0].Format != FormatHLS {
|
||||
t.Fatalf("default outputs should be mpegts HLS only, got %+v", on)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeOutputsKeepsFullSetAndAliases(t *testing.T) {
|
||||
// A client toggling DASH on by id alone should get the whole set back
|
||||
// with DASH enabled and HLS still present.
|
||||
got := NormalizeOutputs([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: true},
|
||||
{ID: "dash", Format: "mpd", Enabled: true},
|
||||
{ID: "bogus", Format: "quicktime", Enabled: true},
|
||||
})
|
||||
if len(got) != len(DefaultOutputs()) {
|
||||
t.Fatalf("want the full output set, got %d: %+v", len(got), got)
|
||||
}
|
||||
byFormat := map[string]OutputSpec{}
|
||||
for _, o := range got {
|
||||
byFormat[o.Format] = o
|
||||
}
|
||||
if !byFormat[FormatDASH].Enabled {
|
||||
t.Error("mpd alias should have enabled DASH")
|
||||
}
|
||||
if !byFormat[FormatHLS].Enabled {
|
||||
t.Error("HLS should still be enabled")
|
||||
}
|
||||
if byFormat[FormatCMAF].Enabled {
|
||||
t.Error("CMAF should have stayed off")
|
||||
}
|
||||
for _, o := range got {
|
||||
if o.Label == "" || o.ID == "" {
|
||||
t.Errorf("output missing id/label: %+v", o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Publishing nothing would make the stream unreachable, so an all-off set
|
||||
// falls back to HLS rather than going dark.
|
||||
func TestNormalizeOutputsNeverPublishesNothing(t *testing.T) {
|
||||
got := NormalizeOutputs([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: false},
|
||||
{ID: "dash", Format: FormatDASH, Enabled: false},
|
||||
})
|
||||
if len(EnabledOutputs(got)) == 0 {
|
||||
t.Fatal("an all-off output set should fall back to HLS")
|
||||
}
|
||||
for _, o := range EnabledOutputs(got) {
|
||||
if o.Format != FormatHLS {
|
||||
t.Errorf("fallback should be HLS, got %q", o.Format)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPublishLinks(t *testing.T) {
|
||||
variants, err := EncodeVariantsJSON([]VariantSpec{
|
||||
{ID: SourceVariantID, Enabled: true, Height: 0},
|
||||
{ID: "hd", Enabled: true, Height: 720},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs, err := EncodeOutputsJSON([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: true},
|
||||
{ID: "ts", Format: FormatTS, Enabled: true},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
links := BuildPublishLinks("city-news", variants, outputs)
|
||||
// master + 2 variants x 2 outputs
|
||||
if len(links) != 5 {
|
||||
t.Fatalf("want 5 links, got %d: %+v", len(links), links)
|
||||
}
|
||||
if !links[0].Master || links[0].PlayPath != "/hls/city-news/master.m3u8" {
|
||||
t.Errorf("first link should be the ABR master, got %+v", links[0])
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, l := range links {
|
||||
if l.PlayPath == "" {
|
||||
t.Errorf("link with no path: %+v", l)
|
||||
}
|
||||
if seen[l.PlayPath] {
|
||||
t.Errorf("duplicate link path %q", l.PlayPath)
|
||||
}
|
||||
seen[l.PlayPath] = true
|
||||
}
|
||||
for _, want := range []string{
|
||||
"/hls/city-news/index.m3u8",
|
||||
"/hls/city-news-hd/index.m3u8",
|
||||
"/live/city-news.ts",
|
||||
"/live/city-news-hd.ts",
|
||||
} {
|
||||
if !seen[want] {
|
||||
t.Errorf("missing expected link %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With a single rung there is nothing to switch between, so no master.
|
||||
func TestBuildPublishLinksNoMasterForSingleRung(t *testing.T) {
|
||||
variants, _ := EncodeVariantsJSON([]VariantSpec{{ID: SourceVariantID, Enabled: true}})
|
||||
outputs, _ := EncodeOutputsJSON(DefaultOutputs())
|
||||
for _, l := range BuildPublishLinks("solo", variants, outputs) {
|
||||
if l.Master {
|
||||
t.Error("a single-rung stream should not advertise an ABR master")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantWidthAndBitrate(t *testing.T) {
|
||||
if got := VariantWidth(720); got != 1280 {
|
||||
t.Errorf("720p width = %d want 1280", got)
|
||||
}
|
||||
if got := VariantWidth(1080); got != 1920 {
|
||||
t.Errorf("1080p width = %d want 1920", got)
|
||||
}
|
||||
if got := VariantWidth(0); got != 0 {
|
||||
t.Errorf("source height should give width 0, got %d", got)
|
||||
}
|
||||
if got := VariantWidth(480); got%2 != 0 {
|
||||
t.Errorf("width must be even for H.264, got %d", got)
|
||||
}
|
||||
for in, want := range map[string]int{
|
||||
"2800k": 2800000, "1200K": 1200000, "5M": 5000000,
|
||||
"": 0, "fast": 0, "900": 900,
|
||||
} {
|
||||
if got := BitrateBps(in); got != want {
|
||||
t.Errorf("BitrateBps(%q) = %d want %d", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidKeyPairs(t *testing.T) {
|
||||
const kid = "0123456789abcdef0123456789abcdef"
|
||||
const key = "fedcba9876543210fedcba9876543210"
|
||||
good := []string{
|
||||
kid + ":" + key,
|
||||
kid + ":" + key + "\n" + kid + ":" + key,
|
||||
// Multi-KID separated by commas and semicolons, as the supervisor
|
||||
// accepts. A single-pair check would reject these, which is why the
|
||||
// agent used to re-capture multi-KID streams forever.
|
||||
kid + ":" + key + "," + kid + ":" + key,
|
||||
kid + ":" + key + ";" + kid + ":" + key,
|
||||
" " + kid + ":" + key + " \n\n",
|
||||
}
|
||||
for _, g := range good {
|
||||
if !ValidKeyPairs(g) {
|
||||
t.Errorf("ValidKeyPairs(%q) = false, want true", g)
|
||||
}
|
||||
}
|
||||
bad := []string{
|
||||
"", " ", "notakey", kid, kid + ":", ":" + key,
|
||||
kid + ":deadbeef",
|
||||
kid + ":" + key + "\nbroken",
|
||||
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz:" + key,
|
||||
}
|
||||
for _, b := range bad {
|
||||
if ValidKeyPairs(b) {
|
||||
t.Errorf("ValidKeyPairs(%q) = true, want false", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTags(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"Council, Sports": "council,sports",
|
||||
"council,council": "council",
|
||||
" Live Events ": "live-events",
|
||||
"": "",
|
||||
",,,": "",
|
||||
"A,b,C": "a,b,c",
|
||||
"Town Hall,town hall": "town-hall",
|
||||
} {
|
||||
if got := normalizeTags(in); got != want {
|
||||
t.Errorf("normalizeTags(%q) = %q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,13 +19,25 @@ import (
|
|||
|
||||
// Status is the resolved path for each tool after Ensure.
|
||||
type Status struct {
|
||||
BinDir string `json:"bin_dir"`
|
||||
FFmpeg string `json:"ffmpeg"`
|
||||
NRE string `json:"nre"`
|
||||
MP4Decrypt string `json:"mp4decrypt"`
|
||||
BinDir string `json:"bin_dir"`
|
||||
FFmpeg string `json:"ffmpeg"`
|
||||
NRE string `json:"nre"`
|
||||
MP4Decrypt string `json:"mp4decrypt"`
|
||||
Notes []string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// Public is Status with filesystem paths reduced to presence flags, for the
|
||||
// unauthenticated part of /api/health. Absolute install paths are useful to an
|
||||
// operator and useful to an attacker, so anonymous callers get neither.
|
||||
func (s Status) Public() map[string]any {
|
||||
have := func(p string) bool { return strings.TrimSpace(p) != "" }
|
||||
return map[string]any{
|
||||
"ffmpeg": have(s.FFmpeg),
|
||||
"nre": have(s.NRE),
|
||||
"mp4decrypt": have(s.MP4Decrypt),
|
||||
}
|
||||
}
|
||||
|
||||
// Options controls Ensure.
|
||||
type Options struct {
|
||||
// BinDir overrides where binaries are installed. Empty → <repo.Root()>/bin
|
||||
|
|
|
|||
675
apps/streamd/internal/hlsgate/hlsgate.go
Normal file
675
apps/streamd/internal/hlsgate/hlsgate.go
Normal file
|
|
@ -0,0 +1,675 @@
|
|||
// Package hlsgate serves the published media and, for streams marked
|
||||
// on-demand, starts them when a viewer first asks for a playlist.
|
||||
//
|
||||
// It replaces a plain http.FileServer over data/www, which could only serve
|
||||
// what was already running, listed directories, and told nobody anything about
|
||||
// who was watching.
|
||||
package hlsgate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
)
|
||||
|
||||
// Supervisor is the subset of the media supervisor the gate needs.
|
||||
type Supervisor interface {
|
||||
Start(id int64) error
|
||||
Stop(id int64) error
|
||||
Running(id int64) bool
|
||||
}
|
||||
|
||||
// CaptureRequester asks connected agents for fresh credentials now.
|
||||
type CaptureRequester interface {
|
||||
RequestCapture(st db.Stream, reason string) int
|
||||
}
|
||||
|
||||
// Defaults.
|
||||
const (
|
||||
// DefaultWait is how long a viewer's request is held while a stream
|
||||
// starts. Long enough for ffmpeg to produce a first segment, short enough
|
||||
// that a browser does not give up on its own.
|
||||
DefaultWait = 30 * time.Second
|
||||
// DefaultCaptureWait applies when credentials must be captured first,
|
||||
// which involves a real phone and takes far longer.
|
||||
DefaultCaptureWait = 120 * time.Second
|
||||
// viewerWindow is how long a client counts as watching after its last
|
||||
// request. A player fetches a segment every few seconds, so a minute is
|
||||
// generous without being stale.
|
||||
viewerWindow = 60 * time.Second
|
||||
idleCheckTick = 30 * time.Second
|
||||
pollInterval = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
// Config is the gate's settings. It is separate from Gate so it can be passed
|
||||
// by value without copying the gate's mutex.
|
||||
type Config struct {
|
||||
Store *db.Store
|
||||
WWWRoot string
|
||||
Sup Supervisor
|
||||
Fanout *tsfanout.Set
|
||||
Capture CaptureRequester
|
||||
Trust httpx.Trust
|
||||
Log *slog.Logger
|
||||
|
||||
// Wait and CaptureWait bound how long a request is held.
|
||||
Wait time.Duration
|
||||
CaptureWait time.Duration
|
||||
}
|
||||
|
||||
type Gate struct {
|
||||
Config
|
||||
|
||||
mu sync.Mutex
|
||||
tracks map[string]*track
|
||||
waking map[int64]*wake
|
||||
|
||||
// wakeLimiter bounds how often an anonymous caller can trigger a start.
|
||||
// Waking a stream spawns processes, so it is the one unauthenticated
|
||||
// action here with real cost.
|
||||
wakeLimiter *auth.Limiter
|
||||
}
|
||||
|
||||
// track is the live request picture for one stream.
|
||||
type track struct {
|
||||
lastRequest time.Time
|
||||
requests int64
|
||||
// clients maps a client address to its last request time, giving a
|
||||
// distinct-viewer count over the window rather than a request count.
|
||||
clients map[string]time.Time
|
||||
}
|
||||
|
||||
// wake is the single-flight state for one stream being started.
|
||||
type wake struct {
|
||||
done chan struct{}
|
||||
err error
|
||||
started time.Time
|
||||
}
|
||||
|
||||
func New(cfg Config) *Gate {
|
||||
out := &Gate{Config: cfg}
|
||||
if out.Wait <= 0 {
|
||||
out.Wait = DefaultWait
|
||||
}
|
||||
if out.CaptureWait <= 0 {
|
||||
out.CaptureWait = DefaultCaptureWait
|
||||
}
|
||||
if out.Log == nil {
|
||||
out.Log = slog.Default()
|
||||
}
|
||||
out.tracks = map[string]*track{}
|
||||
out.waking = map[int64]*wake{}
|
||||
// Eight wakes per client, refilling slowly: enough for a person opening a
|
||||
// few channels, not enough to be used as a process-spawning amplifier.
|
||||
out.wakeLimiter = auth.NewLimiter(8, 0.1)
|
||||
return out
|
||||
}
|
||||
|
||||
func (g *Gate) Mount(mux *http.ServeMux) {
|
||||
mux.Handle("/hls/", http.HandlerFunc(g.serveHLS))
|
||||
mux.Handle("/live/", http.HandlerFunc(g.serveLive))
|
||||
}
|
||||
|
||||
// target is a resolved request: which stream, which rung, which file.
|
||||
type target struct {
|
||||
stream db.Stream
|
||||
variant db.VariantSpec
|
||||
// dir is the www subdirectory, i.e. the stream or variant directory name.
|
||||
dir string
|
||||
// rel is the file path within dir ("index.m3u8", "cmaf/index.m3u8", ...).
|
||||
rel string
|
||||
// isPlaylist marks the requests that may wake a stream.
|
||||
isPlaylist bool
|
||||
}
|
||||
|
||||
var errNotFound = errors.New("no such stream")
|
||||
|
||||
// resolve maps a www directory name onto a stream and rung.
|
||||
//
|
||||
// The layout is "<name>" for the source rung and "<name>-<variant>" for the
|
||||
// others, and a stream name may itself contain a dash — so an exact match is
|
||||
// tried first, and only then a split at the last dash whose suffix is a real
|
||||
// rung of the stream that remains.
|
||||
func (g *Gate) resolve(dir string) (db.Stream, db.VariantSpec, error) {
|
||||
if dir == "" {
|
||||
return db.Stream{}, db.VariantSpec{}, errNotFound
|
||||
}
|
||||
if st, err := g.Store.GetStreamByName(dir); err == nil {
|
||||
return st, sourceRung(st), nil
|
||||
}
|
||||
// Try progressively earlier dashes, so "a-b-hd" resolves against a stream
|
||||
// called "a-b" even though "a" also exists.
|
||||
for i := strings.LastIndex(dir, "-"); i > 0; i = strings.LastIndex(dir[:i], "-") {
|
||||
name, variantID := dir[:i], dir[i+1:]
|
||||
st, err := g.Store.GetStreamByName(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
|
||||
if v.ID == variantID {
|
||||
return st, v, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return db.Stream{}, db.VariantSpec{}, errNotFound
|
||||
}
|
||||
|
||||
func sourceRung(st db.Stream) db.VariantSpec {
|
||||
for _, v := range db.ParseVariantsJSON(st.VariantsJSON) {
|
||||
if v.IsSource() {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true}
|
||||
}
|
||||
|
||||
// serveHLS handles /hls/<dir>/<file...>.
|
||||
func (g *Gate) serveHLS(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
rest := strings.TrimPrefix(r.URL.Path, "/hls/")
|
||||
// A trailing slash or a bare /hls/ used to produce a directory listing,
|
||||
// which enumerated every stream on the server.
|
||||
if rest == "" || strings.HasSuffix(rest, "/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
dir, rel, ok := strings.Cut(rest, "/")
|
||||
if !ok || rel == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
st, variant, err := g.resolve(dir)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// Reject anything that tries to climb out of the stream's directory
|
||||
// before it is ever joined to a filesystem path.
|
||||
clean := path.Clean("/" + rel)
|
||||
if clean == "/" || strings.Contains(clean, "..") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
rel = strings.TrimPrefix(clean, "/")
|
||||
|
||||
t := target{
|
||||
stream: st,
|
||||
variant: variant,
|
||||
dir: dir,
|
||||
rel: rel,
|
||||
isPlaylist: isPlaylist(rel),
|
||||
}
|
||||
if !g.authorise(w, r, st) {
|
||||
return
|
||||
}
|
||||
g.note(st.Name, g.Trust.ClientIP(r))
|
||||
|
||||
full := filepath.Join(g.WWWRoot, filepath.FromSlash(dir), filepath.FromSlash(rel))
|
||||
if _, err := os.Stat(full); err != nil {
|
||||
// Only a playlist request may wake a stream. A segment request for a
|
||||
// stream that is not running is simply a 404: starting a stream would
|
||||
// not produce that particular segment anyway.
|
||||
if !t.isPlaylist || !g.shouldWake(st) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if !g.waitForStart(w, r, t, full) {
|
||||
return
|
||||
}
|
||||
}
|
||||
g.serveFile(w, r, full, rel)
|
||||
}
|
||||
|
||||
// serveLive handles /live/<dir>.ts, the progressive MPEG-TS output.
|
||||
func (g *Gate) serveLive(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
name := strings.TrimPrefix(r.URL.Path, "/live/")
|
||||
if !strings.HasSuffix(name, ".ts") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
dir := strings.TrimSuffix(name, ".ts")
|
||||
if dir == "" || strings.ContainsAny(dir, "/\\") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
st, _, err := g.resolve(dir)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if !tsEnabled(st) {
|
||||
http.Error(w, "this stream does not publish a progressive MPEG-TS output", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if !g.authorise(w, r, st) {
|
||||
return
|
||||
}
|
||||
g.note(st.Name, g.Trust.ClientIP(r))
|
||||
|
||||
ring, ok := g.Fanout.Get(dir)
|
||||
if !ok {
|
||||
// Nothing is publishing yet: wake it if we may, then wait for a ring.
|
||||
if !g.shouldWake(st) {
|
||||
http.Error(w, "stream is not running", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if !g.wakeAndWaitRing(w, r, st, dir) {
|
||||
return
|
||||
}
|
||||
ring, ok = g.Fanout.Get(dir)
|
||||
if !ok {
|
||||
g.retryLater(w, "stream did not start in time")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if r.Method == http.MethodHead {
|
||||
w.Header().Set("Content-Type", "video/mp2t")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
reader := ring.NewReader()
|
||||
defer reader.Close()
|
||||
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "video/mp2t")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
// Defeat proxy buffering, or the viewer waits for a buffer to fill.
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
flusher, _ := w.(http.Flusher)
|
||||
buf := make([]byte, 64<<10)
|
||||
ctx := r.Context()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
n, err := reader.Read(buf)
|
||||
if n > 0 {
|
||||
if _, werr := w.Write(buf[:n]); werr != nil {
|
||||
return
|
||||
}
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
// A request that is actively pulling bytes is a live viewer, but
|
||||
// re-noting on every chunk would be pointless work; the ring's
|
||||
// own reader count covers the fine grain.
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, tsfanout.ErrLagged) {
|
||||
g.Log.Info("dropped a progressive-TS client that fell behind",
|
||||
"stream", st.Name, "ip", g.Trust.ClientIP(r))
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tsEnabled(st db.Stream) bool {
|
||||
for _, o := range db.EnabledOutputs(db.ParseOutputsJSON(st.OutputsJSON)) {
|
||||
if o.Format == db.FormatTS {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isPlaylist(rel string) bool {
|
||||
l := strings.ToLower(rel)
|
||||
return strings.HasSuffix(l, ".m3u8") || strings.HasSuffix(l, ".mpd")
|
||||
}
|
||||
|
||||
// authorise enforces the per-stream public flag. A public stream is readable
|
||||
// by anyone, which is what makes on-demand work; a private one needs a
|
||||
// principal.
|
||||
func (g *Gate) authorise(w http.ResponseWriter, r *http.Request, st db.Stream) bool {
|
||||
if st.Public {
|
||||
return true
|
||||
}
|
||||
if p := auth.From(r); p != nil {
|
||||
return true
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="streamd"`)
|
||||
http.Error(w, "this stream is not public", http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
|
||||
// shouldWake reports whether this request may start the stream.
|
||||
// Deliberately NOT conditioned on the stream being stopped: when twenty
|
||||
// viewers arrive together, the first one starts it and the rest must wait for
|
||||
// the same playlist. Checking Running() here meant everyone after the first
|
||||
// got a 404 while the stream was still starting. startOnce is what makes sure
|
||||
// only one start actually happens.
|
||||
func (g *Gate) shouldWake(st db.Stream) bool {
|
||||
if !st.OnDemand || !st.Enabled {
|
||||
return false
|
||||
}
|
||||
// Nothing to start from: no manifest, and no agent able to fetch one.
|
||||
if strings.TrimSpace(st.MPD) == "" && !st.NeedsCapture {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// waitForStart holds the request while the stream comes up. Returns true when
|
||||
// the file now exists and may be served.
|
||||
func (g *Gate) waitForStart(w http.ResponseWriter, r *http.Request, t target, full string) bool {
|
||||
ip := g.Trust.ClientIP(r)
|
||||
if !g.wakeLimiter.Allow(ip) {
|
||||
g.retryLater(w, "too many start requests from this client")
|
||||
return false
|
||||
}
|
||||
st := t.stream
|
||||
deadline := g.Wait
|
||||
// Credentials have to be captured first, which involves a real phone and
|
||||
// is far slower than starting a packager.
|
||||
if st.NeedsCapture {
|
||||
deadline = g.CaptureWait
|
||||
}
|
||||
if err := g.startOnce(st); err != nil {
|
||||
g.Log.Error("on-demand start failed", "stream", st.Name, "err", err)
|
||||
g.retryLater(w, "stream could not be started")
|
||||
return false
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
give := time.Now().Add(deadline)
|
||||
for time.Now().Before(give) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// The viewer gave up; the stream stays up for the idle timeout so
|
||||
// their retry is instant.
|
||||
return false
|
||||
case <-time.After(pollInterval):
|
||||
}
|
||||
if fi, err := os.Stat(full); err == nil && fi.Size() > 0 {
|
||||
// A playlist exists; make sure it lists at least one segment, or
|
||||
// the player gets an empty playlist and stops.
|
||||
if !t.isPlaylist || playlistHasSegment(full) {
|
||||
g.note(st.Name, ip)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
g.retryLater(w, "stream is still starting")
|
||||
return false
|
||||
}
|
||||
|
||||
// wakeAndWaitRing starts a stream and waits for its progressive-TS ring.
|
||||
func (g *Gate) wakeAndWaitRing(w http.ResponseWriter, r *http.Request, st db.Stream, dir string) bool {
|
||||
ip := g.Trust.ClientIP(r)
|
||||
if !g.wakeLimiter.Allow(ip) {
|
||||
g.retryLater(w, "too many start requests from this client")
|
||||
return false
|
||||
}
|
||||
deadline := g.Wait
|
||||
if st.NeedsCapture {
|
||||
deadline = g.CaptureWait
|
||||
}
|
||||
if err := g.startOnce(st); err != nil {
|
||||
g.retryLater(w, "stream could not be started")
|
||||
return false
|
||||
}
|
||||
ctx := r.Context()
|
||||
give := time.Now().Add(deadline)
|
||||
for time.Now().Before(give) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-time.After(pollInterval):
|
||||
}
|
||||
if _, ok := g.Fanout.Get(dir); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
g.retryLater(w, "stream is still starting")
|
||||
return false
|
||||
}
|
||||
|
||||
// startOnce starts a stream under a per-stream single flight, so twenty
|
||||
// viewers arriving together produce one start, not twenty.
|
||||
func (g *Gate) startOnce(st db.Stream) error {
|
||||
g.mu.Lock()
|
||||
if wk, ok := g.waking[st.ID]; ok {
|
||||
g.mu.Unlock()
|
||||
// Someone else is already starting it; wait for their result.
|
||||
<-wk.done
|
||||
return wk.err
|
||||
}
|
||||
if g.Sup.Running(st.ID) {
|
||||
// Already up, or already coming up from an earlier request: there is
|
||||
// nothing to start, only a playlist to wait for. Calling Start again
|
||||
// would restart a healthy stream and cut off its current viewers.
|
||||
g.noteLocked(st.Name, "")
|
||||
g.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
wk := &wake{done: make(chan struct{}), started: time.Now()}
|
||||
g.waking[st.ID] = wk
|
||||
// Count the wake as activity straight away, so the idle sweep cannot stop
|
||||
// the stream before the first viewer has been served.
|
||||
g.noteLocked(st.Name, "")
|
||||
g.mu.Unlock()
|
||||
|
||||
g.Log.Info("waking on-demand stream", "stream", st.Name, "needs_capture", st.NeedsCapture)
|
||||
g.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: st.ID, Kind: db.EventOnDemandWake, Severity: db.SevInfo,
|
||||
Message: "a viewer requested this stream, starting it",
|
||||
})
|
||||
// Credentials may be stale. Ask any connected agent to refresh now rather
|
||||
// than on its next poll, with a viewer already waiting.
|
||||
if st.NeedsCapture && g.Capture != nil {
|
||||
if n := g.Capture.RequestCapture(st, "ondemand_wake"); n > 0 {
|
||||
g.Log.Info("asked agents for fresh credentials", "stream", st.Name, "agents", n)
|
||||
}
|
||||
}
|
||||
|
||||
err := g.Sup.Start(st.ID)
|
||||
|
||||
g.mu.Lock()
|
||||
wk.err = err
|
||||
delete(g.waking, st.ID)
|
||||
g.mu.Unlock()
|
||||
close(wk.done)
|
||||
return err
|
||||
}
|
||||
|
||||
// playlistHasSegment reports whether a media playlist lists at least one
|
||||
// segment. A freshly created but empty playlist makes a player give up.
|
||||
func playlistHasSegment(p string) bool {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
body := string(b)
|
||||
if strings.HasSuffix(strings.ToLower(p), ".mpd") {
|
||||
// A DASH manifest is self-describing; its presence is enough.
|
||||
return strings.Contains(body, "<MPD")
|
||||
}
|
||||
// A master playlist lists other playlists, not segments.
|
||||
if strings.Contains(body, "#EXT-X-STREAM-INF") {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(body, "#EXTINF")
|
||||
}
|
||||
|
||||
func (g *Gate) retryLater(w http.ResponseWriter, msg string) {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
http.Error(w, msg, http.StatusServiceUnavailable)
|
||||
}
|
||||
|
||||
// serveFile sends one media file with cache headers appropriate to its kind.
|
||||
func (g *Gate) serveFile(w http.ResponseWriter, r *http.Request, full, rel string) {
|
||||
f, err := os.Open(full)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil || fi.IsDir() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
h := w.Header()
|
||||
low := strings.ToLower(rel)
|
||||
switch {
|
||||
case strings.HasSuffix(low, ".m3u8"):
|
||||
h.Set("Content-Type", "application/vnd.apple.mpegurl")
|
||||
// A live playlist changes every few seconds.
|
||||
h.Set("Cache-Control", "no-cache, max-age=1")
|
||||
case strings.HasSuffix(low, ".mpd"):
|
||||
h.Set("Content-Type", "application/dash+xml")
|
||||
h.Set("Cache-Control", "no-cache, max-age=1")
|
||||
case strings.HasSuffix(low, ".ts"):
|
||||
h.Set("Content-Type", "video/mp2t")
|
||||
h.Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
case strings.HasSuffix(low, ".m4s"), strings.HasSuffix(low, ".mp4"):
|
||||
h.Set("Content-Type", "video/mp4")
|
||||
h.Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
default:
|
||||
h.Set("Cache-Control", "no-cache")
|
||||
}
|
||||
http.ServeContent(w, r, filepath.Base(rel), fi.ModTime(), f)
|
||||
}
|
||||
|
||||
// ---------- viewer tracking ----------
|
||||
|
||||
// note records a request against a stream.
|
||||
func (g *Gate) note(name, ip string) {
|
||||
g.mu.Lock()
|
||||
g.noteLocked(name, ip)
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *Gate) noteLocked(name, ip string) {
|
||||
t, ok := g.tracks[name]
|
||||
if !ok {
|
||||
t = &track{clients: map[string]time.Time{}}
|
||||
g.tracks[name] = t
|
||||
}
|
||||
nowT := time.Now()
|
||||
t.lastRequest = nowT
|
||||
t.requests++
|
||||
if ip != "" {
|
||||
t.clients[ip] = nowT
|
||||
// Expire stale clients here rather than on a timer; the map only
|
||||
// grows while requests are arriving.
|
||||
if len(t.clients) > 1 {
|
||||
for k, seen := range t.clients {
|
||||
if nowT.Sub(seen) > viewerWindow {
|
||||
delete(t.clients, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ViewersFor is the number of distinct clients seen in the last minute, plus
|
||||
// any progressive-TS readers currently attached.
|
||||
func (g *Gate) ViewersFor(name string) int {
|
||||
g.mu.Lock()
|
||||
t, ok := g.tracks[name]
|
||||
n := 0
|
||||
if ok {
|
||||
nowT := time.Now()
|
||||
for _, seen := range t.clients {
|
||||
if nowT.Sub(seen) <= viewerWindow {
|
||||
n++
|
||||
}
|
||||
}
|
||||
}
|
||||
g.mu.Unlock()
|
||||
if g.Fanout != nil {
|
||||
n += g.Fanout.Readers(name)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// RunIdleLoop stops on-demand streams nobody is watching.
|
||||
func (g *Gate) RunIdleLoop(stop <-chan struct{}) {
|
||||
t := time.NewTicker(idleCheckTick)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-t.C:
|
||||
g.sweepIdle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gate) sweepIdle() {
|
||||
list, err := g.Store.ListStreams()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, st := range list {
|
||||
if !st.OnDemand || !g.Sup.Running(st.ID) {
|
||||
continue
|
||||
}
|
||||
idle := time.Duration(st.IdleTimeoutS) * time.Second
|
||||
if idle <= 0 {
|
||||
idle = db.DefaultIdleTimeoutS * time.Second
|
||||
}
|
||||
// A progressive-TS client holds an open connection rather than
|
||||
// polling, so it would otherwise look idle the whole time it watched.
|
||||
if g.Fanout != nil && g.Fanout.Readers(st.Name) > 0 {
|
||||
g.note(st.Name, "")
|
||||
continue
|
||||
}
|
||||
g.mu.Lock()
|
||||
t, seen := g.tracks[st.Name]
|
||||
var last time.Time
|
||||
if seen {
|
||||
last = t.lastRequest
|
||||
}
|
||||
g.mu.Unlock()
|
||||
if !seen || last.IsZero() {
|
||||
// Running but never requested through the gate: it was started by
|
||||
// hand or by a schedule, so leave it alone.
|
||||
continue
|
||||
}
|
||||
if time.Since(last) < idle {
|
||||
continue
|
||||
}
|
||||
g.Log.Info("stopping idle on-demand stream",
|
||||
"stream", st.Name, "idle_s", int(time.Since(last).Seconds()))
|
||||
g.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: st.ID, Kind: db.EventIdleStop, Severity: db.SevInfo,
|
||||
Message: "no viewers for " + idle.String() + ", stopping until the next request",
|
||||
})
|
||||
if err := g.Sup.Stop(st.ID); err != nil {
|
||||
g.Log.Error("idle stop failed", "stream", st.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
g.mu.Lock()
|
||||
delete(g.tracks, st.Name)
|
||||
g.mu.Unlock()
|
||||
}
|
||||
}
|
||||
642
apps/streamd/internal/hlsgate/hlsgate_test.go
Normal file
642
apps/streamd/internal/hlsgate/hlsgate_test.go
Normal file
|
|
@ -0,0 +1,642 @@
|
|||
package hlsgate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
)
|
||||
|
||||
// fakeSup records what the gate asked for, and can pretend a stream comes up.
|
||||
type fakeSup struct {
|
||||
mu sync.Mutex
|
||||
starts int32
|
||||
stops int32
|
||||
running map[int64]bool
|
||||
onStart func(id int64)
|
||||
startErr error
|
||||
}
|
||||
|
||||
func newFakeSup() *fakeSup {
|
||||
return &fakeSup{running: map[int64]bool{}}
|
||||
}
|
||||
|
||||
func (f *fakeSup) Start(id int64) error {
|
||||
atomic.AddInt32(&f.starts, 1)
|
||||
if f.startErr != nil {
|
||||
return f.startErr
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.running[id] = true
|
||||
cb := f.onStart
|
||||
f.mu.Unlock()
|
||||
if cb != nil {
|
||||
cb(id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSup) Stop(id int64) error {
|
||||
atomic.AddInt32(&f.stops, 1)
|
||||
f.mu.Lock()
|
||||
f.running[id] = false
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSup) Running(id int64) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.running[id]
|
||||
}
|
||||
|
||||
type fakeCapture struct{ n int32 }
|
||||
|
||||
func (c *fakeCapture) RequestCapture(st db.Stream, reason string) int {
|
||||
atomic.AddInt32(&c.n, 1)
|
||||
return 1
|
||||
}
|
||||
|
||||
func newTestGate(t *testing.T) (*Gate, *db.Store, *fakeSup, string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
store, err := db.Open(filepath.Join(dir, "db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
www := filepath.Join(dir, "www")
|
||||
if err := os.MkdirAll(www, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sup := newFakeSup()
|
||||
g := New(Config{
|
||||
Store: store,
|
||||
WWWRoot: www,
|
||||
Sup: sup,
|
||||
Fanout: tsfanout.NewSet(1 << 16),
|
||||
Wait: 2 * time.Second,
|
||||
})
|
||||
return g, store, sup, www
|
||||
}
|
||||
|
||||
func mkStream(t *testing.T, store *db.Store, in db.CreateStream) db.Stream {
|
||||
t.Helper()
|
||||
st, err := store.CreateStream(in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, path, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
const livePlaylist = "#EXTM3U\n#EXT-X-VERSION:3\n#EXTINF:4.0,\nseg_00001.ts\n"
|
||||
|
||||
// ---------- path resolution ----------
|
||||
|
||||
// A stream name may contain a dash, so "city-news-hd" must resolve as the
|
||||
// "hd" rung of "city-news", while "city-news" resolves as its own source rung.
|
||||
func TestResolveStreamNamesContainingDashes(t *testing.T) {
|
||||
g, store, _, _ := newTestGate(t)
|
||||
variants, err := db.EncodeVariantsJSON([]db.VariantSpec{
|
||||
{ID: db.SourceVariantID, Enabled: true},
|
||||
{ID: "hd", Enabled: true, Height: 720},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mkStream(t, store, db.CreateStream{Name: "city-news", VariantsJSON: variants})
|
||||
mkStream(t, store, db.CreateStream{Name: "city", VariantsJSON: variants})
|
||||
// A stream whose literal name ends in -hd must win over being read as a
|
||||
// rung of another stream.
|
||||
mkStream(t, store, db.CreateStream{Name: "sport-hd"})
|
||||
|
||||
cases := []struct {
|
||||
dir string
|
||||
wantStream string
|
||||
wantVariant string
|
||||
}{
|
||||
{"city-news", "city-news", db.SourceVariantID},
|
||||
{"city-news-hd", "city-news", "hd"},
|
||||
{"city", "city", db.SourceVariantID},
|
||||
{"city-hd", "city", "hd"},
|
||||
{"sport-hd", "sport-hd", db.SourceVariantID},
|
||||
}
|
||||
for _, c := range cases {
|
||||
st, v, err := g.resolve(c.dir)
|
||||
if err != nil {
|
||||
t.Errorf("resolve(%q) failed: %v", c.dir, err)
|
||||
continue
|
||||
}
|
||||
if st.Name != c.wantStream || v.ID != c.wantVariant {
|
||||
t.Errorf("resolve(%q) = %s/%s, want %s/%s",
|
||||
c.dir, st.Name, v.ID, c.wantStream, c.wantVariant)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "nope", "city-news-4k", "city-news-hd-extra"} {
|
||||
if _, _, err := g.resolve(bad); err == nil {
|
||||
t.Errorf("resolve(%q) should have failed", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- traversal ----------
|
||||
|
||||
func TestPathTraversalRejected(t *testing.T) {
|
||||
g, store, _, www := newTestGate(t)
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
// A secret outside the media root, as a credible target.
|
||||
writeFile(t, filepath.Join(filepath.Dir(www), "streamd.db"), "SECRET")
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(g.serveHLS))
|
||||
defer srv.Close()
|
||||
|
||||
for _, p := range []string{
|
||||
"/hls/news/../../streamd.db",
|
||||
"/hls/news/..%2f..%2fstreamd.db",
|
||||
"/hls/news/%2e%2e/%2e%2e/streamd.db",
|
||||
"/hls/news/....//....//streamd.db",
|
||||
"/hls/../streamd.db",
|
||||
} {
|
||||
req, err := http.NewRequest(http.MethodGet, srv.URL+p, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultTransport.RoundTrip(req)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
body := make([]byte, 64)
|
||||
n, _ := resp.Body.Read(body)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK && string(body[:n]) == "SECRET" {
|
||||
t.Errorf("traversal succeeded for %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryListingRefused(t *testing.T) {
|
||||
g, store, _, www := newTestGate(t)
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
|
||||
for _, p := range []string{"/hls/", "/hls/news/", "/hls/news"} {
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, p, nil))
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Errorf("%s returned 200; a listing would enumerate every stream", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- serving ----------
|
||||
|
||||
func TestServesExistingPlaylistWithCacheHeaders(t *testing.T) {
|
||||
g, store, _, www := newTestGate(t)
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
writeFile(t, filepath.Join(www, "news", "seg_00001.ts"), "mediabytes")
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("playlist: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "application/vnd.apple.mpegurl" {
|
||||
t.Errorf("playlist content type = %q", ct)
|
||||
}
|
||||
// A live playlist must not be cached, or viewers stick on a stale window.
|
||||
if cc := rec.Header().Get("Cache-Control"); cc == "" || !contains(cc, "no-cache") {
|
||||
t.Errorf("playlist cache-control = %q, want no-cache", cc)
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00001.ts", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("segment: %d", rec.Code)
|
||||
}
|
||||
// A segment never changes under its name, so it is cacheable forever.
|
||||
if cc := rec.Header().Get("Cache-Control"); !contains(cc, "immutable") {
|
||||
t.Errorf("segment cache-control = %q, want immutable", cc)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(h, needle string) bool {
|
||||
return len(h) >= len(needle) && (h == needle || indexOf(h, needle) >= 0)
|
||||
}
|
||||
|
||||
func indexOf(h, needle string) int {
|
||||
for i := 0; i+len(needle) <= len(h); i++ {
|
||||
if h[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// ---------- on-demand wake ----------
|
||||
|
||||
func TestWakeStartsStreamAndServesOnceReady(t *testing.T) {
|
||||
g, store, sup, www := newTestGate(t)
|
||||
on := true
|
||||
st := mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
})
|
||||
// The supervisor "starts" by producing a playlist, as the real one does.
|
||||
sup.onStart = func(id int64) {
|
||||
go func() {
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
}()
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("want the request held until ready, got %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := atomic.LoadInt32(&sup.starts); got != 1 {
|
||||
t.Errorf("starts = %d, want 1", got)
|
||||
}
|
||||
// The wake must be on the stream's timeline.
|
||||
_ = store.FlushHistory()
|
||||
events, err := store.ListEvents(st.ID, 20, db.EventOnDemandWake, "")
|
||||
if err != nil || len(events) == 0 {
|
||||
t.Errorf("expected an ondemand_wake event, got %v (%v)", events, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Twenty viewers arriving together must produce one start, not twenty.
|
||||
func TestWakeIsSingleFlight(t *testing.T) {
|
||||
g, store, sup, www := newTestGate(t)
|
||||
on := true
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
})
|
||||
var once sync.Once
|
||||
sup.onStart = func(id int64) {
|
||||
once.Do(func() {
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
const clients = 20
|
||||
var wg sync.WaitGroup
|
||||
codes := make([]int, clients)
|
||||
for i := 0; i < clients; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
|
||||
// Distinct client addresses, so the per-IP wake limiter does not
|
||||
// mask the single-flight behaviour being tested.
|
||||
req.RemoteAddr = fmt.Sprintf("10.0.0.%d:1234", i+1)
|
||||
g.serveHLS(rec, req)
|
||||
codes[i] = rec.Code
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if got := atomic.LoadInt32(&sup.starts); got != 1 {
|
||||
t.Errorf("concurrent wakes started the stream %d times, want exactly 1", got)
|
||||
}
|
||||
for i, c := range codes {
|
||||
if c != http.StatusOK {
|
||||
t.Errorf("client %d got %d, want 200", i, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWakeTimesOutWithRetryAfter(t *testing.T) {
|
||||
g, store, sup, _ := newTestGate(t)
|
||||
g.Wait = 300 * time.Millisecond
|
||||
on := true
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
})
|
||||
// Starts, but never produces media.
|
||||
sup.onStart = func(id int64) {}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("want 503 when the stream does not come up, got %d", rec.Code)
|
||||
}
|
||||
if ra := rec.Header().Get("Retry-After"); ra == "" {
|
||||
t.Error("a 503 should carry Retry-After so players back off sensibly")
|
||||
}
|
||||
}
|
||||
|
||||
// A stream that is not marked on-demand must never be started by a request.
|
||||
func TestNonOnDemandStreamIsNotWoken(t *testing.T) {
|
||||
g, store, sup, _ := newTestGate(t)
|
||||
yes := true
|
||||
no := false
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &no, Enabled: &yes,
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("want 404, got %d", rec.Code)
|
||||
}
|
||||
if got := atomic.LoadInt32(&sup.starts); got != 0 {
|
||||
t.Errorf("a non-on-demand stream was started %d times", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a playlist may wake a stream. Starting one to serve a specific old
|
||||
// segment would not produce that segment anyway.
|
||||
func TestSegmentRequestDoesNotWake(t *testing.T) {
|
||||
g, store, sup, _ := newTestGate(t)
|
||||
on := true
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00042.ts", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("want 404 for a segment on a stopped stream, got %d", rec.Code)
|
||||
}
|
||||
if got := atomic.LoadInt32(&sup.starts); got != 0 {
|
||||
t.Errorf("a segment request woke the stream %d times", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An empty playlist makes a player give up, so the gate must keep waiting
|
||||
// until a segment is listed.
|
||||
func TestWakeWaitsForASegmentNotJustAFile(t *testing.T) {
|
||||
g, store, sup, www := newTestGate(t)
|
||||
g.Wait = 2 * time.Second
|
||||
on := true
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
})
|
||||
sup.onStart = func(id int64) {
|
||||
go func() {
|
||||
// First an empty playlist, as ffmpeg briefly writes...
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), "#EXTM3U\n#EXT-X-VERSION:3\n")
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
// ...then one with a segment.
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
}()
|
||||
}
|
||||
start := time.Now()
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got %d", rec.Code)
|
||||
}
|
||||
if time.Since(start) < 250*time.Millisecond {
|
||||
t.Error("served an empty playlist instead of waiting for a segment")
|
||||
}
|
||||
if !contains(rec.Body.String(), "#EXTINF") {
|
||||
t.Error("served playlist has no segment")
|
||||
}
|
||||
}
|
||||
|
||||
// A woken stream with stale credentials must trigger a capture push, not wait
|
||||
// for the agent's next poll.
|
||||
func TestWakeRequestsCaptureWhenCredentialsAreStale(t *testing.T) {
|
||||
g, store, sup, _ := newTestGate(t)
|
||||
capReq := &fakeCapture{}
|
||||
g.Capture = capReq
|
||||
g.Wait = 200 * time.Millisecond
|
||||
// needs_capture switches the gate to the longer CaptureWait deadline, so
|
||||
// that is the one this test has to shorten.
|
||||
g.CaptureWait = 300 * time.Millisecond
|
||||
on := true
|
||||
// Enabled, on-demand, DRM required but no key: needs_capture is true.
|
||||
mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on,
|
||||
DRMMode: db.DRMYes,
|
||||
})
|
||||
sup.onStart = func(id int64) {}
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil))
|
||||
if got := atomic.LoadInt32(&capReq.n); got != 1 {
|
||||
t.Errorf("capture requests = %d, want 1", got)
|
||||
}
|
||||
_ = rec
|
||||
}
|
||||
|
||||
// ---------- access control ----------
|
||||
|
||||
func TestPrivateStreamNeedsAPrincipal(t *testing.T) {
|
||||
g, store, _, www := newTestGate(t)
|
||||
no := false
|
||||
mkStream(t, store, db.CreateStream{Name: "internal", Public: &no})
|
||||
writeFile(t, filepath.Join(www, "internal", "index.m3u8"), livePlaylist)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("a private stream should need auth, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// With a principal attached it is served.
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil)
|
||||
req = req.WithContext(auth.WithPrincipal(req.Context(),
|
||||
&auth.Principal{Kind: auth.ActorUser, Role: auth.RoleViewer, Name: "op"}))
|
||||
rec = httptest.NewRecorder()
|
||||
g.serveHLS(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("an authenticated request should be served, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- viewers ----------
|
||||
|
||||
func TestViewerCountIsDistinctClientsNotRequests(t *testing.T) {
|
||||
g, store, _, www := newTestGate(t)
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
|
||||
// One client, many requests: still one viewer.
|
||||
for i := 0; i < 10; i++ {
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
|
||||
req.RemoteAddr = "198.51.100.7:4000"
|
||||
g.serveHLS(httptest.NewRecorder(), req)
|
||||
}
|
||||
if got := g.ViewersFor("news"); got != 1 {
|
||||
t.Errorf("viewers = %d after 10 requests from one client, want 1", got)
|
||||
}
|
||||
|
||||
// Three clients: three viewers.
|
||||
for _, ip := range []string{"198.51.100.8:1", "198.51.100.9:1"} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
|
||||
req.RemoteAddr = ip
|
||||
g.serveHLS(httptest.NewRecorder(), req)
|
||||
}
|
||||
if got := g.ViewersFor("news"); got != 3 {
|
||||
t.Errorf("viewers = %d, want 3", got)
|
||||
}
|
||||
if got := g.ViewersFor("nosuchstream"); got != 0 {
|
||||
t.Errorf("unknown stream viewers = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- idle stop ----------
|
||||
|
||||
func TestIdleSweepStopsUnwatchedOnDemandStream(t *testing.T) {
|
||||
g, store, sup, www := newTestGate(t)
|
||||
on := true
|
||||
idle := 1 // one second
|
||||
st := mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd",
|
||||
OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
|
||||
})
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
sup.running[st.ID] = true
|
||||
|
||||
// A viewer arrives, so it is not idle yet.
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
|
||||
req.RemoteAddr = "203.0.113.5:9"
|
||||
g.serveHLS(httptest.NewRecorder(), req)
|
||||
|
||||
g.sweepIdle()
|
||||
if got := atomic.LoadInt32(&sup.stops); got != 0 {
|
||||
t.Fatalf("stopped a stream that was just requested (%d stops)", got)
|
||||
}
|
||||
|
||||
// Let the idle window pass.
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
g.sweepIdle()
|
||||
if got := atomic.LoadInt32(&sup.stops); got != 1 {
|
||||
t.Errorf("stops = %d, want 1 after the idle window", got)
|
||||
}
|
||||
_ = store.FlushHistory()
|
||||
events, _ := store.ListEvents(st.ID, 20, db.EventIdleStop, "")
|
||||
if len(events) == 0 {
|
||||
t.Error("expected an idle_stop event on the timeline")
|
||||
}
|
||||
}
|
||||
|
||||
// A stream started by hand or by a schedule must not be stopped by the idle
|
||||
// sweep just because nobody has pulled it through the gate.
|
||||
func TestIdleSweepLeavesManuallyStartedStreams(t *testing.T) {
|
||||
g, store, sup, _ := newTestGate(t)
|
||||
on := true
|
||||
idle := 1
|
||||
st := mkStream(t, store, db.CreateStream{
|
||||
Name: "council", MPD: "https://origin.test/a.mpd",
|
||||
OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle,
|
||||
})
|
||||
sup.running[st.ID] = true
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
g.sweepIdle()
|
||||
if got := atomic.LoadInt32(&sup.stops); got != 0 {
|
||||
t.Errorf("stopped a stream that was never requested through the gate (%d stops)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An always-on stream is never stopped for being idle.
|
||||
func TestIdleSweepIgnoresAlwaysOnStreams(t *testing.T) {
|
||||
g, store, sup, www := newTestGate(t)
|
||||
yes := true
|
||||
no := false
|
||||
idle := 1
|
||||
st := mkStream(t, store, db.CreateStream{
|
||||
Name: "news", MPD: "https://origin.test/a.mpd",
|
||||
OnDemand: &no, Enabled: &yes, IdleTimeoutS: &idle,
|
||||
})
|
||||
writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist)
|
||||
sup.running[st.ID] = true
|
||||
req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)
|
||||
req.RemoteAddr = "203.0.113.6:9"
|
||||
g.serveHLS(httptest.NewRecorder(), req)
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
g.sweepIdle()
|
||||
if got := atomic.LoadInt32(&sup.stops); got != 0 {
|
||||
t.Errorf("an always-on stream was idle-stopped (%d stops)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- progressive TS ----------
|
||||
|
||||
func TestLiveTSRequiresTheOutputToBeEnabled(t *testing.T) {
|
||||
g, store, _, _ := newTestGate(t)
|
||||
// Default outputs are HLS only, so /live/ must refuse.
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveLive(rec, httptest.NewRequest(http.MethodGet, "/live/news.ts", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("want 404 when the TS output is off, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveTSServesFromTheRing(t *testing.T) {
|
||||
g, store, _, _ := newTestGate(t)
|
||||
outputs, err := db.EncodeOutputsJSON([]db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "ts", Format: db.FormatTS, Enabled: true},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mkStream(t, store, db.CreateStream{Name: "news", OutputsJSON: outputs})
|
||||
|
||||
ring := g.Fanout.Create("news")
|
||||
// A PAT packet so a joining reader has a decodable starting point.
|
||||
pkt := make([]byte, 188)
|
||||
pkt[0] = 0x47
|
||||
pkt[3] = 0x10
|
||||
for i := 4; i < 188; i++ {
|
||||
pkt[i] = 0xAB
|
||||
}
|
||||
_, _ = ring.Write(pkt)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/live/news.ts", nil)
|
||||
// Close the ring shortly so the handler returns rather than streaming
|
||||
// forever.
|
||||
go func() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_ = ring.Close()
|
||||
}()
|
||||
g.serveLive(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "video/mp2t" {
|
||||
t.Errorf("content type = %q, want video/mp2t", ct)
|
||||
}
|
||||
if rec.Body.Len() == 0 {
|
||||
t.Error("no media was written to the client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveTSRejectsOddPaths(t *testing.T) {
|
||||
g, store, _, _ := newTestGate(t)
|
||||
mkStream(t, store, db.CreateStream{Name: "news"})
|
||||
for _, p := range []string{"/live/", "/live/news", "/live/news.m3u8", "/live/../x.ts", "/live/a/b.ts"} {
|
||||
rec := httptest.NewRecorder()
|
||||
g.serveLive(rec, httptest.NewRequest(http.MethodGet, p, nil))
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Errorf("%s returned 200", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
257
apps/streamd/internal/httpx/httpx.go
Normal file
257
apps/streamd/internal/httpx/httpx.go
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
// Package httpx holds the transport-level middleware streamd wraps around its
|
||||
// mux: real-client-IP resolution behind a trusted reverse proxy, security
|
||||
// headers, a strict CORS policy and an access log.
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ParseCIDRs turns a comma-separated list of CIDRs or bare IPs into networks.
|
||||
// Bare IPs become single-host networks, so --trusted-proxies 10.0.0.5 works.
|
||||
func ParseCIDRs(list string) ([]*net.IPNet, error) {
|
||||
var out []*net.IPNet
|
||||
for _, raw := range strings.Split(list, ",") {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
if _, n, err := net.ParseCIDR(raw); err == nil {
|
||||
out = append(out, n)
|
||||
continue
|
||||
}
|
||||
ip := net.ParseIP(raw)
|
||||
if ip == nil {
|
||||
return nil, &net.ParseError{Type: "CIDR or IP address", Text: raw}
|
||||
}
|
||||
bits := 32
|
||||
if ip.To4() == nil {
|
||||
bits = 128
|
||||
}
|
||||
out = append(out, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Trust decides whether forwarded headers may be believed.
|
||||
type Trust struct {
|
||||
Proxies []*net.IPNet
|
||||
}
|
||||
|
||||
func (t Trust) trusted(ip net.IP) bool {
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
for _, n := range t.Proxies {
|
||||
if n.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ClientIP returns the caller's address. X-Forwarded-For is honoured only when
|
||||
// the immediate peer is a configured trusted proxy; otherwise the peer address
|
||||
// wins, so a stranger cannot spoof their IP to dodge a rate limit.
|
||||
func (t Trust) ClientIP(r *http.Request) string {
|
||||
peer := peerIP(r)
|
||||
if !t.trusted(net.ParseIP(peer)) {
|
||||
return peer
|
||||
}
|
||||
// Right-most entry is the one our trusted proxy appended; walk from the
|
||||
// right to the first address that is not itself a trusted proxy.
|
||||
xff := r.Header.Get("X-Forwarded-For")
|
||||
parts := strings.Split(xff, ",")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
cand := strings.TrimSpace(parts[i])
|
||||
if cand == "" {
|
||||
continue
|
||||
}
|
||||
ip := net.ParseIP(cand)
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
if !t.trusted(ip) {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
if real := strings.TrimSpace(r.Header.Get("X-Real-IP")); real != "" {
|
||||
if ip := net.ParseIP(real); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
}
|
||||
return peer
|
||||
}
|
||||
|
||||
// IsHTTPS reports whether the original client request used TLS, trusting
|
||||
// X-Forwarded-Proto only from a trusted proxy.
|
||||
func (t Trust) IsHTTPS(r *http.Request) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
if !t.trusted(net.ParseIP(peerIP(r))) {
|
||||
return false
|
||||
}
|
||||
proto := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")))
|
||||
// A proxy chain may append, e.g. "https, http".
|
||||
if i := strings.IndexByte(proto, ','); i >= 0 {
|
||||
proto = strings.TrimSpace(proto[:i])
|
||||
}
|
||||
return proto == "https"
|
||||
}
|
||||
|
||||
func peerIP(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return strings.TrimSpace(r.RemoteAddr)
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// SecurityHeaders sets conservative defaults on every response. The CSP is
|
||||
// default-src 'self' throughout, which is why hls.js is vendored into the
|
||||
// embedded assets rather than loaded from a CDN.
|
||||
func SecurityHeaders(trust Trust, next http.Handler) http.Handler {
|
||||
const csp = "default-src 'self'; " +
|
||||
"script-src 'self'; " +
|
||||
"style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data:; " +
|
||||
"media-src 'self' blob:; " +
|
||||
"connect-src 'self' ws: wss:; " +
|
||||
"font-src 'self'; " +
|
||||
"object-src 'none'; " +
|
||||
"base-uri 'none'; " +
|
||||
"form-action 'self'; " +
|
||||
"frame-ancestors 'none'"
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
// Media responses are served to players and must stay cacheable and
|
||||
// embeddable; the policy above is for the dashboard documents.
|
||||
if !isMediaPath(r.URL.Path) {
|
||||
h.Set("Content-Security-Policy", csp)
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
}
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
if trust.IsHTTPS(r) {
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func isMediaPath(p string) bool {
|
||||
return strings.HasPrefix(p, "/hls/") || strings.HasPrefix(p, "/live/")
|
||||
}
|
||||
|
||||
// CORS echoes an Origin only when it is explicitly allowed. With no allowed
|
||||
// origins configured the API is same-origin only, which is the default.
|
||||
func CORS(allowed []string, next http.Handler) http.Handler {
|
||||
allow := map[string]bool{}
|
||||
wildcardMedia := false
|
||||
for _, o := range allowed {
|
||||
o = strings.TrimRight(strings.TrimSpace(o), "/")
|
||||
if o == "" {
|
||||
continue
|
||||
}
|
||||
if o == "*" {
|
||||
wildcardMedia = true
|
||||
continue
|
||||
}
|
||||
allow[strings.ToLower(o)] = true
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := strings.TrimRight(strings.TrimSpace(r.Header.Get("Origin")), "/")
|
||||
if origin != "" {
|
||||
switch {
|
||||
case allow[strings.ToLower(origin)]:
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
case wildcardMedia && isMediaPath(r.URL.Path):
|
||||
// A wildcard is only ever honoured for media, never for the
|
||||
// API, so credentials can never be read cross-origin.
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token, X-CSRF-Token, X-Agent-ID")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Max-Age", "600")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// StatusRecorder captures the response status and byte count for logging and
|
||||
// for the audit trail.
|
||||
type StatusRecorder struct {
|
||||
http.ResponseWriter
|
||||
Status int
|
||||
Bytes int64
|
||||
}
|
||||
|
||||
func (s *StatusRecorder) WriteHeader(code int) {
|
||||
if s.Status == 0 {
|
||||
s.Status = code
|
||||
}
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *StatusRecorder) Write(b []byte) (int, error) {
|
||||
if s.Status == 0 {
|
||||
s.Status = http.StatusOK
|
||||
}
|
||||
n, err := s.ResponseWriter.Write(b)
|
||||
s.Bytes += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Flush forwards to the underlying writer so SSE and progressive TS keep
|
||||
// streaming through this wrapper.
|
||||
func (s *StatusRecorder) Flush() {
|
||||
if f, ok := s.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// Unwrap lets http.ResponseController reach the real writer (needed for
|
||||
// per-write deadlines on long-lived streaming responses).
|
||||
func (s *StatusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
||||
|
||||
// AccessLog logs one line per request at debug level, and at info level for
|
||||
// 5xx responses so failures are visible without enabling debug.
|
||||
func AccessLog(lg *slog.Logger, trust Trust, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Media and websocket traffic is far too chatty for a per-request log.
|
||||
if isMediaPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/ws/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
rec := &StatusRecorder{ResponseWriter: w}
|
||||
next.ServeHTTP(rec, r)
|
||||
if rec.Status == 0 {
|
||||
rec.Status = http.StatusOK
|
||||
}
|
||||
lvl := slog.LevelDebug
|
||||
if rec.Status >= 500 {
|
||||
lvl = slog.LevelInfo
|
||||
}
|
||||
lg.Log(r.Context(), lvl, "http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.Status,
|
||||
"bytes", rec.Bytes,
|
||||
"dur_ms", time.Since(start).Milliseconds(),
|
||||
"ip", trust.ClientIP(r),
|
||||
)
|
||||
})
|
||||
}
|
||||
211
apps/streamd/internal/logfile/logfile.go
Normal file
211
apps/streamd/internal/logfile/logfile.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
// Package logfile provides a size-capped rotating writer for the per-stream
|
||||
// downloader and packager logs.
|
||||
//
|
||||
// It replaces two patterns that both lost information: the N_m3u8DL-RE log was
|
||||
// opened with O_TRUNC on every start, which erased the evidence from the crash
|
||||
// you were about to investigate, and the ffmpeg logs were opened O_APPEND with
|
||||
// no bound, which grew without limit on a long-running stream.
|
||||
package logfile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Defaults for a per-stream log.
|
||||
const (
|
||||
DefaultMaxBytes = 8 << 20 // 8 MiB per generation
|
||||
DefaultGenerations = 3 // name.log, name.log.1, name.log.2
|
||||
)
|
||||
|
||||
// Writer is an io.WriteCloser that rotates when the file passes MaxBytes.
|
||||
// It is safe for concurrent use, and for being handed to an exec.Cmd as
|
||||
// Stdout and Stderr at the same time.
|
||||
type Writer struct {
|
||||
path string
|
||||
maxBytes int64
|
||||
generations int
|
||||
|
||||
mu sync.Mutex
|
||||
f *os.File
|
||||
size int64
|
||||
}
|
||||
|
||||
// Open opens path for appending, rotating it if it is already over the cap.
|
||||
// maxBytes and generations fall back to the defaults when not positive.
|
||||
func Open(path string, maxBytes int64, generations int) (*Writer, error) {
|
||||
if maxBytes <= 0 {
|
||||
maxBytes = DefaultMaxBytes
|
||||
}
|
||||
if generations <= 0 {
|
||||
generations = DefaultGenerations
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w := &Writer{path: path, maxBytes: maxBytes, generations: generations}
|
||||
if err := w.reopen(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// OpenWithBanner opens the log and writes a start marker, so one file can hold
|
||||
// several runs and still be readable. This is what replaces truncating.
|
||||
func OpenWithBanner(path string, maxBytes int64, generations int, what string) (*Writer, error) {
|
||||
w, err := Open(path, maxBytes, generations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, "\n==== %s start %s ====\n", what, time.Now().UTC().Format(time.RFC3339))
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *Writer) reopen() error {
|
||||
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.f = f
|
||||
if st, err := f.Stat(); err == nil {
|
||||
w.size = st.Size()
|
||||
} else {
|
||||
w.size = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Writer) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.f == nil {
|
||||
return 0, os.ErrClosed
|
||||
}
|
||||
// Rotate before the write that would cross the cap, so a generation never
|
||||
// greatly exceeds MaxBytes.
|
||||
if w.size > 0 && w.size+int64(len(p)) > w.maxBytes {
|
||||
if err := w.rotateLocked(); err != nil {
|
||||
// Rotation failing (a Windows file lock, say) must not lose the
|
||||
// log line: keep writing to the current file.
|
||||
_, _ = fmt.Fprintf(w.f, "==== rotate failed: %v ====\n", err)
|
||||
}
|
||||
}
|
||||
n, err := w.f.Write(p)
|
||||
w.size += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// rotateLocked shifts name.log.N-1 -> name.log.N and starts a fresh file.
|
||||
func (w *Writer) rotateLocked() error {
|
||||
if err := w.f.Close(); err != nil {
|
||||
// Still try to rotate; reopen below will surface a real problem.
|
||||
_ = err
|
||||
}
|
||||
// Drop the oldest, then walk down so each generation moves up one.
|
||||
oldest := fmt.Sprintf("%s.%d", w.path, w.generations-1)
|
||||
_ = os.Remove(oldest)
|
||||
for i := w.generations - 2; i >= 1; i-- {
|
||||
from := fmt.Sprintf("%s.%d", w.path, i)
|
||||
to := fmt.Sprintf("%s.%d", w.path, i+1)
|
||||
if _, err := os.Stat(from); err == nil {
|
||||
_ = os.Rename(from, to)
|
||||
}
|
||||
}
|
||||
if w.generations > 1 {
|
||||
if err := os.Rename(w.path, w.path+".1"); err != nil && !os.IsNotExist(err) {
|
||||
// Could not move the live file; reopen it and carry on appending.
|
||||
if rerr := w.reopen(); rerr != nil {
|
||||
return rerr
|
||||
}
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
_ = os.Remove(w.path)
|
||||
}
|
||||
return w.reopen()
|
||||
}
|
||||
|
||||
func (w *Writer) Close() error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.f == nil {
|
||||
return nil
|
||||
}
|
||||
err := w.f.Close()
|
||||
w.f = nil
|
||||
return err
|
||||
}
|
||||
|
||||
// Path is the live file's path.
|
||||
func (w *Writer) Path() string { return w.path }
|
||||
|
||||
// Tail returns the last n lines of path. Reads from the end rather than
|
||||
// loading the file, so an 8 MiB log is cheap to tail.
|
||||
func Tail(path string, lines int) ([]byte, error) {
|
||||
if lines <= 0 {
|
||||
lines = 200
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
size := st.Size()
|
||||
if size == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
const chunk = 64 << 10
|
||||
var (
|
||||
buf []byte
|
||||
newlines int
|
||||
pos = size
|
||||
)
|
||||
for pos > 0 && newlines <= lines {
|
||||
readSize := int64(chunk)
|
||||
if pos < readSize {
|
||||
readSize = pos
|
||||
}
|
||||
pos -= readSize
|
||||
part := make([]byte, readSize)
|
||||
if _, err := f.ReadAt(part, pos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, b := range part {
|
||||
if b == '\n' {
|
||||
newlines++
|
||||
}
|
||||
}
|
||||
buf = append(part, buf...)
|
||||
// Guard against a single enormous line eating memory.
|
||||
if int64(len(buf)) > 8<<20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Trim to the requested number of trailing lines.
|
||||
count := 0
|
||||
for i := len(buf) - 1; i >= 0; i-- {
|
||||
if buf[i] != '\n' {
|
||||
continue
|
||||
}
|
||||
// Ignore a trailing newline at the very end of the file.
|
||||
if i == len(buf)-1 {
|
||||
continue
|
||||
}
|
||||
// The content after the Nth newline from the end is exactly N lines,
|
||||
// so stop on the Nth, not past it.
|
||||
count++
|
||||
if count == lines {
|
||||
return buf[i+1:], nil
|
||||
}
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
192
apps/streamd/internal/logfile/logfile_test.go
Normal file
192
apps/streamd/internal/logfile/logfile_test.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package logfile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRotatesAtSizeCap(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "stream-nre.log")
|
||||
w, err := Open(path, 1024, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer w.Close()
|
||||
|
||||
line := strings.Repeat("x", 100) + "\n"
|
||||
for i := 0; i < 50; i++ {
|
||||
if _, err := w.Write([]byte(line)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// The live file must stay near the cap, not grow to 5 KiB.
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Size() > 1024+int64(len(line)) {
|
||||
t.Errorf("live log is %d bytes, cap is 1024", st.Size())
|
||||
}
|
||||
// Generations exist, and no more than were asked for.
|
||||
if _, err := os.Stat(path + ".1"); err != nil {
|
||||
t.Errorf("expected a rotated generation: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path + ".3"); err == nil {
|
||||
t.Error("generation 3 should not exist with generations=3 (0,1,2)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerationCountRespected(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "x.log")
|
||||
w, err := Open(path, 200, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer w.Close()
|
||||
for i := 0; i < 40; i++ {
|
||||
_, _ = w.Write([]byte(strings.Repeat("y", 50) + "\n"))
|
||||
}
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// generations=2 means x.log and x.log.1 only.
|
||||
if len(ents) > 2 {
|
||||
var names []string
|
||||
for _, e := range ents {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Errorf("want at most 2 files, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Reopening must append, not truncate: a restart has to leave the previous
|
||||
// run's output in place, which is the whole point of this package.
|
||||
func TestReopenAppendsAndBannerMarksRuns(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "run.log")
|
||||
|
||||
w1, err := OpenWithBanner(path, 1<<20, 3, "nre")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = w1.Write([]byte("first run output\n"))
|
||||
_ = w1.Close()
|
||||
|
||||
w2, err := OpenWithBanner(path, 1<<20, 3, "nre")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = w2.Write([]byte("second run output\n"))
|
||||
_ = w2.Close()
|
||||
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := string(b)
|
||||
if !strings.Contains(body, "first run output") {
|
||||
t.Error("the previous run's output was lost — this is the O_TRUNC bug")
|
||||
}
|
||||
if !strings.Contains(body, "second run output") {
|
||||
t.Error("the new run's output is missing")
|
||||
}
|
||||
if n := strings.Count(body, "==== nre start "); n != 2 {
|
||||
t.Errorf("want 2 start banners, got %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTail(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "t.log")
|
||||
var buf bytes.Buffer
|
||||
for i := 0; i < 500; i++ {
|
||||
fmt.Fprintf(&buf, "line %d\n", i)
|
||||
}
|
||||
if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
out, err := Tail(path, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
|
||||
if len(lines) != 10 {
|
||||
t.Fatalf("want 10 lines, got %d: %q", len(lines), string(out))
|
||||
}
|
||||
if lines[9] != "line 499" {
|
||||
t.Errorf("last line = %q, want %q", lines[9], "line 499")
|
||||
}
|
||||
if lines[0] != "line 490" {
|
||||
t.Errorf("first line = %q, want %q", lines[0], "line 490")
|
||||
}
|
||||
|
||||
// Asking for more lines than exist returns the whole file.
|
||||
out, err = Tail(path, 10000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(out, buf.Bytes()) {
|
||||
t.Error("tail of a short file should return all of it")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTailEmptyAndMissing(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
empty := filepath.Join(dir, "empty.log")
|
||||
if err := os.WriteFile(empty, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := Tail(empty, 10); err != nil || len(out) != 0 {
|
||||
t.Errorf("empty file: got %q %v", out, err)
|
||||
}
|
||||
if _, err := Tail(filepath.Join(dir, "nope.log"), 10); err == nil {
|
||||
t.Error("a missing file should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAfterCloseDoesNotPanic(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "c.log")
|
||||
w, err := Open(path, 1<<20, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Close()
|
||||
if _, err := w.Write([]byte("x")); err == nil {
|
||||
t.Error("writing to a closed writer should error, not panic")
|
||||
}
|
||||
// Double close is harmless.
|
||||
if err := w.Close(); err != nil {
|
||||
t.Errorf("second Close should be a no-op, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentWrites(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "p.log")
|
||||
// An exec.Cmd gets this same writer as both Stdout and Stderr, so
|
||||
// concurrent writes are the normal case, not an edge case.
|
||||
w, err := Open(path, 4096, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer w.Close()
|
||||
done := make(chan struct{})
|
||||
for g := 0; g < 4; g++ {
|
||||
go func(g int) {
|
||||
defer func() { done <- struct{}{} }()
|
||||
for i := 0; i < 100; i++ {
|
||||
_, _ = w.Write([]byte(fmt.Sprintf("writer %d line %d\n", g, i)))
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
<-done
|
||||
}
|
||||
}
|
||||
178
apps/streamd/internal/scheduler/scheduler.go
Normal file
178
apps/streamd/internal/scheduler/scheduler.go
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
// Package scheduler starts and stops streams at planned times, so a council
|
||||
// meeting or a match can be set up in advance instead of started by hand.
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// Supervisor is the subset of the media supervisor the scheduler needs.
|
||||
type Supervisor interface {
|
||||
Start(id int64) error
|
||||
Stop(id int64) error
|
||||
Running(id int64) bool
|
||||
}
|
||||
|
||||
// CaptureRequester asks connected agents for fresh credentials now.
|
||||
type CaptureRequester interface {
|
||||
RequestCapture(st db.Stream, reason string) int
|
||||
}
|
||||
|
||||
const (
|
||||
tick = 15 * time.Second
|
||||
// DefaultPreroll is how far ahead of a scheduled start credentials are
|
||||
// refreshed. A 19:00 meeting is no use if the keys expired at noon, and a
|
||||
// phone capture takes minutes.
|
||||
DefaultPreroll = 5 * time.Minute
|
||||
)
|
||||
|
||||
type Scheduler struct {
|
||||
Store *db.Store
|
||||
Sup Supervisor
|
||||
Capture CaptureRequester
|
||||
Log *slog.Logger
|
||||
Preroll time.Duration
|
||||
}
|
||||
|
||||
func New(store *db.Store, sup Supervisor, capture CaptureRequester, lg *slog.Logger, preroll time.Duration) *Scheduler {
|
||||
if lg == nil {
|
||||
lg = slog.Default()
|
||||
}
|
||||
if preroll <= 0 {
|
||||
preroll = DefaultPreroll
|
||||
}
|
||||
return &Scheduler{Store: store, Sup: sup, Capture: capture, Log: lg, Preroll: preroll}
|
||||
}
|
||||
|
||||
// Run drives the scheduler until stop is closed.
|
||||
func (s *Scheduler) Run(stop <-chan struct{}) {
|
||||
// A server that was down over an occurrence must not fire it late; recompute
|
||||
// every next_fire_at against the current time first.
|
||||
if err := s.Store.RecomputeNextFire(); err != nil {
|
||||
s.Log.Error("recompute schedule times", "err", err)
|
||||
}
|
||||
t := time.NewTicker(tick)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-t.C:
|
||||
s.step(time.Now().UTC())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// step fires everything due and requests pre-roll captures.
|
||||
func (s *Scheduler) step(now time.Time) {
|
||||
s.preroll(now)
|
||||
|
||||
due, err := s.Store.DueSchedules(now)
|
||||
if err != nil {
|
||||
s.Log.Error("list due schedules", "err", err)
|
||||
return
|
||||
}
|
||||
for _, sc := range due {
|
||||
st, err := s.Store.GetStream(sc.StreamID)
|
||||
if err != nil {
|
||||
// The stream is gone; the schedule row went with it via the
|
||||
// foreign key, so nothing to do.
|
||||
continue
|
||||
}
|
||||
s.fire(sc, st, now)
|
||||
if err := s.Store.MarkFired(sc, now); err != nil {
|
||||
s.Log.Error("advance schedule", "schedule", sc.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) fire(sc db.Schedule, st db.Stream, now time.Time) {
|
||||
switch sc.Action {
|
||||
case db.ActionStart:
|
||||
if s.Sup.Running(st.ID) {
|
||||
s.Log.Info("scheduled start skipped: already running", "stream", st.Name)
|
||||
s.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo,
|
||||
Actor: db.ActorSystem, Message: "scheduled start: already running",
|
||||
})
|
||||
return
|
||||
}
|
||||
s.Log.Info("scheduled start", "stream", st.Name, "schedule", sc.ID)
|
||||
s.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo,
|
||||
Actor: db.ActorSystem, Message: "scheduled start",
|
||||
})
|
||||
// Enable it too, or a manual stop earlier in the day would leave the
|
||||
// scheduled event unable to come up.
|
||||
if _, err := s.Store.SetEnabled(st.ID, true); err != nil {
|
||||
s.Log.Error("scheduled enable failed", "stream", st.Name, "err", err)
|
||||
}
|
||||
if err := s.Sup.Start(st.ID); err != nil {
|
||||
s.Log.Error("scheduled start failed", "stream", st.Name, "err", err)
|
||||
s.Store.Eventf(st.ID, db.EventScheduledStart, db.SevError,
|
||||
"scheduled start failed: %v", err)
|
||||
}
|
||||
|
||||
case db.ActionStop:
|
||||
s.Log.Info("scheduled stop", "stream", st.Name, "schedule", sc.ID)
|
||||
s.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: st.ID, Kind: db.EventScheduledStop, Severity: db.SevInfo,
|
||||
Actor: db.ActorSystem, Message: "scheduled stop",
|
||||
})
|
||||
if err := s.Sup.Stop(st.ID); err != nil {
|
||||
s.Log.Error("scheduled stop failed", "stream", st.Name, "err", err)
|
||||
}
|
||||
if _, err := s.Store.SetEnabled(st.ID, false); err != nil {
|
||||
s.Log.Error("scheduled disable failed", "stream", st.Name, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// preroll asks for fresh credentials shortly before a scheduled start, so the
|
||||
// event does not begin with a capture still in flight.
|
||||
func (s *Scheduler) preroll(now time.Time) {
|
||||
if s.Capture == nil {
|
||||
return
|
||||
}
|
||||
pending, err := s.Store.PendingPreroll(now, s.Preroll)
|
||||
if err != nil {
|
||||
s.Log.Error("list pre-roll schedules", "err", err)
|
||||
return
|
||||
}
|
||||
for _, sc := range pending {
|
||||
st, err := s.Store.GetStream(sc.StreamID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// Mark it either way: a stream with good credentials needs no capture,
|
||||
// and re-checking it every 15s until the event would be pointless.
|
||||
_ = s.Store.MarkPrerolled(sc.ID, sc.NextFireAt)
|
||||
if !st.NeedsCapture {
|
||||
continue
|
||||
}
|
||||
if n := s.Capture.RequestCapture(st, "schedule_preroll"); n > 0 {
|
||||
s.Log.Info("pre-roll capture requested",
|
||||
"stream", st.Name, "fires_at", sc.NextFireAt, "agents", n)
|
||||
s.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo,
|
||||
"pre-roll: asked %d agent(s) for fresh credentials before the scheduled start", n)
|
||||
} else {
|
||||
s.Log.Warn("pre-roll needed but no agent is connected",
|
||||
"stream", st.Name, "fires_at", sc.NextFireAt)
|
||||
s.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn,
|
||||
"pre-roll: credentials are stale and no agent is connected")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Upcoming is the dashboard's view of what is scheduled next. It returns `any`
|
||||
// to keep the api package free of a dependency on this one.
|
||||
func (s *Scheduler) Upcoming(limit int) any {
|
||||
list, err := s.Store.UpcomingSchedules(limit)
|
||||
if err != nil {
|
||||
return []db.Schedule{}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
|
@ -9,15 +9,19 @@ import (
|
|||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// streamSettings are the downloader knobs for one stream. They come from the
|
||||
// stream's app module when it declares them, so the supervisor never has to
|
||||
// guess from an app name or a stream name.
|
||||
// streamSettings are the downloader and packager knobs for one stream. They
|
||||
// come from the stream row first, then the stream's app module, then the
|
||||
// installation-wide settings, then neutral defaults — so the supervisor never
|
||||
// has to guess from an app name or a stream name.
|
||||
type streamSettings struct {
|
||||
VideoSelect string
|
||||
AudioSelect string
|
||||
Rewriter string
|
||||
LiveWait int
|
||||
TSReadyBytes int64
|
||||
// HLSTime and HLSListSize shape every output's segmenting.
|
||||
HLSTime int
|
||||
HLSListSize int
|
||||
// IsHLS drives packaging choices that depend on the manifest format.
|
||||
IsHLS bool
|
||||
}
|
||||
|
|
@ -31,15 +35,20 @@ const (
|
|||
hlsLiveWait = 6
|
||||
)
|
||||
|
||||
// settingsFor resolves a stream's downloader settings: the app module's
|
||||
// declarations first, then the stream row, then neutral defaults.
|
||||
func settingsFor(st db.Stream) streamSettings {
|
||||
// settingsFor resolves a stream's settings. globals is the installation-wide
|
||||
// layer, read from the settings table; pass the zero value when there is none.
|
||||
func settingsFor(st db.Stream, globals db.PackagerSettings) streamSettings {
|
||||
// Per-stream overrides win over everything.
|
||||
own := db.ParsePackagerSettings(st.SettingsJSON)
|
||||
|
||||
s := streamSettings{
|
||||
VideoSelect: strings.TrimSpace(st.VideoSelect),
|
||||
AudioSelect: strings.TrimSpace(st.AudioSelect),
|
||||
Rewriter: strings.TrimSpace(st.Rewriter),
|
||||
LiveWait: defaultLiveWait,
|
||||
TSReadyBytes: defaultTSReadyBytes,
|
||||
LiveWait: own.LiveWait,
|
||||
TSReadyBytes: int64(own.TSReadyBytes),
|
||||
HLSTime: own.HLSTime,
|
||||
HLSListSize: own.HLSListSize,
|
||||
IsHLS: isHLS(st),
|
||||
}
|
||||
if sd := streamDefaultsFor(st.App); sd != nil {
|
||||
|
|
@ -52,21 +61,53 @@ func settingsFor(st db.Stream) streamSettings {
|
|||
if s.Rewriter == "" {
|
||||
s.Rewriter = sd.RewriterName()
|
||||
}
|
||||
if n := sd.LiveWaitSeconds(); n > 0 {
|
||||
s.LiveWait = n
|
||||
if s.LiveWait == 0 {
|
||||
if n := sd.LiveWaitSeconds(); n > 0 {
|
||||
s.LiveWait = n
|
||||
}
|
||||
}
|
||||
if n := sd.TSReadyBytes(); n > 0 {
|
||||
s.TSReadyBytes = n
|
||||
if s.TSReadyBytes == 0 {
|
||||
if n := sd.TSReadyBytes(); n > 0 {
|
||||
s.TSReadyBytes = n
|
||||
}
|
||||
}
|
||||
}
|
||||
// Installation-wide settings.
|
||||
if s.LiveWait == 0 {
|
||||
s.LiveWait = globals.LiveWait
|
||||
}
|
||||
if s.TSReadyBytes == 0 {
|
||||
s.TSReadyBytes = int64(globals.TSReadyBytes)
|
||||
}
|
||||
if s.HLSTime == 0 {
|
||||
s.HLSTime = globals.HLSTime
|
||||
}
|
||||
if s.HLSListSize == 0 {
|
||||
s.HLSListSize = globals.HLSListSize
|
||||
}
|
||||
// An HLS source needs a longer wait and a bigger buffer before probing,
|
||||
// but only when nothing more specific asked otherwise.
|
||||
if s.IsHLS {
|
||||
if s.LiveWait == defaultLiveWait {
|
||||
if s.LiveWait == 0 {
|
||||
s.LiveWait = hlsLiveWait
|
||||
}
|
||||
if s.TSReadyBytes == defaultTSReadyBytes {
|
||||
if s.TSReadyBytes == 0 {
|
||||
s.TSReadyBytes = hlsTSReadyBytes
|
||||
}
|
||||
}
|
||||
// Neutral defaults.
|
||||
if s.LiveWait == 0 {
|
||||
s.LiveWait = defaultLiveWait
|
||||
}
|
||||
if s.TSReadyBytes == 0 {
|
||||
s.TSReadyBytes = defaultTSReadyBytes
|
||||
}
|
||||
if s.HLSTime == 0 {
|
||||
s.HLSTime = defaultHLSTime
|
||||
}
|
||||
if s.HLSListSize == 0 {
|
||||
s.HLSListSize = defaultHLSListSize
|
||||
}
|
||||
if s.VideoSelect == "" {
|
||||
s.VideoSelect = "for=best"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ func register(t *testing.T, f *fakeApp) {
|
|||
|
||||
func TestSettingsComeFromTheAppModule(t *testing.T) {
|
||||
register(t, &fakeApp{name: "fakedash", rewriter: "fakedash", liveWait: 3, tsBytes: 111})
|
||||
got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"})
|
||||
got := settingsFor(db.Stream{App: "fakedash", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
|
||||
if got.Rewriter != "fakedash" {
|
||||
t.Errorf("rewriter = %q, want fakedash", got.Rewriter)
|
||||
}
|
||||
|
|
@ -67,7 +67,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
|
|||
MPD: "https://origin.test/manifest.mpd",
|
||||
VideoSelect: "res=1920x1080:for=best",
|
||||
Rewriter: "none",
|
||||
})
|
||||
}, db.PackagerSettings{})
|
||||
if got.VideoSelect != "res=1920x1080:for=best" {
|
||||
t.Errorf("video select = %q, want the stored value", got.VideoSelect)
|
||||
}
|
||||
|
|
@ -78,7 +78,7 @@ func TestStoredSettingsOverrideTheModule(t *testing.T) {
|
|||
|
||||
// An unknown app must not inherit any provider's preferences.
|
||||
func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
|
||||
got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"})
|
||||
got := settingsFor(db.Stream{App: "nosuchapp", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
|
||||
if got.VideoSelect != "for=best" || got.AudioSelect != "for=best" {
|
||||
t.Errorf("selectors = %q / %q, want for=best", got.VideoSelect, got.AudioSelect)
|
||||
}
|
||||
|
|
@ -93,7 +93,7 @@ func TestUnknownAppGetsNeutralDefaults(t *testing.T) {
|
|||
// HLS gets more buffering and a longer live wait, by manifest shape and not by
|
||||
// matching a stream name.
|
||||
func TestHLSDetectionByManifestShape(t *testing.T) {
|
||||
got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"})
|
||||
got := settingsFor(db.Stream{App: "", MPD: "https://cdn.test/x/playlist-hls-dvr.m3u8"}, db.PackagerSettings{})
|
||||
if !got.IsHLS {
|
||||
t.Fatal("an .m3u8 manifest should be detected as HLS")
|
||||
}
|
||||
|
|
@ -104,7 +104,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
|
|||
t.Errorf("tsReadyBytes = %d, want %d", got.TSReadyBytes, hlsTSReadyBytes)
|
||||
}
|
||||
// The old code keyed this off stream names like "tg4"/"cula"/"plus".
|
||||
named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"})
|
||||
named := settingsFor(db.Stream{Name: "tg4-ioi", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
|
||||
if named.TSReadyBytes != defaultTSReadyBytes {
|
||||
t.Error("buffering must not be chosen by stream name any more")
|
||||
}
|
||||
|
|
@ -113,7 +113,7 @@ func TestHLSDetectionByManifestShape(t *testing.T) {
|
|||
// A module's rewriter is only used if it registered one under that name.
|
||||
func TestRewriterLookupGatesTheRewrite(t *testing.T) {
|
||||
register(t, &fakeApp{name: "fakeunregistered", rewriter: "fakeunregistered"})
|
||||
cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"})
|
||||
cfg := settingsFor(db.Stream{App: "fakeunregistered", MPD: "https://origin.test/manifest.mpd"}, db.PackagerSettings{})
|
||||
if _, needed := mpd.Lookup(cfg.Rewriter); needed {
|
||||
t.Error("an unregistered rewriter name must not trigger a rewrite")
|
||||
}
|
||||
|
|
@ -127,3 +127,63 @@ type stubRewriter struct{}
|
|||
|
||||
func (stubRewriter) Name() string { return "fakeunregistered" }
|
||||
func (stubRewriter) Rewrite(in []byte, _ string) ([]byte, error) { return in, nil }
|
||||
|
||||
// The resolution chain is: stream row, then app module, then the
|
||||
// installation-wide settings, then the compiled-in defaults.
|
||||
func TestGlobalSettingsSitBelowTheModule(t *testing.T) {
|
||||
globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9, TSReadyBytes: 999}
|
||||
|
||||
// Nothing more specific: the global layer applies.
|
||||
got := settingsFor(db.Stream{MPD: "https://origin.test/manifest.mpd"}, globals)
|
||||
if got.HLSTime != 6 || got.HLSListSize != 30 {
|
||||
t.Errorf("hls_time=%d list_size=%d, want the global values", got.HLSTime, got.HLSListSize)
|
||||
}
|
||||
if got.LiveWait != 9 || got.TSReadyBytes != 999 {
|
||||
t.Errorf("liveWait=%d tsReady=%d, want the global values", got.LiveWait, got.TSReadyBytes)
|
||||
}
|
||||
|
||||
// A module declaration beats the global layer.
|
||||
register(t, &fakeApp{name: "fakeglobals", rewriter: "none", liveWait: 4, tsBytes: 222})
|
||||
got = settingsFor(db.Stream{App: "fakeglobals", MPD: "https://origin.test/manifest.mpd"}, globals)
|
||||
if got.LiveWait != 4 || got.TSReadyBytes != 222 {
|
||||
t.Errorf("liveWait=%d tsReady=%d, want the module values", got.LiveWait, got.TSReadyBytes)
|
||||
}
|
||||
// ...but the global packager knobs still apply, since no module declares them.
|
||||
if got.HLSTime != 6 {
|
||||
t.Errorf("hls_time = %d, want the global 6", got.HLSTime)
|
||||
}
|
||||
}
|
||||
|
||||
// A per-stream settings_json override beats everything else.
|
||||
func TestPerStreamSettingsWinOverAllLayers(t *testing.T) {
|
||||
register(t, &fakeApp{name: "fakeperstream", rewriter: "none", liveWait: 4, tsBytes: 222})
|
||||
globals := db.PackagerSettings{HLSTime: 6, HLSListSize: 30, LiveWait: 9}
|
||||
got := settingsFor(db.Stream{
|
||||
App: "fakeperstream",
|
||||
MPD: "https://origin.test/manifest.mpd",
|
||||
SettingsJSON: `{"hls_time":2,"hls_list_size":8,"live_wait":1}`,
|
||||
}, globals)
|
||||
if got.HLSTime != 2 || got.HLSListSize != 8 || got.LiveWait != 1 {
|
||||
t.Errorf("got hls_time=%d list_size=%d live_wait=%d, want the per-stream 2/8/1",
|
||||
got.HLSTime, got.HLSListSize, got.LiveWait)
|
||||
}
|
||||
}
|
||||
|
||||
// Nonsense in settings_json must be ignored rather than handed to ffmpeg,
|
||||
// where a zero segment duration would produce an unplayable stream.
|
||||
func TestInsaneSettingsAreIgnored(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
`{"hls_time":0}`, `{"hls_time":-5}`, `{"hls_time":9999}`,
|
||||
`{"hls_list_size":0}`, `not json at all`, ``,
|
||||
} {
|
||||
got := settingsFor(db.Stream{
|
||||
MPD: "https://origin.test/manifest.mpd", SettingsJSON: raw,
|
||||
}, db.PackagerSettings{})
|
||||
if got.HLSTime != defaultHLSTime {
|
||||
t.Errorf("settings_json %q gave hls_time=%d, want the default %d", raw, got.HLSTime, defaultHLSTime)
|
||||
}
|
||||
if got.HLSListSize != defaultHLSListSize {
|
||||
t.Errorf("settings_json %q gave list_size=%d, want the default %d", raw, got.HLSListSize, defaultHLSListSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
218
apps/streamd/internal/supervisor/ffmpeg_integration_test.go
Normal file
218
apps/streamd/internal/supervisor/ffmpeg_integration_test.go
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
package supervisor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// These tests run the real ffmpeg against the real generated command line.
|
||||
// The unit tests prove the arguments look right; only ffmpeg can prove it
|
||||
// accepts them — tee's escaping rules in particular are easy to get subtly
|
||||
// wrong in a way no amount of string assertion would catch.
|
||||
//
|
||||
// Skipped when ffmpeg is not installed, and under -short.
|
||||
|
||||
func ffmpegPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
if testing.Short() {
|
||||
t.Skip("skipping ffmpeg integration test in short mode")
|
||||
}
|
||||
for _, cand := range []string{os.Getenv("FFMPEG_PATH"), "ffmpeg"} {
|
||||
if cand == "" {
|
||||
continue
|
||||
}
|
||||
if p, err := exec.LookPath(cand); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
t.Skip("ffmpeg not found on PATH; skipping integration test")
|
||||
return ""
|
||||
}
|
||||
|
||||
// makeTestTS renders a few seconds of synthetic audio and video to an MPEG-TS
|
||||
// file, standing in for what the downloader produces.
|
||||
func makeTestTS(t *testing.T, ff, dir string, seconds int) string {
|
||||
t.Helper()
|
||||
out := filepath.Join(dir, "source.ts")
|
||||
cmd := exec.Command(ff,
|
||||
"-hide_banner", "-loglevel", "error", "-y",
|
||||
"-f", "lavfi", "-i", "testsrc2=size=640x360:rate=25",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
|
||||
"-t", strconv.Itoa(seconds),
|
||||
"-c:v", "libx264", "-preset", "ultrafast", "-g", "25", "-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-b:a", "96k",
|
||||
"-f", "mpegts", out,
|
||||
)
|
||||
if b, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Skipf("could not render a test source (%v): %s", err, b)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// runPlan runs one variant's full generated command against src and returns
|
||||
// the process's CPU time.
|
||||
func runPlan(t *testing.T, ff, src, wwwDir string, spec db.VariantSpec, outputs []db.OutputSpec) (time.Duration, string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(wwwDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := streamSettings{HLSTime: 2, HLSListSize: 5}
|
||||
plan := buildOutputPlan(outputs, wwwDir, cfg, spec)
|
||||
for _, d := range plan.Dirs {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// The real supervisor passes "-follow 1" to track a growing file; here the
|
||||
// source is complete, so read it once and exit.
|
||||
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-i", src}
|
||||
args = append(args, variantCodecArgs(spec)...)
|
||||
args = append(args, plan.Args...)
|
||||
|
||||
cmd := exec.Command(ff, args...)
|
||||
// Capture stderr explicitly rather than with CombinedOutput: when the TS
|
||||
// output is on, stdout carries media and cannot also collect diagnostics.
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if plan.WantsTS {
|
||||
sink, err := os.Create(filepath.Join(wwwDir, "pipe.ts"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sink.Close()
|
||||
cmd.Stdout = sink
|
||||
}
|
||||
err := cmd.Run()
|
||||
out := stderr.String()
|
||||
if err != nil {
|
||||
t.Fatalf("ffmpeg rejected the generated command: %v\nargs: %q\nstderr: %s", err, args, out)
|
||||
}
|
||||
var cpu time.Duration
|
||||
if cmd.ProcessState != nil {
|
||||
cpu = cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime()
|
||||
}
|
||||
return cpu, out
|
||||
}
|
||||
|
||||
// A single HLS output must work: this is the command streamd has always run.
|
||||
func TestFFmpegAcceptsSingleHLSOutput(t *testing.T) {
|
||||
ff := ffmpegPath(t)
|
||||
dir := t.TempDir()
|
||||
src := makeTestTS(t, ff, dir, 4)
|
||||
www := filepath.Join(dir, "www", "news")
|
||||
_, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
})
|
||||
mustExist(t, filepath.Join(www, "index.m3u8"))
|
||||
mustGlob(t, filepath.Join(www, "seg_*.ts"))
|
||||
}
|
||||
|
||||
// The real test of the tee spec: ffmpeg must accept it and every output must
|
||||
// actually be written.
|
||||
func TestFFmpegAcceptsTeeWithEveryFormat(t *testing.T) {
|
||||
ff := ffmpegPath(t)
|
||||
dir := t.TempDir()
|
||||
src := makeTestTS(t, ff, dir, 4)
|
||||
www := filepath.Join(dir, "www", "news")
|
||||
_, out := runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
{ID: "ts", Format: db.FormatTS, Enabled: true},
|
||||
})
|
||||
// onfail=ignore means a broken leg is silent, so check the files rather
|
||||
// than trusting the exit status.
|
||||
mustExist(t, filepath.Join(www, "index.m3u8"))
|
||||
mustGlob(t, filepath.Join(www, "seg_*.ts"))
|
||||
mustExist(t, filepath.Join(www, "cmaf", "index.m3u8"))
|
||||
mustGlob(t, filepath.Join(www, "cmaf", "*.m4s"))
|
||||
mustExist(t, filepath.Join(www, "cmaf", "init.mp4"))
|
||||
mustExist(t, filepath.Join(www, "dash", "index.mpd"))
|
||||
mustNonEmpty(t, filepath.Join(www, "pipe.ts"))
|
||||
if strings.Contains(strings.ToLower(out), "invalid argument") {
|
||||
t.Errorf("ffmpeg complained about the tee spec: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A path with a drive letter and a space is where tee escaping actually bites.
|
||||
func TestFFmpegAcceptsTeeWithAwkwardPath(t *testing.T) {
|
||||
ff := ffmpegPath(t)
|
||||
dir := t.TempDir()
|
||||
src := makeTestTS(t, ff, dir, 3)
|
||||
// A space in a directory name, which is ordinary on Windows.
|
||||
www := filepath.Join(dir, "www root", "city news")
|
||||
_, _ = runPlan(t, ff, src, www, sourceSpecForTest(), []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
})
|
||||
mustExist(t, filepath.Join(www, "index.m3u8"))
|
||||
mustExist(t, filepath.Join(www, "dash", "index.mpd"))
|
||||
}
|
||||
|
||||
// The headline efficiency claim: adding formats to a transcoded rung must
|
||||
// share one encode. Three formats through tee should cost far less than three
|
||||
// times a single format — if it is ~3x, the encoder is running per output.
|
||||
func TestTeeEncodesOnceNotPerOutput(t *testing.T) {
|
||||
ff := ffmpegPath(t)
|
||||
dir := t.TempDir()
|
||||
// Long enough that encoding dominates process start-up cost.
|
||||
src := makeTestTS(t, ff, dir, 8)
|
||||
hd := db.VariantSpec{ID: "hd", Label: "HD", Enabled: true, Height: 720,
|
||||
VideoBitrate: "2800k", AudioBitrate: "128k"}
|
||||
|
||||
oneCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "one"), hd, []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
})
|
||||
threeCPU, _ := runPlan(t, ff, src, filepath.Join(dir, "three"), hd, []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
})
|
||||
if oneCPU <= 0 || threeCPU <= 0 {
|
||||
t.Skipf("no CPU accounting available (one=%v three=%v)", oneCPU, threeCPU)
|
||||
}
|
||||
ratio := float64(threeCPU) / float64(oneCPU)
|
||||
t.Logf("CPU: 1 format = %v, 3 formats = %v (ratio %.2fx)", oneCPU, threeCPU, ratio)
|
||||
// Muxing three times instead of once is not free, but it is nothing like
|
||||
// encoding three times. Anything approaching 3x means tee is not in use.
|
||||
if ratio > 2.0 {
|
||||
t.Errorf("3 formats cost %.2fx the CPU of 1 — the encoder appears to be running "+
|
||||
"per output rather than once through tee", ratio)
|
||||
}
|
||||
}
|
||||
|
||||
func mustExist(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Errorf("expected %s to exist: %v", path, err)
|
||||
return
|
||||
}
|
||||
if st.Size() == 0 {
|
||||
t.Errorf("%s is empty", path)
|
||||
}
|
||||
}
|
||||
|
||||
func mustNonEmpty(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
st, err := os.Stat(path)
|
||||
if err != nil || st.Size() == 0 {
|
||||
t.Errorf("expected %s to have content (err=%v)", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustGlob(t *testing.T, pattern string) {
|
||||
t.Helper()
|
||||
m, err := filepath.Glob(pattern)
|
||||
if err != nil || len(m) == 0 {
|
||||
t.Errorf("expected files matching %s (err=%v)", pattern, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
|
@ -15,45 +15,69 @@ import (
|
|||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// Media runs N_m3u8DL-RE + ffmpeg HLS packager per stream into DataDir/www/<name>/.
|
||||
// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
|
||||
// DataDir/www/<name>/ and, when the progressive TS output is on, into a
|
||||
// shared in-memory ring.
|
||||
type Media struct {
|
||||
Store *db.Store
|
||||
DataDir string
|
||||
NRE string
|
||||
FFmpeg string
|
||||
MP4Decrypt string
|
||||
Log *log.Logger
|
||||
Log *slog.Logger
|
||||
// Fanout holds the live progressive-TS rings, when that output is on.
|
||||
Fanout *tsfanout.Set
|
||||
// Notifier pushes health changes to the dashboard. Optional.
|
||||
Notifier Notifier
|
||||
// ViewersFn reports the live client count for a stream, for the metrics
|
||||
// series. Optional.
|
||||
ViewersFn func(streamName string) int
|
||||
|
||||
mu sync.Mutex
|
||||
procs map[int64]*streamProc
|
||||
stopMon chan struct{}
|
||||
}
|
||||
|
||||
// Notifier is the subset of the websocket hub the supervisor needs.
|
||||
type Notifier interface {
|
||||
NotifyRuntime(name, health string)
|
||||
NotifyStreamChanged(name, reason string)
|
||||
}
|
||||
|
||||
type streamProc struct {
|
||||
id int64
|
||||
name string
|
||||
nre *exec.Cmd
|
||||
ffmpeg *exec.Cmd
|
||||
started time.Time
|
||||
workDir string
|
||||
wwwDir string
|
||||
tsPath string
|
||||
hlsIndex string
|
||||
nreLog *os.File
|
||||
ffOutLog *os.File
|
||||
ffErrLog *os.File
|
||||
stopping bool
|
||||
mpdProxy *mpd.LocalServer
|
||||
nreDead bool
|
||||
ffDead bool
|
||||
variants []*variantProc
|
||||
id int64
|
||||
name string
|
||||
nre *exec.Cmd
|
||||
ffmpeg *exec.Cmd
|
||||
started time.Time
|
||||
workDir string
|
||||
wwwDir string
|
||||
tsPath string
|
||||
hlsIndex string
|
||||
nreLog *logfile.Writer
|
||||
ffOutLog *logfile.Writer
|
||||
ffErrLog *logfile.Writer
|
||||
stopping bool
|
||||
mpdProxy *mpd.LocalServer
|
||||
nreDead bool
|
||||
ffDead bool
|
||||
variants []*variantProc
|
||||
variantSpecs []db.VariantSpec
|
||||
outputSpecs []db.OutputSpec
|
||||
cfg streamSettings
|
||||
// tsReadyBytes is how much muxed output to buffer before probing, from the
|
||||
// stream's app module.
|
||||
tsReadyBytes int64
|
||||
// lastHealth lets the supervisor report only health transitions.
|
||||
lastHealth string
|
||||
// lastTSSize / lastTSAt back the bitrate estimate.
|
||||
lastTSSize int64
|
||||
lastTSAt time.Time
|
||||
}
|
||||
|
||||
// Options for constructing the media supervisor.
|
||||
|
|
@ -63,13 +87,20 @@ type Options struct {
|
|||
NRE string
|
||||
FFmpeg string
|
||||
MP4Decrypt string
|
||||
Log *log.Logger
|
||||
Log *slog.Logger
|
||||
Fanout *tsfanout.Set
|
||||
Notifier Notifier
|
||||
ViewersFn func(streamName string) int
|
||||
}
|
||||
|
||||
func NewMedia(opt Options) *Media {
|
||||
lg := opt.Log
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
lg = slog.Default()
|
||||
}
|
||||
fan := opt.Fanout
|
||||
if fan == nil {
|
||||
fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
|
||||
}
|
||||
m := &Media{
|
||||
Store: opt.Store,
|
||||
|
|
@ -78,6 +109,9 @@ func NewMedia(opt Options) *Media {
|
|||
FFmpeg: opt.FFmpeg,
|
||||
MP4Decrypt: opt.MP4Decrypt,
|
||||
Log: lg,
|
||||
Fanout: fan,
|
||||
Notifier: opt.Notifier,
|
||||
ViewersFn: opt.ViewersFn,
|
||||
procs: map[int64]*streamProc{},
|
||||
stopMon: make(chan struct{}),
|
||||
}
|
||||
|
|
@ -98,34 +132,33 @@ func (m *Media) Close() {
|
|||
}
|
||||
}
|
||||
|
||||
// Running reports whether a stream currently has a live worker. The HLS gate
|
||||
// uses this to decide whether a request needs to wake the stream.
|
||||
func (m *Media) Running(id int64) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
sp, ok := m.procs[id]
|
||||
return ok && !sp.stopping
|
||||
}
|
||||
|
||||
func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
|
||||
|
||||
func (m *Media) Start(id int64) error {
|
||||
st, err := m.Store.GetStream(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(st.MPD) == "" {
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "down",
|
||||
PlayPath: "/hls/" + st.Name + "/index.m3u8",
|
||||
LastError: "missing mpd — paste a manifest URL (keys optional for clear streams)",
|
||||
})
|
||||
m.fail(id, st.Name, "missing mpd — paste a manifest URL (keys optional for clear streams)")
|
||||
return fmt.Errorf("missing mpd")
|
||||
}
|
||||
mpdURL := strings.TrimSpace(st.MPD)
|
||||
if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") {
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "down",
|
||||
PlayPath: "/hls/" + st.Name + "/index.m3u8",
|
||||
LastError: "mpd must be an http(s) URL",
|
||||
})
|
||||
m.fail(id, st.Name, "mpd must be an http(s) URL")
|
||||
return fmt.Errorf("invalid mpd url")
|
||||
}
|
||||
if m.NRE == "" || m.FFmpeg == "" {
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "down",
|
||||
PlayPath: "/hls/" + st.Name + "/index.m3u8",
|
||||
LastError: "NRE or ffmpeg binary not configured",
|
||||
})
|
||||
m.fail(id, st.Name, "NRE or ffmpeg binary not configured")
|
||||
return fmt.Errorf("NRE or ffmpeg not configured")
|
||||
}
|
||||
|
||||
|
|
@ -144,13 +177,14 @@ func (m *Media) Start(id int64) error {
|
|||
workDir := filepath.Join(m.DataDir, "work", st.Name)
|
||||
wwwDir := filepath.Join(m.DataDir, "www", st.Name)
|
||||
variantSpecs := db.ParseVariantsJSON(st.VariantsJSON)
|
||||
outputSpecs := db.ParseOutputsJSON(st.OutputsJSON)
|
||||
// Fresh dirs each start — leftover decrypted segments make NRE File.Move fail.
|
||||
_ = os.RemoveAll(wwwDir)
|
||||
_ = os.RemoveAll(workDir)
|
||||
for _, v := range db.ScaledVariants(variantSpecs) {
|
||||
_ = os.RemoveAll(filepath.Join(m.DataDir, "www", st.Name+"-"+v.ID))
|
||||
_ = os.RemoveAll(filepath.Join(m.DataDir, "www", db.VariantDir(st.Name, v.ID, v.Height, v.AudioOnly)))
|
||||
}
|
||||
for _, d := range []string{workDir, wwwDir, filepath.Join(m.DataDir, "logs")} {
|
||||
for _, d := range []string{workDir, wwwDir, m.logsDir()} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -160,39 +194,34 @@ func (m *Media) Start(id int64) error {
|
|||
hasKeys := strings.TrimSpace(st.Key) != ""
|
||||
if hasKeys {
|
||||
keysBody := normalizeKeysFile(st.Key)
|
||||
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
|
||||
// 0600: this file holds the content keys.
|
||||
if err := os.WriteFile(keysFile, []byte(keysBody), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
saveName := st.Name
|
||||
tsPath := filepath.Join(workDir, saveName+".ts")
|
||||
_ = os.Remove(tsPath)
|
||||
|
||||
headers := headerMap(st.HeadersJSON)
|
||||
cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
|
||||
manifestURL := st.MPD
|
||||
cfg := settingsFor(st)
|
||||
var mpdProxy *mpd.LocalServer
|
||||
// The rewriter is named by the stream row or its app module and looked up in
|
||||
// the mpd registry, so streamd needs no knowledge of any provider.
|
||||
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
|
||||
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
|
||||
if err != nil {
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8",
|
||||
LastError: "mpd rewrite server: " + err.Error(),
|
||||
})
|
||||
m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
|
||||
return err
|
||||
}
|
||||
mpdProxy = srv
|
||||
manifestURL = srv.URL
|
||||
m.logf("stream %s: rewritten MPD %s", st.Name, manifestURL)
|
||||
m.Log.Info("rewritten MPD in use", "stream", st.Name, "url", manifestURL)
|
||||
}
|
||||
|
||||
// Ad-stitched manifest rewrite + live pipe mux.
|
||||
nreTmp := filepath.Join(workDir, "nre")
|
||||
_ = os.MkdirAll(nreTmp, 0o755)
|
||||
tsPath = filepath.Join(nreTmp, saveName+".ts")
|
||||
tsPath := filepath.Join(nreTmp, saveName+".ts")
|
||||
_ = os.Remove(tsPath)
|
||||
|
||||
liveWait := strconv.Itoa(cfg.LiveWait)
|
||||
|
|
@ -219,8 +248,9 @@ func (m *Media) Start(id int64) error {
|
|||
}
|
||||
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
|
||||
// NRE prefers --custom-proxy over the system proxy when both are set.
|
||||
// The proxy may carry credentials, so it is not logged.
|
||||
nreArgs = append(nreArgs, "--custom-proxy", proxy)
|
||||
m.logf("stream %s: origin proxy %s", st.Name, proxy)
|
||||
m.Log.Info("origin proxy in use", "stream", st.Name)
|
||||
}
|
||||
// A synthetic manifest publishes exactly one video + audio pair, and an HLS
|
||||
// master's variants rarely match a resolution/language filter, so in both
|
||||
|
|
@ -242,10 +272,13 @@ func (m *Media) Start(id int64) error {
|
|||
nreArgs = append(nreArgs, "-H", h)
|
||||
}
|
||||
}
|
||||
_ = keysFile // kept on disk for debugging
|
||||
|
||||
nreLogPath := filepath.Join(m.DataDir, "logs", st.Name+"-nre.log")
|
||||
nreLog, err := os.OpenFile(nreLogPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
||||
// A rotating log opened with a start banner, rather than truncated. The
|
||||
// previous run's output is exactly what you need when working out why
|
||||
// this run is happening.
|
||||
nreLog, err := logfile.OpenWithBanner(
|
||||
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
|
||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -278,10 +311,10 @@ func (m *Media) Start(id int64) error {
|
|||
if mpdProxy != nil {
|
||||
mpdProxy.Close()
|
||||
}
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "down", LastError: err.Error(), PlayPath: "/hls/" + st.Name + "/index.m3u8"})
|
||||
m.fail(id, st.Name, err.Error())
|
||||
return err
|
||||
}
|
||||
m.logf("stream %s: NRE pid=%d", st.Name, nreCmd.Process.Pid)
|
||||
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
|
||||
|
||||
sp := &streamProc{
|
||||
id: id,
|
||||
|
|
@ -296,6 +329,8 @@ func (m *Media) Start(id int64) error {
|
|||
mpdProxy: mpdProxy,
|
||||
|
||||
variantSpecs: variantSpecs,
|
||||
outputSpecs: outputSpecs,
|
||||
cfg: cfg,
|
||||
tsReadyBytes: cfg.TSReadyBytes,
|
||||
}
|
||||
|
||||
|
|
@ -303,6 +338,12 @@ func (m *Media) Start(id int64) error {
|
|||
m.procs[id] = sp
|
||||
m.mu.Unlock()
|
||||
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id, Kind: db.EventStarted, Severity: db.SevInfo,
|
||||
Message: fmt.Sprintf("downloader started (pid %d), publishing %s",
|
||||
nreCmd.Process.Pid, outputSummary(outputSpecs)),
|
||||
})
|
||||
|
||||
go func() {
|
||||
_ = nreCmd.Wait()
|
||||
m.mu.Lock()
|
||||
|
|
@ -316,6 +357,34 @@ func (m *Media) Start(id int64) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// fail records a start-up failure in one place: runtime row, timeline, log and
|
||||
// dashboard push.
|
||||
func (m *Media) fail(id int64, name, msg string) {
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "down",
|
||||
PlayPath: "/hls/" + name + "/index.m3u8",
|
||||
LastError: msg,
|
||||
})
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError, Message: msg,
|
||||
})
|
||||
m.Log.Error("stream failed to start", "stream", name, "err", msg)
|
||||
if m.Notifier != nil {
|
||||
m.Notifier.NotifyRuntime(name, "down")
|
||||
}
|
||||
}
|
||||
|
||||
func outputSummary(outputs []db.OutputSpec) string {
|
||||
var on []string
|
||||
for _, o := range db.EnabledOutputs(outputs) {
|
||||
on = append(on, o.Label)
|
||||
}
|
||||
if len(on) == 0 {
|
||||
return "nothing"
|
||||
}
|
||||
return strings.Join(on, "+")
|
||||
}
|
||||
|
||||
func (m *Media) bootstrapHLS(sp *streamProc) {
|
||||
deadline := time.Now().Add(3 * time.Minute)
|
||||
nreDir := filepath.Dir(sp.tsPath)
|
||||
|
|
@ -344,6 +413,10 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
|||
PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
||||
LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
|
||||
})
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
|
||||
})
|
||||
m.cleanupProc(sp.id)
|
||||
return
|
||||
}
|
||||
|
|
@ -355,17 +428,26 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
|||
PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
||||
LastError: "timed out waiting for growing TS",
|
||||
})
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: "timed out waiting for the downloader to produce media",
|
||||
})
|
||||
_ = m.Stop(sp.id)
|
||||
return
|
||||
}
|
||||
|
||||
if err := m.startFFmpegHLS(sp); err != nil {
|
||||
if err := m.startPackager(sp); err != nil {
|
||||
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
|
||||
Health: "down", LastError: err.Error(), PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
||||
})
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: "packager failed to start: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
m.startVariantPackagers(sp, sp.variantSpecs)
|
||||
m.writeMasterPlaylist(sp)
|
||||
pid := int64(0)
|
||||
if sp.nre != nil && sp.nre.Process != nil {
|
||||
pid = int64(sp.nre.Process.Pid)
|
||||
|
|
@ -377,46 +459,67 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
|||
})
|
||||
}
|
||||
|
||||
func (m *Media) startFFmpegHLS(sp *streamProc) error {
|
||||
ffOut := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.out.log")
|
||||
ffErr := filepath.Join(m.DataDir, "logs", sp.name+"-ffmpeg.err.log")
|
||||
outF, err := os.OpenFile(ffOut, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
// startPackager runs the ffmpeg that publishes the source rung's outputs.
|
||||
// The source rung is a stream copy, so additional output formats here are
|
||||
// nearly free; the tee muxer still keeps it to one process.
|
||||
func (m *Media) startPackager(sp *streamProc) error {
|
||||
sourceSpec := db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
|
||||
plan := buildOutputPlan(sp.outputSpecs, sp.wwwDir, sp.cfg, sourceSpec)
|
||||
// ffmpeg will not create an output's directory, and under tee's
|
||||
// onfail=ignore a missing one fails that output silently.
|
||||
for _, d := range plan.Dirs {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
args := append(inputArgs(sp.tsPath), variantCodecArgs(sourceSpec)...)
|
||||
args = append(args, plan.Args...)
|
||||
|
||||
errLog, err := logfile.OpenWithBanner(
|
||||
filepath.Join(m.logsDir(), sp.name+"-ffmpeg.err.log"),
|
||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
errF, err := os.OpenFile(ffErr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
_ = outF.Close()
|
||||
return err
|
||||
ffCmd := exec.Command(m.FFmpeg, args...)
|
||||
ffCmd.Stderr = errLog
|
||||
|
||||
var outLog *logfile.Writer
|
||||
if plan.WantsTS {
|
||||
// stdout carries the live media, so it cannot also be a log file.
|
||||
// ffmpeg writes diagnostics to stderr, so nothing is lost.
|
||||
ring := m.Fanout.Create(sp.name)
|
||||
pipe, err := ffCmd.StdoutPipe()
|
||||
if err != nil {
|
||||
_ = errLog.Close()
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
_, _ = io.Copy(ring, pipe)
|
||||
_ = ring.Close()
|
||||
}()
|
||||
} else {
|
||||
outLog, err = logfile.Open(
|
||||
filepath.Join(m.logsDir(), sp.name+"-ffmpeg.out.log"),
|
||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations)
|
||||
if err != nil {
|
||||
_ = errLog.Close()
|
||||
return err
|
||||
}
|
||||
ffCmd.Stdout = outLog
|
||||
}
|
||||
ffArgs := []string{
|
||||
"-hide_banner", "-loglevel", "warning", "-y",
|
||||
"-follow", "1",
|
||||
// Large probe: early pipe-mux bytes often lack clean audio config.
|
||||
"-analyzeduration", "20M",
|
||||
"-probesize", "10M",
|
||||
"-fflags", "+genpts",
|
||||
"-i", sp.tsPath,
|
||||
"-map", "0",
|
||||
"-c", "copy",
|
||||
"-f", "hls",
|
||||
"-hls_time", "4",
|
||||
"-hls_list_size", "15",
|
||||
"-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
|
||||
"-hls_segment_type", "mpegts",
|
||||
"-hls_segment_filename", filepath.Join(sp.wwwDir, "seg_%05d.ts"),
|
||||
sp.hlsIndex,
|
||||
}
|
||||
ffCmd := exec.Command(m.FFmpeg, ffArgs...)
|
||||
ffCmd.Stdout = outF
|
||||
ffCmd.Stderr = errF
|
||||
|
||||
hideWindow(ffCmd)
|
||||
if err := ffCmd.Start(); err != nil {
|
||||
_ = outF.Close()
|
||||
_ = errF.Close()
|
||||
_ = errLog.Close()
|
||||
if outLog != nil {
|
||||
_ = outLog.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
m.logf("stream %s: ffmpeg HLS pid=%d → %s", sp.name, ffCmd.Process.Pid, sp.hlsIndex)
|
||||
m.Log.Info("packager started", "stream", sp.name, "pid", ffCmd.Process.Pid,
|
||||
"outputs", outputSummary(sp.outputSpecs))
|
||||
|
||||
m.mu.Lock()
|
||||
if cur, ok := m.procs[sp.id]; ok && !cur.stopping {
|
||||
|
|
@ -427,14 +530,16 @@ func (m *Media) startFFmpegHLS(sp *streamProc) error {
|
|||
_ = cur.ffErrLog.Close()
|
||||
}
|
||||
cur.ffmpeg = ffCmd
|
||||
cur.ffOutLog = outF
|
||||
cur.ffErrLog = errF
|
||||
cur.ffOutLog = outLog
|
||||
cur.ffErrLog = errLog
|
||||
cur.ffDead = false
|
||||
} else {
|
||||
m.mu.Unlock()
|
||||
_ = killProcess(ffCmd)
|
||||
_ = outF.Close()
|
||||
_ = errF.Close()
|
||||
_ = errLog.Close()
|
||||
if outLog != nil {
|
||||
_ = outLog.Close()
|
||||
}
|
||||
return fmt.Errorf("stream stopped before ffmpeg attach")
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
|
@ -480,21 +585,33 @@ func (m *Media) Stop(id int64) error {
|
|||
sp.mpdProxy.Close()
|
||||
sp.mpdProxy = nil
|
||||
}
|
||||
// Drops every progressive-TS client of this stream and its variants.
|
||||
m.Fanout.RemovePrefix(sp.name)
|
||||
waitPIDsGone([]int{nrePID, ffPID}, 5*time.Second)
|
||||
m.cleanupProc(id)
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: "stopped",
|
||||
PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
||||
})
|
||||
m.logf("stream %s: stopped", sp.name)
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id, Kind: db.EventStopped, Severity: db.SevInfo, Message: "worker stopped",
|
||||
})
|
||||
m.Log.Info("stream stopped", "stream", sp.name)
|
||||
if m.Notifier != nil {
|
||||
m.Notifier.NotifyRuntime(sp.name, "stopped")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Media) Restart(id int64) error {
|
||||
m.logf("stream id=%d: hard restart (kill worker, fresh start)", id)
|
||||
m.Log.Info("hard restart", "stream_id", id)
|
||||
_ = m.Stop(id)
|
||||
// Give Windows time to release file locks on work/www before Start wipes them.
|
||||
time.Sleep(1 * time.Second)
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id, Kind: db.EventRestarted, Severity: db.SevInfo,
|
||||
Message: "restarting worker",
|
||||
})
|
||||
return m.Start(id)
|
||||
}
|
||||
|
||||
|
|
@ -505,14 +622,10 @@ func (m *Media) cleanupProc(id int64) {
|
|||
if !ok {
|
||||
return
|
||||
}
|
||||
if sp.nreLog != nil {
|
||||
_ = sp.nreLog.Close()
|
||||
}
|
||||
if sp.ffOutLog != nil {
|
||||
_ = sp.ffOutLog.Close()
|
||||
}
|
||||
if sp.ffErrLog != nil {
|
||||
_ = sp.ffErrLog.Close()
|
||||
for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
|
||||
if w != nil {
|
||||
_ = w.Close()
|
||||
}
|
||||
}
|
||||
delete(m.procs, id)
|
||||
}
|
||||
|
|
@ -563,6 +676,12 @@ func (m *Media) refreshHealth(id int64) {
|
|||
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
|
||||
LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
|
||||
})
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
|
||||
})
|
||||
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
|
||||
m.report(sp, "down")
|
||||
m.cleanupProc(id)
|
||||
return
|
||||
}
|
||||
|
|
@ -573,6 +692,7 @@ func (m *Media) refreshHealth(id int64) {
|
|||
Health: "starting", PID: pid, PlayPath: playPath, UptimeS: uptime,
|
||||
LastError: "waiting for HLS playlist",
|
||||
})
|
||||
m.sample(sp, "starting", 0, 0)
|
||||
if ffDead {
|
||||
// restart ffmpeg packager if TS still growing
|
||||
go m.restartFFmpeg(sp)
|
||||
|
|
@ -586,16 +706,88 @@ func (m *Media) refreshHealth(id int64) {
|
|||
health = "down"
|
||||
lastErr = fmt.Sprintf("playlist stale (%.0fs)", age)
|
||||
}
|
||||
bitrate := m.estimateBitrate(sp)
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||
Health: health, PID: pid, PlayPath: playPath, UptimeS: uptime,
|
||||
PlaylistAgeS: age, LastError: lastErr,
|
||||
PlaylistAgeS: age, LastError: lastErr, BitrateMbps: bitrate,
|
||||
})
|
||||
m.sample(sp, health, bitrate, age)
|
||||
m.report(sp, health)
|
||||
if ffDead && health != "down" {
|
||||
go m.restartFFmpeg(sp)
|
||||
}
|
||||
go m.restartDeadVariants(sp)
|
||||
}
|
||||
|
||||
// report pushes a health change to the dashboard, only on a transition, so an
|
||||
// idle stream does not generate traffic every five seconds.
|
||||
func (m *Media) report(sp *streamProc, health string) {
|
||||
m.mu.Lock()
|
||||
cur, ok := m.procs[sp.id]
|
||||
if !ok {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
prev := cur.lastHealth
|
||||
changed := prev != health
|
||||
cur.lastHealth = health
|
||||
m.mu.Unlock()
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
if prev != "" {
|
||||
sev := db.SevInfo
|
||||
if health == "down" {
|
||||
sev = db.SevError
|
||||
}
|
||||
m.Store.Eventf(sp.id, db.EventVariantUp, sev, "health %s to %s", prev, health)
|
||||
}
|
||||
if m.Notifier != nil {
|
||||
m.Notifier.NotifyRuntime(sp.name, health)
|
||||
}
|
||||
}
|
||||
|
||||
// sample records one point on the stream's health series.
|
||||
func (m *Media) sample(sp *streamProc, health string, bitrate, age float64) {
|
||||
viewers := 0
|
||||
if m.ViewersFn != nil {
|
||||
viewers = m.ViewersFn(sp.name)
|
||||
}
|
||||
m.Store.AddMetric(sp.id, db.MetricPoint{
|
||||
Health: health,
|
||||
BitrateMbps: bitrate,
|
||||
PlaylistAgeS: age,
|
||||
Viewers: viewers,
|
||||
})
|
||||
}
|
||||
|
||||
// estimateBitrate derives Mbps from how fast the muxed TS is growing, which is
|
||||
// all the dashboard sparkline needs.
|
||||
func (m *Media) estimateBitrate(sp *streamProc) float64 {
|
||||
fi, err := os.Stat(sp.tsPath)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
size := fi.Size()
|
||||
nowT := time.Now()
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cur, ok := m.procs[sp.id]
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
prevSize, prevAt := cur.lastTSSize, cur.lastTSAt
|
||||
cur.lastTSSize, cur.lastTSAt = size, nowT
|
||||
if prevAt.IsZero() || size <= prevSize {
|
||||
return 0
|
||||
}
|
||||
elapsed := nowT.Sub(prevAt).Seconds()
|
||||
if elapsed <= 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(size-prevSize) * 8 / elapsed / 1e6
|
||||
}
|
||||
|
||||
func (m *Media) restartFFmpeg(sp *streamProc) {
|
||||
m.mu.Lock()
|
||||
cur, ok := m.procs[sp.id]
|
||||
|
|
@ -620,9 +812,13 @@ func (m *Media) restartFFmpeg(sp *streamProc) {
|
|||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.logf("stream %s: restarting ffmpeg HLS packager", sp.name)
|
||||
if err := m.startFFmpegHLS(sp); err != nil {
|
||||
m.logf("stream %s: ffmpeg restart failed: %v", sp.name, err)
|
||||
m.Log.Warn("restarting packager", "stream", sp.name)
|
||||
m.Store.AddEvent(db.StreamEvent{
|
||||
StreamID: sp.id, Kind: db.EventFFRestart, Severity: db.SevWarn,
|
||||
Message: "packager exited; restarting it",
|
||||
})
|
||||
if err := m.startPackager(sp); err != nil {
|
||||
m.Log.Error("packager restart failed", "stream", sp.name, "err", err)
|
||||
m.mu.Lock()
|
||||
if cur, ok := m.procs[sp.id]; ok {
|
||||
cur.ffDead = true
|
||||
|
|
@ -637,10 +833,7 @@ func (m *Media) restartFFmpeg(sp *streamProc) {
|
|||
}
|
||||
m.mu.Unlock()
|
||||
m.startVariantPackagers(sp, specs)
|
||||
}
|
||||
|
||||
func (m *Media) logf(format string, args ...any) {
|
||||
m.Log.Printf("supervisor: "+format, args...)
|
||||
m.writeMasterPlaylist(sp)
|
||||
}
|
||||
|
||||
func headerMap(headersJSON string) map[string]string {
|
||||
|
|
@ -675,25 +868,19 @@ func headerFlags(headersJSON string) []string {
|
|||
// normalizeKeysFile turns a DB key field (one or many KID:KEY lines, or
|
||||
// comma/semicolon separated) into an NRE --key-text-file body.
|
||||
func normalizeKeysFile(raw string) string {
|
||||
raw = strings.ReplaceAll(raw, ",", "\n")
|
||||
raw = strings.ReplaceAll(raw, ";", "\n")
|
||||
var lines []string
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.Count(line, ":") != 1 {
|
||||
continue
|
||||
}
|
||||
if seen[line] {
|
||||
for _, line := range db.SplitKeyLines(raw) {
|
||||
if strings.Count(line, ":") != 1 || seen[line] {
|
||||
continue
|
||||
}
|
||||
seen[line] = true
|
||||
lines = append(lines, line)
|
||||
out = append(out, line)
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
if len(out) == 0 {
|
||||
return strings.TrimSpace(raw) + "\n"
|
||||
}
|
||||
return strings.Join(lines, "\n") + "\n"
|
||||
return strings.Join(out, "\n") + "\n"
|
||||
}
|
||||
|
||||
func killProcess(cmd *exec.Cmd) error {
|
||||
|
|
@ -702,8 +889,7 @@ func killProcess(cmd *exec.Cmd) error {
|
|||
}
|
||||
pid := cmd.Process.Pid
|
||||
if runtime.GOOS == "windows" {
|
||||
_ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
|
||||
return nil
|
||||
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
|
||||
}
|
||||
return cmd.Process.Kill()
|
||||
}
|
||||
|
|
@ -745,8 +931,6 @@ func copyFile(src, dst string) error {
|
|||
return out.Close()
|
||||
}
|
||||
|
||||
// findGrowingTS locates NRE's live-pipe-mux output. Depending on version/flags
|
||||
// it may be saveName.ts or saveName.<lang>.ts (e.g. test.en.ts).
|
||||
func waitPIDsGone(pids []int, timeout time.Duration) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
|
|
@ -767,10 +951,8 @@ func waitPIDsGone(pids []int, timeout time.Duration) {
|
|||
}
|
||||
}
|
||||
|
||||
func findGrowingTS(dir, saveName string) string {
|
||||
return findGrowingTSMin(dir, saveName, 256*1024)
|
||||
}
|
||||
|
||||
// findGrowingTSMin locates NRE's live-pipe-mux output. Depending on
|
||||
// version/flags it may be saveName.ts or saveName.<lang>.ts (e.g. test.en.ts).
|
||||
func findGrowingTSMin(dir, saveName string, minSize int64) string {
|
||||
if minSize <= 0 {
|
||||
minSize = 256 * 1024
|
||||
|
|
|
|||
299
apps/streamd/internal/supervisor/outputs.go
Normal file
299
apps/streamd/internal/supervisor/outputs.go
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
package supervisor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// Packager defaults. These were literals in the ffmpeg command line before
|
||||
// they became per-stream settings.
|
||||
const (
|
||||
defaultHLSTime = 4
|
||||
defaultHLSListSize = 15
|
||||
hlsFlags = "delete_segments+append_list+omit_endlist+independent_segments"
|
||||
)
|
||||
|
||||
// outputPlan is the resolved publishing plan for one variant.
|
||||
type outputPlan struct {
|
||||
// Args are the ffmpeg output arguments, appended after the input.
|
||||
Args []string
|
||||
// WantsTS is true when one of the outputs is the progressive MPEG-TS
|
||||
// pipe, which means the process's stdout is media and must not also be
|
||||
// used for logging.
|
||||
WantsTS bool
|
||||
// Dirs must exist before ffmpeg starts: it will not create them, and
|
||||
// under tee's onfail=ignore a missing one fails that output silently.
|
||||
Dirs []string
|
||||
// Playlists maps an output format to the file it writes, for health
|
||||
// checks and the master playlist.
|
||||
Playlists map[string]string
|
||||
}
|
||||
|
||||
// buildOutputPlan turns a variant's enabled outputs into ffmpeg arguments.
|
||||
//
|
||||
// With a single output it emits a plain "-f <muxer> ... <url>", which keeps
|
||||
// the common HLS-only case the same shape streamd has always run. With
|
||||
// several it emits one tee muxer, so the frames are encoded once and muxed N
|
||||
// times — listing several plain outputs would instead run the encoder once per
|
||||
// output, roughly tripling CPU for a 720p rung publishing HLS+CMAF+DASH.
|
||||
func buildOutputPlan(outputs []db.OutputSpec, wwwDir string, cfg streamSettings, spec db.VariantSpec) outputPlan {
|
||||
plan := outputPlan{Playlists: map[string]string{}}
|
||||
enabled := db.EnabledOutputs(outputs)
|
||||
if len(enabled) == 0 {
|
||||
// Never publish nothing: that would leave the stream unreachable.
|
||||
enabled = []db.OutputSpec{{ID: "hls", Format: db.FormatHLS, Enabled: true}}
|
||||
}
|
||||
// The source rung is a stream copy from the downloader's MPEG-TS. Copying
|
||||
// that into an fMP4 container needs two fixes that re-encoding would not:
|
||||
// the AAC has to be converted from ADTS to ASC, and the H.264 codec tag
|
||||
// carried from TS is rejected by the MP4 muxer. Both were found by running
|
||||
// the real ffmpeg; see ffmpeg_integration_test.go.
|
||||
copying := spec.IsSource()
|
||||
|
||||
type target struct {
|
||||
format string
|
||||
options []kv
|
||||
url string
|
||||
// fmp4 marks an output whose container is ISO-BMFF.
|
||||
fmp4 bool
|
||||
}
|
||||
var targets []target
|
||||
|
||||
for _, o := range enabled {
|
||||
segDur := o.SegmentDuration
|
||||
if segDur <= 0 {
|
||||
segDur = cfg.HLSTime
|
||||
}
|
||||
listSize := o.ListSize
|
||||
if listSize <= 0 {
|
||||
listSize = cfg.HLSListSize
|
||||
}
|
||||
switch o.Format {
|
||||
case db.FormatHLS:
|
||||
index := filepath.Join(wwwDir, "index.m3u8")
|
||||
targets = append(targets, target{
|
||||
format: "hls",
|
||||
options: []kv{
|
||||
{"hls_time", strconv.Itoa(segDur)},
|
||||
{"hls_list_size", strconv.Itoa(listSize)},
|
||||
{"hls_flags", hlsFlags},
|
||||
{"hls_segment_type", "mpegts"},
|
||||
{"hls_segment_filename", filepath.Join(wwwDir, "seg_%05d.ts")},
|
||||
},
|
||||
url: index,
|
||||
})
|
||||
plan.Playlists[db.FormatHLS] = index
|
||||
|
||||
case db.FormatCMAF:
|
||||
dir := filepath.Join(wwwDir, "cmaf")
|
||||
index := filepath.Join(dir, "index.m3u8")
|
||||
targets = append(targets, target{
|
||||
format: "hls",
|
||||
fmp4: true,
|
||||
options: []kv{
|
||||
{"hls_time", strconv.Itoa(segDur)},
|
||||
{"hls_list_size", strconv.Itoa(listSize)},
|
||||
{"hls_flags", hlsFlags},
|
||||
{"hls_segment_type", "fmp4"},
|
||||
{"hls_fmp4_init_filename", "init.mp4"},
|
||||
{"hls_segment_filename", filepath.Join(dir, "seg_%05d.m4s")},
|
||||
},
|
||||
url: index,
|
||||
})
|
||||
plan.Dirs = append(plan.Dirs, dir)
|
||||
plan.Playlists[db.FormatCMAF] = index
|
||||
|
||||
case db.FormatDASH:
|
||||
dir := filepath.Join(wwwDir, "dash")
|
||||
index := filepath.Join(dir, "index.mpd")
|
||||
targets = append(targets, target{
|
||||
format: "dash",
|
||||
fmp4: true,
|
||||
options: []kv{
|
||||
{"seg_duration", strconv.Itoa(segDur)},
|
||||
{"window_size", strconv.Itoa(listSize)},
|
||||
{"extra_window_size", "2"},
|
||||
{"use_template", "1"},
|
||||
{"use_timeline", "1"},
|
||||
{"streaming", "1"},
|
||||
},
|
||||
url: index,
|
||||
})
|
||||
plan.Dirs = append(plan.Dirs, dir)
|
||||
plan.Playlists[db.FormatDASH] = index
|
||||
|
||||
case db.FormatTS:
|
||||
targets = append(targets, target{format: "mpegts", url: "pipe:1"})
|
||||
plan.WantsTS = true
|
||||
}
|
||||
}
|
||||
|
||||
// An fMP4 output from a copied source needs an MP4-compatible codec tag.
|
||||
// This is a stream option rather than a muxer option, so it applies to the
|
||||
// whole output; it is harmless to the MPEG-TS legs, which ignore it.
|
||||
var pre []string
|
||||
needsFMP4Fixes := false
|
||||
for _, t := range targets {
|
||||
if t.fmp4 {
|
||||
needsFMP4Fixes = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if copying && needsFMP4Fixes {
|
||||
pre = append(pre, "-tag:v", "avc1", "-tag:a", "mp4a")
|
||||
}
|
||||
|
||||
if len(targets) == 1 {
|
||||
t := targets[0]
|
||||
args := append([]string{}, pre...)
|
||||
// With one output there is no tee, so a bitstream filter is set the
|
||||
// ordinary way.
|
||||
if copying && t.fmp4 {
|
||||
args = append(args, "-bsf:a", "aac_adtstoasc")
|
||||
}
|
||||
args = append(args, "-f", t.format)
|
||||
for _, o := range t.options {
|
||||
args = append(args, "-"+o.k, o.v)
|
||||
}
|
||||
plan.Args = append(args, t.url)
|
||||
return plan
|
||||
}
|
||||
|
||||
// Several outputs: one tee, one encode.
|
||||
specs := make([]string, 0, len(targets))
|
||||
for _, t := range targets {
|
||||
opts := make([]string, 0, len(t.options)+3)
|
||||
opts = append(opts, "f="+t.format)
|
||||
// onfail=ignore on every leg is essential. Without it, a reader
|
||||
// disconnecting from the progressive TS pipe, or a full disk under one
|
||||
// output directory, tears down the whole ffmpeg process and takes the
|
||||
// healthy outputs with it.
|
||||
opts = append(opts, "onfail=ignore")
|
||||
// The ADTS-to-ASC conversion has to be per-leg: applying it globally
|
||||
// would also rewrite the audio going into the MPEG-TS outputs, which
|
||||
// need ADTS.
|
||||
if copying && t.fmp4 {
|
||||
opts = append(opts, "bsfs/a=aac_adtstoasc")
|
||||
}
|
||||
for _, o := range t.options {
|
||||
opts = append(opts, teeEscapeKey(o.k)+"="+teeEscapeValue(o.v))
|
||||
}
|
||||
specs = append(specs, "["+strings.Join(opts, ":")+"]"+teeEscapeURL(t.url))
|
||||
}
|
||||
plan.Args = append(pre, "-f", "tee", strings.Join(specs, "|"))
|
||||
return plan
|
||||
}
|
||||
|
||||
type kv struct{ k, v string }
|
||||
|
||||
// teeEscapeKey escapes a tee option name. Names are fixed identifiers, so
|
||||
// this only guards against a stray separator reaching the parser.
|
||||
func teeEscapeKey(s string) string {
|
||||
return strings.NewReplacer(
|
||||
`\`, `\\`,
|
||||
`:`, `\:`,
|
||||
`|`, `\|`,
|
||||
`[`, `\[`,
|
||||
`]`, `\]`,
|
||||
`=`, `\=`,
|
||||
).Replace(s)
|
||||
}
|
||||
|
||||
// teeEscapeValue escapes a tee option value.
|
||||
//
|
||||
// This needs two layers at once, which is not obvious and was established by
|
||||
// testing against the real ffmpeg (see ffmpeg_integration_test.go): the value
|
||||
// is wrapped in single quotes AND its colons are backslash-escaped. Quoting
|
||||
// alone is not enough, and escaping alone is not enough.
|
||||
//
|
||||
// A Windows path is what makes it matter. Unescaped,
|
||||
// "hls_segment_filename=C:/data/seg.ts" is split at the drive letter, ffmpeg
|
||||
// rejects that slave, and under onfail=ignore the output silently never
|
||||
// appears — a failure mode that looks like "CMAF just doesn't work".
|
||||
func teeEscapeValue(s string) string {
|
||||
// Forward slashes throughout: a backslash is itself an escape character
|
||||
// here, so a Windows path written with them is a second problem.
|
||||
s = filepath.ToSlash(s)
|
||||
// A literal single quote cannot appear inside a single-quoted run: close
|
||||
// the quote, emit an escaped one, reopen.
|
||||
s = strings.ReplaceAll(s, `'`, `'\''`)
|
||||
s = strings.ReplaceAll(s, `:`, `\:`)
|
||||
return `'` + s + `'`
|
||||
}
|
||||
|
||||
// teeEscapeURL escapes the destination URL of one tee output. The URL runs
|
||||
// from after "]" to the next unescaped "|", so only the separator and bracket
|
||||
// characters need escaping — a colon is safe here, and escaping it would
|
||||
// corrupt the path.
|
||||
func teeEscapeURL(s string) string {
|
||||
s = filepath.ToSlash(s)
|
||||
return strings.NewReplacer(
|
||||
`|`, `\|`,
|
||||
`[`, `\[`,
|
||||
`]`, `\]`,
|
||||
).Replace(s)
|
||||
}
|
||||
|
||||
// variantCodecArgs builds the encoder arguments for one rung. The source rung
|
||||
// is a stream copy; a scaled rung re-encodes; an audio-only rung drops video.
|
||||
func variantCodecArgs(v db.VariantSpec) []string {
|
||||
if v.IsSource() {
|
||||
return []string{"-map", "0", "-c", "copy"}
|
||||
}
|
||||
if v.AudioOnly {
|
||||
abr := v.AudioBitrate
|
||||
if abr == "" {
|
||||
abr = "96k"
|
||||
}
|
||||
return []string{
|
||||
"-map", "0:a:0?",
|
||||
"-vn",
|
||||
"-c:a", "aac",
|
||||
"-b:a", abr,
|
||||
"-ac", "2",
|
||||
}
|
||||
}
|
||||
vbr := v.VideoBitrate
|
||||
if vbr == "" {
|
||||
vbr = "2800k"
|
||||
}
|
||||
abr := v.AudioBitrate
|
||||
if abr == "" {
|
||||
abr = "128k"
|
||||
}
|
||||
return []string{
|
||||
"-map", "0:v:0",
|
||||
"-map", "0:a:0?",
|
||||
"-vf", fmt.Sprintf("scale=-2:%d", v.Height),
|
||||
"-c:v", "libx264",
|
||||
"-preset", "veryfast",
|
||||
"-tune", "zerolatency",
|
||||
"-b:v", vbr,
|
||||
"-maxrate", vbr,
|
||||
"-bufsize", doubleBitrate(vbr),
|
||||
"-g", "48",
|
||||
"-keyint_min", "48",
|
||||
"-sc_threshold", "0",
|
||||
"-c:a", "aac",
|
||||
"-b:a", abr,
|
||||
"-ac", "2",
|
||||
}
|
||||
}
|
||||
|
||||
// inputArgs are the demuxer options for reading the growing TS the downloader
|
||||
// is writing. The large probe is deliberate: the first bytes of a pipe-mux
|
||||
// often lack a clean audio configuration.
|
||||
func inputArgs(tsPath string) []string {
|
||||
return []string{
|
||||
"-hide_banner", "-loglevel", "warning", "-y",
|
||||
"-follow", "1",
|
||||
"-analyzeduration", "20M",
|
||||
"-probesize", "10M",
|
||||
"-fflags", "+genpts",
|
||||
"-i", tsPath,
|
||||
}
|
||||
}
|
||||
389
apps/streamd/internal/supervisor/outputs_test.go
Normal file
389
apps/streamd/internal/supervisor/outputs_test.go
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
package supervisor
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// quote and backslash as values, so the test source stays readable where it
|
||||
// asserts on ffmpeg's escaping.
|
||||
const (
|
||||
q = "'"
|
||||
bs = `\`
|
||||
)
|
||||
|
||||
func testCfg() streamSettings {
|
||||
return streamSettings{HLSTime: defaultHLSTime, HLSListSize: defaultHLSListSize}
|
||||
}
|
||||
|
||||
func only(format string) []db.OutputSpec {
|
||||
return []db.OutputSpec{{ID: "x", Format: format, Enabled: true}}
|
||||
}
|
||||
|
||||
func sourceSpecForTest() db.VariantSpec {
|
||||
return db.VariantSpec{ID: db.SourceVariantID, Label: "FHD", Enabled: true, Height: 0}
|
||||
}
|
||||
|
||||
func normalize(s string) string { return strings.ReplaceAll(s, `\`, "/") }
|
||||
|
||||
// findFormat returns the muxer named by -f, without assuming a position: a
|
||||
// stream-copied rung publishing fMP4 carries -tag options first.
|
||||
func findFormat(args []string) string {
|
||||
for i := 0; i < len(args)-1; i++ {
|
||||
if args[i] == "-f" {
|
||||
return args[i+1]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// teeSpec returns the single tee specification argument.
|
||||
func teeSpec(t *testing.T, args []string) string {
|
||||
t.Helper()
|
||||
for i := 0; i < len(args)-1; i++ {
|
||||
if args[i] == "-f" && args[i+1] == "tee" {
|
||||
if i+2 >= len(args) {
|
||||
t.Fatalf("-f tee with no spec: %v", args)
|
||||
}
|
||||
return args[i+2]
|
||||
}
|
||||
}
|
||||
t.Fatalf("no tee muxer in %v", args)
|
||||
return ""
|
||||
}
|
||||
|
||||
// With a single mpegts HLS output the command must stay the plain form
|
||||
// streamd has always run. media.go is the least-exercised code in the project,
|
||||
// so the common path deliberately does not change shape.
|
||||
func TestSingleHLSOutputMatchesTheOriginalCommand(t *testing.T) {
|
||||
plan := buildOutputPlan(only(db.FormatHLS), "/data/www/news", testCfg(), sourceSpecForTest())
|
||||
want := []string{
|
||||
"-f", "hls",
|
||||
"-hls_time", "4",
|
||||
"-hls_list_size", "15",
|
||||
"-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
|
||||
"-hls_segment_type", "mpegts",
|
||||
"-hls_segment_filename", "/data/www/news/seg_%05d.ts",
|
||||
"/data/www/news/index.m3u8",
|
||||
}
|
||||
if len(plan.Args) != len(want) {
|
||||
t.Fatalf("arg count %d, want %d\ngot: %v\nwant: %v", len(plan.Args), len(want), plan.Args, want)
|
||||
}
|
||||
for i := range want {
|
||||
// Separators are normalised, since filepath.Join is platform-specific.
|
||||
if normalize(plan.Args[i]) != normalize(want[i]) {
|
||||
t.Errorf("arg %d = %q, want %q", i, plan.Args[i], want[i])
|
||||
}
|
||||
}
|
||||
if plan.WantsTS {
|
||||
t.Error("an HLS-only plan must not claim stdout")
|
||||
}
|
||||
for _, a := range plan.Args {
|
||||
if a == "tee" {
|
||||
t.Error("a single output must not use the tee muxer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleOutputPerFormat(t *testing.T) {
|
||||
cases := []struct {
|
||||
format string
|
||||
wantMux string
|
||||
wantPath string
|
||||
}{
|
||||
{db.FormatHLS, "hls", "/data/www/news/index.m3u8"},
|
||||
{db.FormatCMAF, "hls", "/data/www/news/cmaf/index.m3u8"},
|
||||
{db.FormatDASH, "dash", "/data/www/news/dash/index.mpd"},
|
||||
{db.FormatTS, "mpegts", "pipe:1"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
plan := buildOutputPlan(only(c.format), "/data/www/news", testCfg(), sourceSpecForTest())
|
||||
if mux := findFormat(plan.Args); mux != c.wantMux {
|
||||
t.Errorf("%s: muxer = %q, want %s (args %v)", c.format, mux, c.wantMux, plan.Args)
|
||||
}
|
||||
if last := normalize(plan.Args[len(plan.Args)-1]); last != c.wantPath {
|
||||
t.Errorf("%s: output = %q, want %q", c.format, last, c.wantPath)
|
||||
}
|
||||
if (c.format == db.FormatTS) != plan.WantsTS {
|
||||
t.Errorf("%s: WantsTS = %v", c.format, plan.WantsTS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The headline requirement: several outputs must share ONE encode via tee. If
|
||||
// this regresses into several plain outputs, ffmpeg runs the encoder once per
|
||||
// format and CPU triples for a transcoded rung.
|
||||
func TestMultipleOutputsUseOneTee(t *testing.T) {
|
||||
outputs := []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
{ID: "ts", Format: db.FormatTS, Enabled: true},
|
||||
}
|
||||
plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
|
||||
spec := teeSpec(t, plan.Args)
|
||||
|
||||
fCount := 0
|
||||
for _, a := range plan.Args {
|
||||
if a == "-f" {
|
||||
fCount++
|
||||
}
|
||||
}
|
||||
if fCount != 1 {
|
||||
t.Errorf("want a single -f (the tee), got %d: %v", fCount, plan.Args)
|
||||
}
|
||||
|
||||
legs := strings.Split(spec, "|")
|
||||
if len(legs) != 4 {
|
||||
t.Fatalf("want 4 tee legs, got %d: %s", len(legs), spec)
|
||||
}
|
||||
// Every leg must carry onfail=ignore: without it one dead output (a
|
||||
// disconnected TS reader, a full disk) kills the whole process and takes
|
||||
// the healthy outputs with it.
|
||||
for i, leg := range legs {
|
||||
if !strings.Contains(leg, "onfail=ignore") {
|
||||
t.Errorf("leg %d has no onfail=ignore: %s", i, leg)
|
||||
}
|
||||
if !strings.HasPrefix(leg, "[") || !strings.Contains(leg, "]") {
|
||||
t.Errorf("leg %d is not a bracketed tee spec: %s", i, leg)
|
||||
}
|
||||
}
|
||||
if n := strings.Count(spec, "f=hls"); n != 2 {
|
||||
t.Errorf("want two hls legs (mpegts + fmp4), got %d", n)
|
||||
}
|
||||
if !strings.Contains(spec, "f=dash") || !strings.Contains(spec, "f=mpegts") {
|
||||
t.Errorf("missing a format in the tee spec: %s", spec)
|
||||
}
|
||||
if !plan.WantsTS {
|
||||
t.Error("a plan including the TS output must claim stdout")
|
||||
}
|
||||
// CMAF and DASH write into subdirectories ffmpeg will not create.
|
||||
if len(plan.Dirs) != 2 {
|
||||
t.Errorf("want 2 directories to pre-create, got %v", plan.Dirs)
|
||||
}
|
||||
}
|
||||
|
||||
// Windows paths contain a colon, which is also the tee option separator.
|
||||
// Unescaped, hls_segment_filename=C:/... is split at the drive letter, that
|
||||
// slave is rejected, and under onfail=ignore the output silently never
|
||||
// appears.
|
||||
func TestTeeEscapesColonsInPaths(t *testing.T) {
|
||||
outputs := []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
}
|
||||
plan := buildOutputPlan(outputs, `C:\data\www\city news`, testCfg(), sourceSpecForTest())
|
||||
spec := teeSpec(t, plan.Args)
|
||||
|
||||
if strings.Contains(spec, "hls_segment_filename=C:") {
|
||||
t.Errorf("drive-letter colon is unescaped in the option value: %s", spec)
|
||||
}
|
||||
// Real ffmpeg needs BOTH: the value quoted and its colon escaped.
|
||||
if !strings.Contains(spec, "hls_segment_filename="+q+"C"+bs+":") {
|
||||
t.Errorf("want the value quoted with its colon escaped, got: %s", spec)
|
||||
}
|
||||
// A space is fine: this is one argv element, not a shell word.
|
||||
if !strings.Contains(spec, "city news") {
|
||||
t.Errorf("path with a space was mangled: %s", spec)
|
||||
}
|
||||
// The URL after ] keeps its colon, which is not special there.
|
||||
if !strings.Contains(spec, "]C:/data/www/city news/index.m3u8") {
|
||||
t.Errorf("output URL should keep its drive colon: %s", spec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeeEscapeKey(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"plain": "plain",
|
||||
"a:b": "a" + bs + ":b",
|
||||
"a|b": "a" + bs + "|b",
|
||||
"a[b]": "a" + bs + "[b" + bs + "]",
|
||||
"k=v": "k" + bs + "=v",
|
||||
"bsfs/a": "bsfs/a",
|
||||
} {
|
||||
if got := teeEscapeKey(in); got != want {
|
||||
t.Errorf("teeEscapeKey(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeeEscapeValue(t *testing.T) {
|
||||
// Both layers, in this order: quote the whole value, escape its colons.
|
||||
// Established against the real ffmpeg; neither alone is accepted.
|
||||
if got := teeEscapeValue("C:/data/seg_%05d.ts"); got != q+"C"+bs+":/data/seg_%05d.ts"+q {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
// Backslashes become forward slashes rather than being doubled, because a
|
||||
// backslash is itself an escape character in a tee spec.
|
||||
if got := teeEscapeValue(`C:\data\x.ts`); got != q+"C"+bs+":/data/x.ts"+q {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
// A space needs nothing special once the value is quoted.
|
||||
if got := teeEscapeValue("/srv/city news/seg.ts"); got != q+"/srv/city news/seg.ts"+q {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
// A plain value is quoted too, which is harmless and keeps one rule.
|
||||
if got := teeEscapeValue("mpegts"); got != q+"mpegts"+q {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
// A literal quote must not end the quoted run.
|
||||
if got := teeEscapeValue("/srv/o" + q + "brien/seg.ts"); !strings.Contains(got, q+bs+q) {
|
||||
t.Errorf("apostrophe was not escaped: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeeEscapeURL(t *testing.T) {
|
||||
// Backslashes become forward slashes, and only the separator characters
|
||||
// are escaped — a colon must survive untouched in a URL.
|
||||
if got := teeEscapeURL(`C:\data\x.m3u8`); got != "C:/data/x.m3u8" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
if got := teeEscapeURL("a|b"); got != "a"+bs+"|b" {
|
||||
t.Errorf("pipe must be escaped in a URL, got %q", got)
|
||||
}
|
||||
if got := teeEscapeURL("pipe:1"); got != "pipe:1" {
|
||||
t.Errorf("pipe:1 must pass through unchanged, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A copied source rung into an fMP4 container needs the ADTS-to-ASC filter on
|
||||
// that leg only, plus an MP4 codec tag. A re-encoded rung needs neither,
|
||||
// because ffmpeg then produces the right bitstream for each muxer itself.
|
||||
func TestFMP4CopyFixesOnlyWhenCopying(t *testing.T) {
|
||||
outputs := []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
|
||||
}
|
||||
src := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
|
||||
if !strings.Contains(strings.Join(src.Args, " "), "-tag:v avc1") {
|
||||
t.Error("a copied rung publishing fMP4 needs an MP4 codec tag")
|
||||
}
|
||||
for _, leg := range strings.Split(teeSpec(t, src.Args), "|") {
|
||||
isFMP4 := strings.Contains(leg, "fmp4")
|
||||
hasBSF := strings.Contains(leg, "aac_adtstoasc")
|
||||
if isFMP4 != hasBSF {
|
||||
t.Errorf("aac_adtstoasc belongs on the fMP4 leg and only there: %s", leg)
|
||||
}
|
||||
}
|
||||
|
||||
hd := db.VariantSpec{ID: "hd", Enabled: true, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"}
|
||||
enc := strings.Join(buildOutputPlan(outputs, "/w", testCfg(), hd).Args, " ")
|
||||
if strings.Contains(enc, "-tag:v avc1") {
|
||||
t.Error("a re-encoded rung should not need a codec tag override")
|
||||
}
|
||||
if strings.Contains(enc, "aac_adtstoasc") {
|
||||
t.Error("a re-encoded rung should not need the ADTS filter")
|
||||
}
|
||||
}
|
||||
|
||||
// A single fMP4 output has no tee, so the bitstream filter is set the
|
||||
// ordinary way.
|
||||
func TestSingleFMP4OutputUsesPlainBSF(t *testing.T) {
|
||||
plan := buildOutputPlan(only(db.FormatCMAF), "/w", testCfg(), sourceSpecForTest())
|
||||
joined := strings.Join(plan.Args, " ")
|
||||
if !strings.Contains(joined, "-bsf:a aac_adtstoasc") {
|
||||
t.Errorf("want a plain -bsf:a, got %s", joined)
|
||||
}
|
||||
if strings.Contains(joined, "bsfs/a") {
|
||||
t.Errorf("tee syntax leaked into a single-output command: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// Publishing nothing would leave the stream unreachable.
|
||||
func TestNoEnabledOutputsFallsBackToHLS(t *testing.T) {
|
||||
plan := buildOutputPlan([]db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: false},
|
||||
}, "/data/www/news", testCfg(), sourceSpecForTest())
|
||||
if findFormat(plan.Args) != "hls" {
|
||||
t.Errorf("want an HLS fallback, got %v", plan.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerOutputSegmentOverrides(t *testing.T) {
|
||||
outputs := []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true, SegmentDuration: 2, ListSize: 6},
|
||||
}
|
||||
plan := buildOutputPlan(outputs, "/data/www/news", testCfg(), sourceSpecForTest())
|
||||
joined := strings.Join(plan.Args, " ")
|
||||
if !strings.Contains(joined, "-hls_time 2") || !strings.Contains(joined, "-hls_list_size 6") {
|
||||
t.Errorf("per-output overrides were ignored: %s", joined)
|
||||
}
|
||||
// An output that does not override inherits the stream's settings.
|
||||
cfg := testCfg()
|
||||
cfg.HLSTime, cfg.HLSListSize = 8, 40
|
||||
plan = buildOutputPlan(only(db.FormatHLS), "/data/www/news", cfg, sourceSpecForTest())
|
||||
joined = strings.Join(plan.Args, " ")
|
||||
if !strings.Contains(joined, "-hls_time 8") || !strings.Contains(joined, "-hls_list_size 40") {
|
||||
t.Errorf("stream settings were not inherited: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantCodecArgs(t *testing.T) {
|
||||
// The source rung is a pass-through copy: no encoder at all.
|
||||
src := strings.Join(variantCodecArgs(sourceSpecForTest()), " ")
|
||||
if !strings.Contains(src, "-c copy") {
|
||||
t.Errorf("source rung must stream-copy, got %q", src)
|
||||
}
|
||||
if strings.Contains(src, "libx264") {
|
||||
t.Error("source rung must not re-encode")
|
||||
}
|
||||
|
||||
// A scaled rung encodes video and audio.
|
||||
hd := strings.Join(variantCodecArgs(db.VariantSpec{
|
||||
ID: "hd", Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k",
|
||||
}), " ")
|
||||
for _, want := range []string{"scale=-2:720", "libx264", "-b:v 2800k", "-b:a 128k", "-bufsize 5600k"} {
|
||||
if !strings.Contains(hd, want) {
|
||||
t.Errorf("scaled rung missing %q in %q", want, hd)
|
||||
}
|
||||
}
|
||||
|
||||
// An audio-only rung drops video entirely.
|
||||
au := strings.Join(variantCodecArgs(db.VariantSpec{
|
||||
ID: "audio", AudioOnly: true, AudioBitrate: "96k",
|
||||
}), " ")
|
||||
if !strings.Contains(au, "-vn") {
|
||||
t.Errorf("audio rung must pass -vn, got %q", au)
|
||||
}
|
||||
if strings.Contains(au, "libx264") || strings.Contains(au, "scale=") {
|
||||
t.Errorf("audio rung must not touch video, got %q", au)
|
||||
}
|
||||
if !strings.Contains(au, "-b:a 96k") {
|
||||
t.Errorf("audio rung missing its bitrate, got %q", au)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoubleBitrate(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"2800k": "5600k",
|
||||
"1200k": "2400k",
|
||||
"5M": "10000k",
|
||||
"": "5600k",
|
||||
"junk": "5600k",
|
||||
} {
|
||||
if got := doubleBitrate(in); got != want {
|
||||
t.Errorf("doubleBitrate(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaylistsRecorded(t *testing.T) {
|
||||
outputs := []db.OutputSpec{
|
||||
{ID: "hls", Format: db.FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Format: db.FormatCMAF, Enabled: true},
|
||||
{ID: "dash", Format: db.FormatDASH, Enabled: true},
|
||||
{ID: "ts", Format: db.FormatTS, Enabled: true},
|
||||
}
|
||||
plan := buildOutputPlan(outputs, "/w", testCfg(), sourceSpecForTest())
|
||||
for _, f := range []string{db.FormatHLS, db.FormatCMAF, db.FormatDASH} {
|
||||
if plan.Playlists[f] == "" {
|
||||
t.Errorf("no playlist recorded for %s", f)
|
||||
}
|
||||
}
|
||||
// The progressive TS has no file on disk, so no playlist entry.
|
||||
if plan.Playlists[db.FormatTS] != "" {
|
||||
t.Error("the TS output should not record a playlist file")
|
||||
}
|
||||
}
|
||||
|
|
@ -2,12 +2,15 @@ package supervisor
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/logfile"
|
||||
)
|
||||
|
||||
type variantProc struct {
|
||||
|
|
@ -15,8 +18,8 @@ type variantProc struct {
|
|||
wwwDir string
|
||||
index string
|
||||
cmd *exec.Cmd
|
||||
outLog *os.File
|
||||
errLog *os.File
|
||||
outLog *logfile.Writer
|
||||
errLog *logfile.Writer
|
||||
dead bool
|
||||
}
|
||||
|
||||
|
|
@ -43,12 +46,16 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) {
|
|||
for _, spec := range scaled {
|
||||
vp, err := m.spawnVariantFFmpeg(sp, spec)
|
||||
if err != nil {
|
||||
m.logf("stream %s variant %s: %v", sp.name, spec.ID, err)
|
||||
m.Log.Error("variant packager failed to start",
|
||||
"stream", sp.name, "variant", spec.ID, "err", err)
|
||||
m.Store.Eventf(sp.id, db.EventVariantDown, db.SevError,
|
||||
"variant %s failed to start: %v", spec.ID, err)
|
||||
continue
|
||||
}
|
||||
started = append(started, vp)
|
||||
m.logf("stream %s: variant %s (%dp) pid=%d → %s",
|
||||
sp.name, spec.ID, spec.Height, vp.cmd.Process.Pid, vp.index)
|
||||
m.Log.Info("variant packager started", "stream", sp.name, "variant", spec.ID,
|
||||
"height", spec.Height, "audio_only", spec.AudioOnly,
|
||||
"pid", vp.cmd.Process.Pid, "index", vp.index)
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
|
|
@ -65,84 +72,76 @@ func (m *Media) startVariantPackagers(sp *streamProc, specs []db.VariantSpec) {
|
|||
}
|
||||
|
||||
func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*variantProc, error) {
|
||||
dirName := sp.name + "-" + spec.ID
|
||||
dirName := db.VariantDir(sp.name, spec.ID, spec.Height, spec.AudioOnly)
|
||||
wwwDir := filepath.Join(m.DataDir, "www", dirName)
|
||||
_ = os.RemoveAll(wwwDir)
|
||||
if err := os.MkdirAll(wwwDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
index := filepath.Join(wwwDir, "index.m3u8")
|
||||
|
||||
outPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.out.log")
|
||||
errPath := filepath.Join(m.DataDir, "logs", dirName+"-ffmpeg.err.log")
|
||||
outF, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
plan := buildOutputPlan(sp.outputSpecs, wwwDir, sp.cfg, spec)
|
||||
for _, d := range plan.Dirs {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// One encoder, N muxers: the codec args appear once and the tee fans the
|
||||
// encoded frames out. Listing several plain outputs instead would run
|
||||
// libx264 once per format.
|
||||
args := append(inputArgs(sp.tsPath), variantCodecArgs(spec)...)
|
||||
args = append(args, plan.Args...)
|
||||
|
||||
errLog, err := logfile.OpenWithBanner(
|
||||
filepath.Join(m.logsDir(), dirName+"-ffmpeg.err.log"),
|
||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "ffmpeg")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
errF, err := os.OpenFile(errPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
_ = outF.Close()
|
||||
return nil, err
|
||||
|
||||
ffCmd := exec.Command(m.FFmpeg, args...)
|
||||
ffCmd.Stderr = errLog
|
||||
|
||||
var outLog *logfile.Writer
|
||||
if plan.WantsTS {
|
||||
// stdout is this variant's live TS, fanned out to its own ring.
|
||||
ring := m.Fanout.Create(dirName)
|
||||
pipe, err := ffCmd.StdoutPipe()
|
||||
if err != nil {
|
||||
_ = errLog.Close()
|
||||
return nil, err
|
||||
}
|
||||
go func() {
|
||||
_, _ = io.Copy(ring, pipe)
|
||||
_ = ring.Close()
|
||||
}()
|
||||
} else {
|
||||
outLog, err = logfile.Open(
|
||||
filepath.Join(m.logsDir(), dirName+"-ffmpeg.out.log"),
|
||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations)
|
||||
if err != nil {
|
||||
_ = errLog.Close()
|
||||
return nil, err
|
||||
}
|
||||
ffCmd.Stdout = outLog
|
||||
}
|
||||
|
||||
vBitrate := spec.VideoBitrate
|
||||
if vBitrate == "" {
|
||||
vBitrate = "2800k"
|
||||
}
|
||||
aBitrate := spec.AudioBitrate
|
||||
if aBitrate == "" {
|
||||
aBitrate = "128k"
|
||||
}
|
||||
scale := fmt.Sprintf("scale=-2:%d", spec.Height)
|
||||
|
||||
ffArgs := []string{
|
||||
"-hide_banner", "-loglevel", "warning", "-y",
|
||||
"-follow", "1",
|
||||
"-analyzeduration", "20M",
|
||||
"-probesize", "10M",
|
||||
"-fflags", "+genpts",
|
||||
"-i", sp.tsPath,
|
||||
"-map", "0:v:0",
|
||||
"-map", "0:a:0?",
|
||||
"-vf", scale,
|
||||
"-c:v", "libx264",
|
||||
"-preset", "veryfast",
|
||||
"-tune", "zerolatency",
|
||||
"-b:v", vBitrate,
|
||||
"-maxrate", vBitrate,
|
||||
"-bufsize", doubleBitrate(vBitrate),
|
||||
"-g", "48",
|
||||
"-keyint_min", "48",
|
||||
"-sc_threshold", "0",
|
||||
"-c:a", "aac",
|
||||
"-b:a", aBitrate,
|
||||
"-ac", "2",
|
||||
"-f", "hls",
|
||||
"-hls_time", "4",
|
||||
"-hls_list_size", "15",
|
||||
"-hls_flags", "delete_segments+append_list+omit_endlist+independent_segments",
|
||||
"-hls_segment_type", "mpegts",
|
||||
"-hls_segment_filename", filepath.Join(wwwDir, "seg_%05d.ts"),
|
||||
index,
|
||||
}
|
||||
|
||||
ffCmd := exec.Command(m.FFmpeg, ffArgs...)
|
||||
ffCmd.Stdout = outF
|
||||
ffCmd.Stderr = errF
|
||||
hideWindow(ffCmd)
|
||||
if err := ffCmd.Start(); err != nil {
|
||||
_ = outF.Close()
|
||||
_ = errF.Close()
|
||||
_ = errLog.Close()
|
||||
if outLog != nil {
|
||||
_ = outLog.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
vp := &variantProc{
|
||||
spec: spec,
|
||||
wwwDir: wwwDir,
|
||||
index: index,
|
||||
index: filepath.Join(wwwDir, "index.m3u8"),
|
||||
cmd: ffCmd,
|
||||
outLog: outF,
|
||||
errLog: errF,
|
||||
outLog: outLog,
|
||||
errLog: errLog,
|
||||
}
|
||||
go func() {
|
||||
_ = ffCmd.Wait()
|
||||
|
|
@ -159,24 +158,13 @@ func (m *Media) spawnVariantFFmpeg(sp *streamProc, spec db.VariantSpec) (*varian
|
|||
return vp, nil
|
||||
}
|
||||
|
||||
// doubleBitrate is the -bufsize that pairs with a -maxrate.
|
||||
func doubleBitrate(b string) string {
|
||||
b = strings.TrimSpace(b)
|
||||
if b == "" {
|
||||
n := db.BitrateBps(b)
|
||||
if n <= 0 {
|
||||
return "5600k"
|
||||
}
|
||||
num := 0
|
||||
unit := ""
|
||||
for i, r := range b {
|
||||
if r < '0' || r > '9' {
|
||||
unit = b[i:]
|
||||
break
|
||||
}
|
||||
num = num*10 + int(r-'0')
|
||||
}
|
||||
if num <= 0 {
|
||||
return "5600k"
|
||||
}
|
||||
return fmt.Sprintf("%d%s", num*2, unit)
|
||||
return fmt.Sprintf("%dk", n*2/1000)
|
||||
}
|
||||
|
||||
func (m *Media) stopVariant(vp *variantProc) {
|
||||
|
|
@ -186,11 +174,10 @@ func (m *Media) stopVariant(vp *variantProc) {
|
|||
if vp.cmd != nil && vp.cmd.Process != nil {
|
||||
_ = killProcess(vp.cmd)
|
||||
}
|
||||
if vp.outLog != nil {
|
||||
_ = vp.outLog.Close()
|
||||
}
|
||||
if vp.errLog != nil {
|
||||
_ = vp.errLog.Close()
|
||||
for _, w := range []*logfile.Writer{vp.outLog, vp.errLog} {
|
||||
if w != nil {
|
||||
_ = w.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -225,9 +212,11 @@ func (m *Media) restartDeadVariants(sp *streamProc) {
|
|||
|
||||
for _, vp := range dead {
|
||||
m.stopVariant(vp)
|
||||
m.Store.Eventf(sp.id, db.EventVariantDown, db.SevWarn,
|
||||
"variant %s exited; restarting it", vp.spec.ID)
|
||||
fresh, err := m.spawnVariantFFmpeg(sp, vp.spec)
|
||||
if err != nil {
|
||||
m.logf("stream %s variant %s restart: %v", sp.name, vp.spec.ID, err)
|
||||
m.Log.Error("variant restart failed", "stream", sp.name, "variant", vp.spec.ID, "err", err)
|
||||
continue
|
||||
}
|
||||
m.mu.Lock()
|
||||
|
|
@ -239,7 +228,103 @@ func (m *Media) restartDeadVariants(sp *streamProc) {
|
|||
return
|
||||
}
|
||||
m.mu.Unlock()
|
||||
m.logf("stream %s: restarted variant %s", sp.name, vp.spec.ID)
|
||||
m.Log.Info("variant restarted", "stream", sp.name, "variant", vp.spec.ID)
|
||||
m.Store.Eventf(sp.id, db.EventVariantUp, db.SevInfo, "variant %s back up", vp.spec.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// writeMasterPlaylist publishes the ABR master listing every enabled rung.
|
||||
//
|
||||
// streamd writes this itself rather than asking ffmpeg to: each rung is a
|
||||
// separate process writing its own playlist, so nothing but the supervisor
|
||||
// knows the whole ladder. Without a master, the rung playlists are independent
|
||||
// URLs and no player can switch between them.
|
||||
func (m *Media) writeMasterPlaylist(sp *streamProc) {
|
||||
enabled := db.EnabledVariants(sp.variantSpecs)
|
||||
// With one rung there is nothing to switch between.
|
||||
if len(enabled) < 2 {
|
||||
return
|
||||
}
|
||||
// Only meaningful when an HLS-family output is actually published.
|
||||
hls := false
|
||||
for _, o := range db.EnabledOutputs(sp.outputSpecs) {
|
||||
if o.Format == db.FormatHLS || o.Format == db.FormatCMAF {
|
||||
hls = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hls {
|
||||
return
|
||||
}
|
||||
|
||||
bw := make(map[string]int, len(enabled))
|
||||
for _, v := range enabled {
|
||||
bw[v.ID] = m.variantBandwidth(sp, v)
|
||||
}
|
||||
// Highest bandwidth first is conventional, and gives a player a sensible
|
||||
// default before it has measured the connection.
|
||||
sort.SliceStable(enabled, func(i, j int) bool {
|
||||
return bw[enabled[i].ID] > bw[enabled[j].ID]
|
||||
})
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("#EXTM3U\n#EXT-X-VERSION:3\n")
|
||||
b.WriteString("## generated by streamd - do not edit\n")
|
||||
for _, v := range enabled {
|
||||
dir := db.VariantDir(sp.name, v.ID, v.Height, v.AudioOnly)
|
||||
// Relative to the master's own directory, so the playlist keeps
|
||||
// working behind whatever path prefix a reverse proxy adds.
|
||||
rel := "index.m3u8"
|
||||
if dir != sp.name {
|
||||
rel = "../" + dir + "/index.m3u8"
|
||||
}
|
||||
switch {
|
||||
case v.AudioOnly:
|
||||
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,CODECS=\"mp4a.40.2\"\n%s\n", bw[v.ID], rel)
|
||||
case v.Height > 0:
|
||||
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,RESOLUTION=%dx%d\n%s\n",
|
||||
bw[v.ID], db.VariantWidth(v.Height), v.Height, rel)
|
||||
default:
|
||||
// The source rung's real resolution is whatever the origin sends,
|
||||
// so advertise it by bandwidth alone rather than by a guess.
|
||||
fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d\n%s\n", bw[v.ID], rel)
|
||||
}
|
||||
}
|
||||
|
||||
path := filepath.Join(sp.wwwDir, "master.m3u8")
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, []byte(b.String()), 0o644); err != nil {
|
||||
m.Log.Error("write master playlist", "stream", sp.name, "err", err)
|
||||
return
|
||||
}
|
||||
// Rename so a player never reads a half-written master.
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
m.Log.Error("publish master playlist", "stream", sp.name, "err", err)
|
||||
return
|
||||
}
|
||||
m.Log.Info("master playlist published", "stream", sp.name, "rungs", len(enabled))
|
||||
}
|
||||
|
||||
// variantBandwidth estimates a rung's peak bitrate for the master playlist.
|
||||
// A scaled rung is capped by its configured bitrates; the source rung has none,
|
||||
// so the measured value is used with a conservative estimate standing in until
|
||||
// the stream has actually run.
|
||||
func (m *Media) variantBandwidth(sp *streamProc, v db.VariantSpec) int {
|
||||
if v.AudioOnly {
|
||||
if bps := db.BitrateBps(v.AudioBitrate); bps > 0 {
|
||||
return bps
|
||||
}
|
||||
return 96000
|
||||
}
|
||||
if v.Height > 0 {
|
||||
if bps := db.BitrateBps(v.VideoBitrate) + db.BitrateBps(v.AudioBitrate); bps > 0 {
|
||||
return bps
|
||||
}
|
||||
return 2800000
|
||||
}
|
||||
if st, err := m.Store.GetStream(sp.id); err == nil && st.BitrateMbps > 0.1 {
|
||||
return int(st.BitrateMbps * 1e6)
|
||||
}
|
||||
return 6000000
|
||||
}
|
||||
|
|
|
|||
333
apps/streamd/internal/tsfanout/tsfanout.go
Normal file
333
apps/streamd/internal/tsfanout/tsfanout.go
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
// Package tsfanout serves one live MPEG-TS pipe to many HTTP clients.
|
||||
//
|
||||
// The packager writes a single progressive mpegts stream to its stdout; this
|
||||
// package buffers the most recent few seconds of it and hands each client a
|
||||
// copy from a decodable starting point. The cost is one encoder regardless of
|
||||
// how many people are watching, rather than an ffmpeg per viewer.
|
||||
package tsfanout
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// TS constants. An MPEG-TS stream is a continuous grid of 188-byte packets,
|
||||
// each starting with the sync byte 0x47.
|
||||
const (
|
||||
packetSize = 188
|
||||
syncByte = 0x47
|
||||
// pidPAT is the Program Association Table. A client that starts here
|
||||
// learns the stream's structure and can begin decoding; starting at an
|
||||
// arbitrary byte produces garbage.
|
||||
pidPAT = 0
|
||||
)
|
||||
|
||||
// DefaultBufferBytes is a few seconds of a typical broadcast bitrate.
|
||||
const DefaultBufferBytes = 8 << 20
|
||||
|
||||
// ErrLagged is returned to a client that fell so far behind that the bytes it
|
||||
// still needed have been overwritten. Such a client is dropped rather than
|
||||
// allowed to hold the buffer hostage or grow memory.
|
||||
var ErrLagged = errors.New("client fell behind the live buffer")
|
||||
|
||||
// ErrClosed is returned once the source has ended.
|
||||
var ErrClosed = errors.New("stream closed")
|
||||
|
||||
// Ring is a fixed-size circular buffer of the live stream, with absolute byte
|
||||
// offsets so each reader can track its own position.
|
||||
type Ring struct {
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
|
||||
buf []byte
|
||||
// written is the total number of bytes ever written, i.e. the absolute
|
||||
// offset just past the newest byte.
|
||||
written int64
|
||||
closed bool
|
||||
|
||||
// joinAt is the absolute offset of the most recent PAT packet, which is
|
||||
// where a new client should start.
|
||||
joinAt int64
|
||||
// aligned tracks whether we have locked onto the 188-byte packet grid,
|
||||
// and carry holds a partial trailing packet between writes.
|
||||
aligned bool
|
||||
carry []byte
|
||||
// carryAt is the absolute offset of carry[0].
|
||||
carryAt int64
|
||||
|
||||
readers int
|
||||
}
|
||||
|
||||
func New(size int) *Ring {
|
||||
if size < 4*packetSize {
|
||||
size = DefaultBufferBytes
|
||||
}
|
||||
// Whole packets keep the arithmetic honest.
|
||||
size -= size % packetSize
|
||||
r := &Ring{buf: make([]byte, size)}
|
||||
r.cond = sync.NewCond(&r.mu)
|
||||
return r
|
||||
}
|
||||
|
||||
// Write implements io.Writer and is wired to the packager's stdout.
|
||||
func (r *Ring) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.closed {
|
||||
return 0, ErrClosed
|
||||
}
|
||||
total := len(p)
|
||||
r.scanLocked(p)
|
||||
for len(p) > 0 {
|
||||
off := int(r.written % int64(len(r.buf)))
|
||||
n := copy(r.buf[off:], p)
|
||||
r.written += int64(n)
|
||||
p = p[n:]
|
||||
}
|
||||
r.cond.Broadcast()
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// scanLocked walks the incoming bytes on the packet grid and records where the
|
||||
// newest PAT begins. It keeps a carry so packets split across writes are still
|
||||
// seen whole.
|
||||
func (r *Ring) scanLocked(p []byte) {
|
||||
// Absolute offset of p[0].
|
||||
base := r.written
|
||||
|
||||
var data []byte
|
||||
var dataAt int64
|
||||
if len(r.carry) > 0 {
|
||||
data = append(r.carry, p...)
|
||||
dataAt = r.carryAt
|
||||
} else {
|
||||
data = p
|
||||
dataAt = base
|
||||
}
|
||||
|
||||
i := 0
|
||||
for {
|
||||
if !r.aligned {
|
||||
// Look for a sync byte with another one a packet later, which is
|
||||
// strong evidence of real alignment rather than a stray 0x47.
|
||||
found := -1
|
||||
for j := i; j+packetSize < len(data); j++ {
|
||||
if data[j] == syncByte && data[j+packetSize] == syncByte {
|
||||
found = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if found < 0 {
|
||||
break
|
||||
}
|
||||
i = found
|
||||
r.aligned = true
|
||||
}
|
||||
if i+packetSize > len(data) {
|
||||
break
|
||||
}
|
||||
if data[i] != syncByte {
|
||||
// Lost the grid; re-acquire from the next byte.
|
||||
r.aligned = false
|
||||
i++
|
||||
continue
|
||||
}
|
||||
pid := (int(data[i+1]&0x1F) << 8) | int(data[i+2])
|
||||
if pid == pidPAT {
|
||||
r.joinAt = dataAt + int64(i)
|
||||
}
|
||||
i += packetSize
|
||||
}
|
||||
|
||||
// Keep whatever is left of the last partial packet.
|
||||
if rest := len(data) - i; rest > 0 && rest < packetSize {
|
||||
r.carry = append(r.carry[:0], data[i:]...)
|
||||
r.carryAt = dataAt + int64(i)
|
||||
} else {
|
||||
r.carry = r.carry[:0]
|
||||
r.carryAt = 0
|
||||
}
|
||||
}
|
||||
|
||||
// Close ends the stream and wakes every reader.
|
||||
func (r *Ring) Close() error {
|
||||
r.mu.Lock()
|
||||
r.closed = true
|
||||
r.cond.Broadcast()
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Closed reports whether the source has ended.
|
||||
func (r *Ring) Closed() bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.closed
|
||||
}
|
||||
|
||||
// Readers is the current client count.
|
||||
func (r *Ring) Readers() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.readers
|
||||
}
|
||||
|
||||
// Reader is one client's view of the ring.
|
||||
type Reader struct {
|
||||
ring *Ring
|
||||
pos int64
|
||||
done bool
|
||||
}
|
||||
|
||||
// NewReader joins the stream at the most recent decodable point.
|
||||
func (r *Ring) NewReader() *Reader {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
start := r.joinAt
|
||||
// Nothing useful seen yet, or the PAT has already been overwritten: start
|
||||
// from the oldest byte still held.
|
||||
oldest := r.oldestLocked()
|
||||
if start < oldest {
|
||||
start = oldest
|
||||
}
|
||||
r.readers++
|
||||
return &Reader{ring: r, pos: start}
|
||||
}
|
||||
|
||||
func (r *Ring) oldestLocked() int64 {
|
||||
if r.written <= int64(len(r.buf)) {
|
||||
return 0
|
||||
}
|
||||
return r.written - int64(len(r.buf))
|
||||
}
|
||||
|
||||
// Read blocks until bytes are available, the client has lagged, or the stream
|
||||
// ends.
|
||||
func (rd *Reader) Read(p []byte) (int, error) {
|
||||
ring := rd.ring
|
||||
ring.mu.Lock()
|
||||
defer ring.mu.Unlock()
|
||||
for {
|
||||
if rd.pos < ring.oldestLocked() {
|
||||
return 0, ErrLagged
|
||||
}
|
||||
if avail := ring.written - rd.pos; avail > 0 {
|
||||
n := int64(len(p))
|
||||
if avail < n {
|
||||
n = avail
|
||||
}
|
||||
// Do not read past the end of the circular array in one go.
|
||||
off := int(rd.pos % int64(len(ring.buf)))
|
||||
if tail := int64(len(ring.buf) - off); n > tail {
|
||||
n = tail
|
||||
}
|
||||
copy(p[:n], ring.buf[off:off+int(n)])
|
||||
rd.pos += n
|
||||
return int(n), nil
|
||||
}
|
||||
if ring.closed {
|
||||
return 0, io.EOF
|
||||
}
|
||||
ring.cond.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// Close releases the reader.
|
||||
func (rd *Reader) Close() error {
|
||||
if rd.done {
|
||||
return nil
|
||||
}
|
||||
rd.done = true
|
||||
rd.ring.mu.Lock()
|
||||
rd.ring.readers--
|
||||
rd.ring.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set tracks one ring per publish target (a stream's variant), so the HTTP
|
||||
// layer can look one up by name.
|
||||
type Set struct {
|
||||
mu sync.Mutex
|
||||
rings map[string]*Ring
|
||||
size int
|
||||
}
|
||||
|
||||
func NewSet(bufferBytes int) *Set {
|
||||
if bufferBytes <= 0 {
|
||||
bufferBytes = DefaultBufferBytes
|
||||
}
|
||||
return &Set{rings: map[string]*Ring{}, size: bufferBytes}
|
||||
}
|
||||
|
||||
// Create replaces any existing ring for key and returns the new one. The old
|
||||
// ring is closed, which drops its readers — they will reconnect.
|
||||
func (s *Set) Create(key string) *Ring {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if old, ok := s.rings[key]; ok {
|
||||
_ = old.Close()
|
||||
}
|
||||
r := New(s.size)
|
||||
s.rings[key] = r
|
||||
return r
|
||||
}
|
||||
|
||||
// Get returns the live ring for key, if any.
|
||||
func (s *Set) Get(key string) (*Ring, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
r, ok := s.rings[key]
|
||||
if ok && r.Closed() {
|
||||
return nil, false
|
||||
}
|
||||
return r, ok
|
||||
}
|
||||
|
||||
// Remove closes and forgets the ring for key.
|
||||
func (s *Set) Remove(key string) {
|
||||
s.mu.Lock()
|
||||
r, ok := s.rings[key]
|
||||
delete(s.rings, key)
|
||||
s.mu.Unlock()
|
||||
if ok {
|
||||
_ = r.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// RemovePrefix drops every ring whose key starts with prefix, used when a
|
||||
// stream and all its variants stop.
|
||||
func (s *Set) RemovePrefix(prefix string) {
|
||||
s.mu.Lock()
|
||||
var doomed []*Ring
|
||||
for k, r := range s.rings {
|
||||
if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) {
|
||||
doomed = append(doomed, r)
|
||||
delete(s.rings, k)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, r := range doomed {
|
||||
_ = r.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Readers totals the clients across every ring whose key starts with prefix.
|
||||
func (s *Set) Readers(prefix string) int {
|
||||
s.mu.Lock()
|
||||
rings := make([]*Ring, 0, len(s.rings))
|
||||
for k, r := range s.rings {
|
||||
if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) {
|
||||
rings = append(rings, r)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
total := 0
|
||||
for _, r := range rings {
|
||||
total += r.Readers()
|
||||
}
|
||||
return total
|
||||
}
|
||||
304
apps/streamd/internal/tsfanout/tsfanout_test.go
Normal file
304
apps/streamd/internal/tsfanout/tsfanout_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package tsfanout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// tsPacket builds one 188-byte TS packet for the given PID.
|
||||
func tsPacket(pid int, fill byte) []byte {
|
||||
p := make([]byte, packetSize)
|
||||
p[0] = syncByte
|
||||
p[1] = byte(pid>>8) & 0x1F
|
||||
p[2] = byte(pid & 0xFF)
|
||||
p[3] = 0x10
|
||||
for i := 4; i < packetSize; i++ {
|
||||
p[i] = fill
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// tsStream builds a stream whose every n-th packet is a PAT, as ffmpeg's
|
||||
// mpegts muxer emits.
|
||||
func tsStream(packets int, patEvery int) []byte {
|
||||
var b bytes.Buffer
|
||||
for i := 0; i < packets; i++ {
|
||||
if patEvery > 0 && i%patEvery == 0 {
|
||||
b.Write(tsPacket(pidPAT, byte(i)))
|
||||
continue
|
||||
}
|
||||
b.Write(tsPacket(0x100, byte(i)))
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestWriteReturnsFullLength(t *testing.T) {
|
||||
r := New(DefaultBufferBytes)
|
||||
data := tsStream(10, 5)
|
||||
n, err := r.Write(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != len(data) {
|
||||
t.Errorf("Write returned %d, want %d — an io.Writer that under-reports breaks io.Copy", n, len(data))
|
||||
}
|
||||
}
|
||||
|
||||
// A client joining mid-stream must start at a PAT packet, or its decoder has
|
||||
// no idea what it is looking at.
|
||||
func TestReaderJoinsAtPATBoundary(t *testing.T) {
|
||||
r := New(64 * packetSize)
|
||||
// PAT every 5 packets.
|
||||
r.Write(tsStream(20, 5))
|
||||
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
buf := make([]byte, packetSize)
|
||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if buf[0] != syncByte {
|
||||
t.Fatalf("reader did not start on a packet boundary: first byte %#x", buf[0])
|
||||
}
|
||||
pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
|
||||
if pid != pidPAT {
|
||||
t.Errorf("reader started at PID %d, want the PAT (%d)", pid, pidPAT)
|
||||
}
|
||||
}
|
||||
|
||||
// Even when the writes are chopped at arbitrary, non-packet-aligned sizes, the
|
||||
// scanner must still find the grid. A pipe gives no alignment guarantees.
|
||||
func TestPATDetectionAcrossSplitWrites(t *testing.T) {
|
||||
r := New(64 * packetSize)
|
||||
data := tsStream(20, 5)
|
||||
// Deliberately awkward chunk size, coprime with 188.
|
||||
for i := 0; i < len(data); i += 77 {
|
||||
end := i + 77
|
||||
if end > len(data) {
|
||||
end = len(data)
|
||||
}
|
||||
if _, err := r.Write(data[i:end]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
buf := make([]byte, packetSize)
|
||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
|
||||
if buf[0] != syncByte || pid != pidPAT {
|
||||
t.Errorf("split writes broke PAT detection: sync=%#x pid=%d", buf[0], pid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaderStreamsSubsequentWrites(t *testing.T) {
|
||||
r := New(64 * packetSize)
|
||||
r.Write(tsStream(5, 5))
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
|
||||
// Drain what is buffered.
|
||||
buf := make([]byte, 5*packetSize)
|
||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A read with nothing available must block, then return new data.
|
||||
type res struct {
|
||||
n int
|
||||
err error
|
||||
}
|
||||
ch := make(chan res, 1)
|
||||
go func() {
|
||||
b := make([]byte, packetSize)
|
||||
n, err := rd.Read(b)
|
||||
ch <- res{n, err}
|
||||
}()
|
||||
select {
|
||||
case got := <-ch:
|
||||
t.Fatalf("Read returned early (%d, %v) instead of waiting for data", got.n, got.err)
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
r.Write(tsPacket(0x100, 9))
|
||||
select {
|
||||
case got := <-ch:
|
||||
if got.err != nil || got.n == 0 {
|
||||
t.Fatalf("Read after write: %d %v", got.n, got.err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Read did not wake after a write")
|
||||
}
|
||||
}
|
||||
|
||||
// A stalled client must be dropped, not allowed to stall the writer or grow
|
||||
// memory. This is the backpressure decision that keeps one slow viewer from
|
||||
// affecting the stream.
|
||||
func TestLaggedReaderIsDropped(t *testing.T) {
|
||||
size := 8 * packetSize
|
||||
r := New(size)
|
||||
r.Write(tsStream(4, 4))
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
|
||||
// Overwrite the whole buffer several times without the reader consuming.
|
||||
for i := 0; i < 5; i++ {
|
||||
r.Write(tsStream(8, 8))
|
||||
}
|
||||
buf := make([]byte, packetSize)
|
||||
_, err := rd.Read(buf)
|
||||
if !errors.Is(err, ErrLagged) {
|
||||
t.Errorf("want ErrLagged for a stalled client, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleReadersGetSameBytes(t *testing.T) {
|
||||
r := New(64 * packetSize)
|
||||
// Three clients, one source: the whole point of the package.
|
||||
a, b, c := r.NewReader(), r.NewReader(), r.NewReader()
|
||||
defer a.Close()
|
||||
defer b.Close()
|
||||
defer c.Close()
|
||||
if got := r.Readers(); got != 3 {
|
||||
t.Fatalf("Readers() = %d, want 3", got)
|
||||
}
|
||||
|
||||
data := tsStream(10, 5)
|
||||
r.Write(data)
|
||||
read := func(rd *Reader) []byte {
|
||||
out := make([]byte, 10*packetSize)
|
||||
if _, err := io.ReadFull(rd, out); err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
ra, rb, rc := read(a), read(b), read(c)
|
||||
if !bytes.Equal(ra, rb) || !bytes.Equal(rb, rc) {
|
||||
t.Error("readers received different bytes from the same source")
|
||||
}
|
||||
|
||||
// Closing one must not disturb the others.
|
||||
_ = a.Close()
|
||||
if got := r.Readers(); got != 2 {
|
||||
t.Errorf("after one close, Readers() = %d, want 2", got)
|
||||
}
|
||||
r.Write(tsPacket(0x100, 1))
|
||||
one := make([]byte, packetSize)
|
||||
if _, err := io.ReadFull(b, one); err != nil {
|
||||
t.Errorf("surviving reader broke after another closed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseEndsReaders(t *testing.T) {
|
||||
r := New(64 * packetSize)
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
b := make([]byte, packetSize)
|
||||
_, err := rd.Read(b)
|
||||
done <- err
|
||||
}()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
_ = r.Close()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, io.EOF) {
|
||||
t.Errorf("want io.EOF after Close, got %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Close did not wake a blocked reader")
|
||||
}
|
||||
if _, err := r.Write([]byte("x")); !errors.Is(err, ErrClosed) {
|
||||
t.Errorf("write after close should fail, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The ring must wrap correctly: reading across the seam has to produce the
|
||||
// bytes that were written, not a torn copy.
|
||||
func TestRingWrapsCorrectly(t *testing.T) {
|
||||
size := 16 * packetSize
|
||||
r := New(size)
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
|
||||
// Write and drain repeatedly so the write position passes the end of the
|
||||
// array several times.
|
||||
var want, got bytes.Buffer
|
||||
for round := 0; round < 10; round++ {
|
||||
chunk := tsStream(6, 6)
|
||||
r.Write(chunk)
|
||||
want.Write(chunk)
|
||||
buf := make([]byte, len(chunk))
|
||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
||||
t.Fatalf("round %d: %v", round, err)
|
||||
}
|
||||
got.Write(buf)
|
||||
}
|
||||
if !bytes.Equal(want.Bytes(), got.Bytes()) {
|
||||
t.Error("data read across the ring wrap does not match what was written")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetLifecycle(t *testing.T) {
|
||||
s := NewSet(16 * packetSize)
|
||||
if _, ok := s.Get("city-news"); ok {
|
||||
t.Error("empty set should not resolve a key")
|
||||
}
|
||||
r := s.Create("city-news")
|
||||
if got, ok := s.Get("city-news"); !ok || got != r {
|
||||
t.Error("Create then Get should return the same ring")
|
||||
}
|
||||
|
||||
// Creating again replaces and closes the old ring, so its readers drop.
|
||||
rd := r.NewReader()
|
||||
defer rd.Close()
|
||||
r2 := s.Create("city-news")
|
||||
if r2 == r {
|
||||
t.Error("Create should replace the existing ring")
|
||||
}
|
||||
if !r.Closed() {
|
||||
t.Error("the replaced ring should be closed")
|
||||
}
|
||||
|
||||
// Prefix removal covers a stream and all of its variants at once.
|
||||
s.Create("city-news-hd")
|
||||
s.Create("other")
|
||||
s.RemovePrefix("city-news")
|
||||
if _, ok := s.Get("city-news"); ok {
|
||||
t.Error("city-news should be gone")
|
||||
}
|
||||
if _, ok := s.Get("city-news-hd"); ok {
|
||||
t.Error("city-news-hd should be gone")
|
||||
}
|
||||
if _, ok := s.Get("other"); !ok {
|
||||
t.Error("unrelated key should survive RemovePrefix")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetReadersCountsAcrossVariants(t *testing.T) {
|
||||
s := NewSet(16 * packetSize)
|
||||
a := s.Create("news")
|
||||
b := s.Create("news-hd")
|
||||
r1, r2, r3 := a.NewReader(), b.NewReader(), b.NewReader()
|
||||
defer r1.Close()
|
||||
defer r2.Close()
|
||||
defer r3.Close()
|
||||
if got := s.Readers("news"); got != 3 {
|
||||
t.Errorf("Readers(news) = %d, want 3 across both variants", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A closed ring must not be handed out as live.
|
||||
func TestGetSkipsClosedRing(t *testing.T) {
|
||||
s := NewSet(16 * packetSize)
|
||||
r := s.Create("x")
|
||||
_ = r.Close()
|
||||
if _, ok := s.Get("x"); ok {
|
||||
t.Error("Get should not return a closed ring")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,211 +0,0 @@
|
|||
:root {
|
||||
--bg: #0f1115;
|
||||
--card: #171a21;
|
||||
--border: #2a303c;
|
||||
--text: #e8eaed;
|
||||
--muted: #9aa0a6;
|
||||
--accent: #7aa2ff;
|
||||
--ok: #3dd68c;
|
||||
--degraded: #f5a524;
|
||||
--down: #f07178;
|
||||
--stopped: #6b7280;
|
||||
--chip: #1c2230;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font: 14px/1.45 system-ui, Segoe UI, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
h1 { margin: 0; font-size: 18px; font-weight: 600; }
|
||||
h2 { margin: 0 0 12px; font-size: 15px; font-weight: 600; }
|
||||
.header-right { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; }
|
||||
.muted { color: var(--muted); }
|
||||
.card {
|
||||
margin: 16px 20px;
|
||||
padding: 16px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px 14px;
|
||||
}
|
||||
.span2 { grid-column: span 2; }
|
||||
label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
|
||||
input, select, button, textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: #0c0e12;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
textarea {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
resize: vertical;
|
||||
min-height: 4.5em;
|
||||
white-space: pre;
|
||||
}
|
||||
button {
|
||||
background: #243044;
|
||||
border-color: #334155;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { border-color: var(--accent); }
|
||||
button.ghost { background: transparent; }
|
||||
button.danger { border-color: #7f1d1d; color: #fecaca; }
|
||||
button.tiny {
|
||||
padding: 3px 8px;
|
||||
font-size: 11px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.actions { display: flex; gap: 8px; align-items: end; }
|
||||
.token-box input { width: 180px; }
|
||||
.row-between { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 10px 6px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
th { color: var(--muted); font-weight: 500; font-size: 12px; }
|
||||
.pill {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
background: #222;
|
||||
}
|
||||
.pill.ok { color: var(--ok); }
|
||||
.pill.degraded { color: var(--degraded); }
|
||||
.pill.down, .pill.starting, .pill.pending { color: var(--down); }
|
||||
.pill.stopped, .pill.off { color: var(--stopped); }
|
||||
.pill.claim { color: #c4b5fd; background: #1f1635; }
|
||||
.row-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.row-actions button { padding: 4px 8px; font-size: 12px; }
|
||||
.msg { min-height: 1.2em; margin: 8px 0 0; }
|
||||
.msg.err { color: var(--down); }
|
||||
a { color: var(--accent); }
|
||||
code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
|
||||
|
||||
.variants-field {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
.variants-field legend {
|
||||
padding: 0 6px;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.hint { margin: 0 0 10px; color: var(--muted); font-size: 12px; }
|
||||
.variant-toggles {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.variant-card {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-rows: auto auto;
|
||||
column-gap: 8px;
|
||||
row-gap: 2px;
|
||||
align-items: center;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #12151c;
|
||||
cursor: pointer;
|
||||
color: var(--text);
|
||||
}
|
||||
.variant-card input {
|
||||
grid-row: 1 / span 2;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.variant-card .v-title { font-weight: 600; font-size: 13px; color: var(--text); }
|
||||
.variant-card .v-meta { font-size: 11px; color: var(--muted); }
|
||||
.variant-card.on,
|
||||
.variant-card:has(input:checked) {
|
||||
border-color: #3b82f6;
|
||||
background: #152033;
|
||||
box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.25);
|
||||
}
|
||||
.variant-card.locked {
|
||||
opacity: 0.92;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.link-stack { display: flex; flex-direction: column; gap: 6px; min-width: 180px; }
|
||||
.link-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
padding: 6px 8px;
|
||||
background: var(--chip);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.link-row .v-label {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
min-width: 2.4em;
|
||||
color: var(--accent);
|
||||
}
|
||||
.link-row .v-path {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.link-row .pill { margin-left: auto; }
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
background: #1e293b;
|
||||
border: 1px solid #334155;
|
||||
color: var(--text);
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,.35);
|
||||
z-index: 50;
|
||||
font-size: 13px;
|
||||
}
|
||||
.toast.show { display: block; }
|
||||
|
||||
dialog {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--card);
|
||||
color: var(--text);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
min-width: min(640px, 94vw);
|
||||
}
|
||||
dialog::backdrop { background: rgba(0,0,0,.55); }
|
||||
@media (max-width: 720px) {
|
||||
.grid { grid-template-columns: 1fr; }
|
||||
.span2 { grid-column: span 1; }
|
||||
.variant-toggles { grid-template-columns: 1fr; }
|
||||
header { flex-direction: column; align-items: flex-start; gap: 8px; }
|
||||
}
|
||||
|
|
@ -1,440 +0,0 @@
|
|||
(() => {
|
||||
const tokenEl = document.getElementById("token");
|
||||
const rowsEl = document.getElementById("rows");
|
||||
const listMsg = document.getElementById("list-msg");
|
||||
const formMsg = document.getElementById("form-msg");
|
||||
const uptimeEl = document.getElementById("uptime");
|
||||
const agentsEl = document.getElementById("agents-status");
|
||||
const dlg = document.getElementById("edit-dlg");
|
||||
const editForm = document.getElementById("edit-form");
|
||||
const toastEl = document.getElementById("toast");
|
||||
|
||||
tokenEl.value = localStorage.getItem("streamd_token") || "";
|
||||
tokenEl.addEventListener("change", () => {
|
||||
localStorage.setItem("streamd_token", tokenEl.value.trim());
|
||||
connectUIWS();
|
||||
});
|
||||
|
||||
function token() {
|
||||
return tokenEl.value.trim();
|
||||
}
|
||||
|
||||
function headers(json) {
|
||||
const h = {};
|
||||
if (json) h["Content-Type"] = "application/json";
|
||||
const t = token();
|
||||
if (t) h["Authorization"] = "Bearer " + t;
|
||||
return h;
|
||||
}
|
||||
|
||||
async function api(path, opts = {}) {
|
||||
const res = await fetch(path, opts);
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
|
||||
if (!res.ok) {
|
||||
const msg = (data && data.error) || res.statusText || "request failed";
|
||||
throw new Error(msg);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function age(s) {
|
||||
if (s == null || s === 0) return "—";
|
||||
return Number(s).toFixed(1) + "s";
|
||||
}
|
||||
|
||||
function absURL(path) {
|
||||
if (!path) return "";
|
||||
try { return new URL(path, location.origin).href; } catch { return path; }
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(msg) {
|
||||
if (!toastEl) return;
|
||||
toastEl.hidden = false;
|
||||
toastEl.classList.add("show");
|
||||
toastEl.textContent = msg;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => {
|
||||
toastEl.hidden = true;
|
||||
toastEl.classList.remove("show");
|
||||
}, 1800);
|
||||
}
|
||||
|
||||
async function copyText(text) {
|
||||
if (!text) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast("Copied m3u8 link");
|
||||
} catch {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.left = "-9999px";
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try { document.execCommand("copy"); toast("Copied m3u8 link"); }
|
||||
catch { toast("Copy failed"); }
|
||||
ta.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function claimLabel(s) {
|
||||
if (!s.claimed_by) return '<span class="muted">—</span>';
|
||||
let exp = "";
|
||||
if (s.claim_expires_at) {
|
||||
const ms = Date.parse(s.claim_expires_at) - Date.now();
|
||||
if (!Number.isNaN(ms)) {
|
||||
exp = ms > 0 ? ` (${Math.ceil(ms / 1000)}s)` : " (expired)";
|
||||
}
|
||||
}
|
||||
return `<span class="pill claim">${esc(s.claimed_by)}${esc(exp)}</span>`;
|
||||
}
|
||||
|
||||
function enabledVariants(s) {
|
||||
const list = Array.isArray(s.variants) ? s.variants : [];
|
||||
const enabled = list.filter((v) => v && v.enabled !== false && v.health !== "off");
|
||||
if (enabled.length) return enabled;
|
||||
return [{
|
||||
id: "fhd",
|
||||
label: "FHD",
|
||||
enabled: true,
|
||||
height: 0,
|
||||
play_path: s.play_path || ("/hls/" + s.name + "/index.m3u8"),
|
||||
health: s.health || "stopped",
|
||||
playlist_age_s: s.playlist_age_s,
|
||||
}];
|
||||
}
|
||||
|
||||
function linksCell(s) {
|
||||
const vars = enabledVariants(s);
|
||||
return `<div class="link-stack">${vars.map((v) => {
|
||||
const path = v.play_path || "";
|
||||
const url = absURL(path);
|
||||
const label = v.label || v.id || "FHD";
|
||||
const health = v.health || s.health || "stopped";
|
||||
return `<div class="link-row">
|
||||
<span class="v-label">${esc(label)}</span>
|
||||
<span class="v-path" title="${esc(url)}">${esc(path)}</span>
|
||||
<span class="pill ${esc(health)}">${esc(health)}</span>
|
||||
<button type="button" class="tiny ghost" data-act="copy-link" data-url="${esc(url)}" title="Copy m3u8 URL">Copy</button>
|
||||
</div>`;
|
||||
}).join("")}</div>`;
|
||||
}
|
||||
|
||||
function render(streams) {
|
||||
if (!streams.length) {
|
||||
rowsEl.innerHTML = "";
|
||||
listMsg.textContent = "No streams yet. Add one above.";
|
||||
return;
|
||||
}
|
||||
listMsg.textContent = streams.length + " stream(s)";
|
||||
rowsEl.innerHTML = streams.map((s) => {
|
||||
const need = !s.mpd ? " needs MPD" : "";
|
||||
return `<tr>
|
||||
<td><strong>${esc(s.name)}</strong><div class="muted">${esc(s.title || "")}${need}</div></td>
|
||||
<td>${esc(s.app)} / ${esc(s.channel)}</td>
|
||||
<td><span class="pill ${esc(s.health || "stopped")}">${esc(s.health || "stopped")}</span></td>
|
||||
<td>${claimLabel(s)}</td>
|
||||
<td>${age(s.playlist_age_s)}</td>
|
||||
<td>${linksCell(s)}</td>
|
||||
<td class="row-actions">
|
||||
<button data-act="start" data-id="${s.id}">Start</button>
|
||||
<button data-act="stop" data-id="${s.id}" class="ghost">Stop</button>
|
||||
<button data-act="restart" data-id="${s.id}" class="ghost">Restart</button>
|
||||
<button data-act="edit" data-id="${s.id}" class="ghost">Edit</button>
|
||||
${s.claimed_by ? `<button data-act="unclaim" data-id="${s.id}" class="ghost">Release</button>` : ""}
|
||||
<button data-act="delete" data-id="${s.id}" class="danger">Delete</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function esc(v) {
|
||||
return String(v ?? "").replace(/[&<>"']/g, (c) => ({
|
||||
"&": "&", "<": "<", ">": ">", '"': """, "'": "'"
|
||||
}[c]));
|
||||
}
|
||||
|
||||
function readVariantToggles(root) {
|
||||
const cards = root.querySelectorAll(".variant-card input[data-id]");
|
||||
const out = [];
|
||||
cards.forEach((input) => {
|
||||
const id = input.dataset.id;
|
||||
const height = Number(input.dataset.height || 0);
|
||||
const enabled = id === "fhd" ? true : !!input.checked;
|
||||
const item = {
|
||||
id,
|
||||
label: id.toUpperCase(),
|
||||
enabled,
|
||||
height: id === "fhd" ? 0 : height,
|
||||
};
|
||||
if (height > 0) {
|
||||
item.video_bitrate = input.dataset.vbr || "";
|
||||
item.audio_bitrate = input.dataset.abr || "";
|
||||
}
|
||||
out.push(item);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function setVariantToggles(root, variants) {
|
||||
const byId = {};
|
||||
(variants || []).forEach((v) => { byId[v.id] = v; });
|
||||
root.querySelectorAll(".variant-card input[data-id]").forEach((input) => {
|
||||
const id = input.dataset.id;
|
||||
if (id === "fhd") {
|
||||
input.checked = true;
|
||||
return;
|
||||
}
|
||||
const v = byId[id];
|
||||
input.checked = !!(v && v.enabled);
|
||||
const card = input.closest(".variant-card");
|
||||
if (card) card.classList.toggle("on", input.checked);
|
||||
});
|
||||
}
|
||||
|
||||
function wireVariantCards(root) {
|
||||
root.querySelectorAll(".variant-card").forEach((card) => {
|
||||
const input = card.querySelector("input[type=checkbox]");
|
||||
if (!input || input.disabled) {
|
||||
card.classList.add("on");
|
||||
return;
|
||||
}
|
||||
const sync = () => card.classList.toggle("on", input.checked);
|
||||
input.addEventListener("change", sync);
|
||||
sync();
|
||||
});
|
||||
}
|
||||
|
||||
wireVariantCards(document.getElementById("create-variants"));
|
||||
wireVariantCards(document.getElementById("edit-variants"));
|
||||
|
||||
function renderAgents(list) {
|
||||
if (!agentsEl) return;
|
||||
if (!list || !list.length) {
|
||||
agentsEl.textContent = "agents: none connected";
|
||||
return;
|
||||
}
|
||||
agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", ");
|
||||
}
|
||||
|
||||
const depsEl = document.getElementById("deps-status");
|
||||
|
||||
function renderDeps(d) {
|
||||
if (!depsEl || !d) return;
|
||||
const bit = (label, path) => (path ? label + "✓" : label + "✗");
|
||||
depsEl.textContent = [
|
||||
bit("ffmpeg", d.ffmpeg),
|
||||
bit("nre", d.nre),
|
||||
bit("mp4decrypt", d.mp4decrypt),
|
||||
].join(" · ");
|
||||
depsEl.title = [
|
||||
"bin: " + (d.bin_dir || ""),
|
||||
"ffmpeg: " + (d.ffmpeg || "(missing)"),
|
||||
"nre: " + (d.nre || "(missing)"),
|
||||
"mp4decrypt: " + (d.mp4decrypt || "(missing)"),
|
||||
...(d.notes || []),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const [health, list, agents] = await Promise.all([
|
||||
api("/api/health"),
|
||||
api("/api/streams"),
|
||||
api("/api/agents").catch(() => ({ agents: [] })),
|
||||
]);
|
||||
uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s";
|
||||
renderDeps(health.deps);
|
||||
render(list.streams || []);
|
||||
renderAgents(agents.agents || []);
|
||||
listMsg.classList.remove("err");
|
||||
} catch (e) {
|
||||
listMsg.textContent = e.message;
|
||||
listMsg.classList.add("err");
|
||||
}
|
||||
}
|
||||
|
||||
const appSel = document.getElementById("app-select");
|
||||
const chanSel = document.getElementById("channel-select");
|
||||
let apps = [];
|
||||
|
||||
function fillChannels() {
|
||||
const a = apps.find((x) => x.name === appSel.value);
|
||||
chanSel.innerHTML = "";
|
||||
if (!a || !a.channels.length) {
|
||||
const o = document.createElement("option");
|
||||
o.value = "";
|
||||
o.textContent = a ? "(no module.yaml — no channels)" : "(no apps)";
|
||||
chanSel.appendChild(o);
|
||||
return;
|
||||
}
|
||||
for (const ch of a.channels) {
|
||||
const o = document.createElement("option");
|
||||
o.value = ch.id;
|
||||
o.textContent = ch.label && ch.label !== ch.id ? ch.id + " — " + ch.label : ch.id;
|
||||
chanSel.appendChild(o);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadApps() {
|
||||
try {
|
||||
const data = await api("/api/apps");
|
||||
apps = data.apps || [];
|
||||
} catch (e) {
|
||||
apps = [];
|
||||
}
|
||||
appSel.innerHTML = "";
|
||||
if (!apps.length) {
|
||||
const o = document.createElement("option");
|
||||
o.value = "";
|
||||
o.textContent = "(no app modules compiled in)";
|
||||
appSel.appendChild(o);
|
||||
}
|
||||
for (const a of apps) {
|
||||
const o = document.createElement("option");
|
||||
o.value = a.name;
|
||||
o.textContent = a.name;
|
||||
appSel.appendChild(o);
|
||||
}
|
||||
fillChannels();
|
||||
}
|
||||
|
||||
appSel.addEventListener("change", fillChannels);
|
||||
loadApps();
|
||||
|
||||
document.getElementById("refresh").addEventListener("click", refresh);
|
||||
|
||||
document.getElementById("create-form").addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
formMsg.textContent = "";
|
||||
formMsg.classList.remove("err");
|
||||
const fd = new FormData(ev.target);
|
||||
const body = Object.fromEntries(fd.entries());
|
||||
body.variants = readVariantToggles(document.getElementById("create-variants"));
|
||||
try {
|
||||
await api("/api/streams", {
|
||||
method: "POST",
|
||||
headers: headers(true),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
ev.target.reset();
|
||||
ev.target.headers_json.value = "{}";
|
||||
setVariantToggles(document.getElementById("create-variants"), [
|
||||
{ id: "fhd", enabled: true },
|
||||
{ id: "hd", enabled: false },
|
||||
{ id: "sd", enabled: false },
|
||||
]);
|
||||
fillChannels();
|
||||
formMsg.textContent = "Created.";
|
||||
refresh();
|
||||
} catch (e) {
|
||||
formMsg.textContent = e.message;
|
||||
formMsg.classList.add("err");
|
||||
}
|
||||
});
|
||||
|
||||
rowsEl.addEventListener("click", async (ev) => {
|
||||
const btn = ev.target.closest("button[data-act]");
|
||||
if (!btn) return;
|
||||
const act = btn.dataset.act;
|
||||
if (act === "copy-link") {
|
||||
copyText(btn.dataset.url || "");
|
||||
return;
|
||||
}
|
||||
const id = btn.dataset.id;
|
||||
try {
|
||||
if (act === "delete") {
|
||||
if (!confirm("Delete stream #" + id + "?")) return;
|
||||
await api("/api/streams/" + id, { method: "DELETE", headers: headers(false) });
|
||||
} else if (act === "unclaim") {
|
||||
await api("/api/streams/" + id + "/claim/release", {
|
||||
method: "POST",
|
||||
headers: headers(true),
|
||||
body: JSON.stringify({ agent_id: "" }),
|
||||
});
|
||||
} else if (act === "edit") {
|
||||
const st = await api("/api/streams/" + id);
|
||||
editForm.id.value = st.id;
|
||||
editForm.title.value = st.title || "";
|
||||
editForm.channel.value = st.channel || "";
|
||||
editForm.mpd.value = st.mpd || "";
|
||||
editForm.key.value = st.key || "";
|
||||
if (editForm.proxy) editForm.proxy.value = st.proxy || "";
|
||||
editForm.headers_json.value = st.headers_json || "{}";
|
||||
setVariantToggles(document.getElementById("edit-variants"), st.variants || []);
|
||||
dlg.showModal();
|
||||
return;
|
||||
} else {
|
||||
await api("/api/streams/" + id + "/" + act, {
|
||||
method: "POST",
|
||||
headers: headers(false),
|
||||
});
|
||||
}
|
||||
refresh();
|
||||
} catch (e) {
|
||||
listMsg.textContent = e.message;
|
||||
listMsg.classList.add("err");
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("edit-cancel").addEventListener("click", () => dlg.close());
|
||||
|
||||
editForm.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const id = editForm.id.value;
|
||||
const body = {
|
||||
title: editForm.title.value,
|
||||
channel: editForm.channel.value,
|
||||
mpd: editForm.mpd.value,
|
||||
key: editForm.key.value,
|
||||
proxy: editForm.proxy ? editForm.proxy.value : "",
|
||||
headers_json: editForm.headers_json.value,
|
||||
variants: readVariantToggles(document.getElementById("edit-variants")),
|
||||
};
|
||||
try {
|
||||
await api("/api/streams/" + id, {
|
||||
method: "PATCH",
|
||||
headers: headers(true),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
dlg.close();
|
||||
refresh();
|
||||
} catch (e) {
|
||||
alert(e.message);
|
||||
}
|
||||
});
|
||||
|
||||
let uiWS = null;
|
||||
let uiWSTimer = null;
|
||||
function connectUIWS() {
|
||||
if (uiWS) {
|
||||
try { uiWS.close(); } catch {}
|
||||
uiWS = null;
|
||||
}
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const ws = new WebSocket(proto + "//" + location.host + "/ws/ui");
|
||||
uiWS = ws;
|
||||
ws.onmessage = (ev) => {
|
||||
try {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.type === "agents" || msg.type === "agent_online" || msg.type === "agent_offline") {
|
||||
renderAgents(msg.agents || []);
|
||||
}
|
||||
if (msg.type === "claims_changed" || msg.type === "agent_offline") {
|
||||
refresh();
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
ws.onclose = () => {
|
||||
clearTimeout(uiWSTimer);
|
||||
uiWSTimer = setTimeout(connectUIWS, 3000);
|
||||
};
|
||||
}
|
||||
|
||||
refresh();
|
||||
connectUIWS();
|
||||
setInterval(refresh, 5000);
|
||||
})();
|
||||
|
|
@ -4,128 +4,102 @@
|
|||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>streamd</title>
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<link rel="stylesheet" href="/static/app.css" />
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%23c47a12'/%3E%3Cpath d='M12 9l12 7-12 7z' fill='white'/%3E%3C/svg%3E" />
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>streamd</h1>
|
||||
<div class="header-right">
|
||||
<span id="uptime" class="muted"></span>
|
||||
<span id="deps-status" class="muted" title="Media tool paths"></span>
|
||||
<label class="token-box">token <input id="token" type="password" placeholder="STREAMD_TOKEN" autocomplete="off" /></label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="card">
|
||||
<h2>Add stream</h2>
|
||||
<form id="create-form" class="grid">
|
||||
<label>name <input name="name" required placeholder="my-channel" /></label>
|
||||
<label>title <input name="title" placeholder="My Channel" /></label>
|
||||
<label>app
|
||||
<select name="app" id="app-select"></select>
|
||||
</label>
|
||||
<label>channel
|
||||
<select name="channel" id="channel-select"></select>
|
||||
</label>
|
||||
<label class="span2">mpd <input name="mpd" placeholder="https://…/manifest.mpd (required to start)" /></label>
|
||||
<label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY lines (clear streams like BBC need no keys)" spellcheck="false"></textarea></label>
|
||||
<label class="span2">proxy <input name="proxy" placeholder="optional — socks5://127.0.0.1:1080 or http://127.0.0.1:8080 (origin fetch)" /></label>
|
||||
<label class="span2">headers JSON <input name="headers_json" value="{}" /></label>
|
||||
<fieldset class="span2 variants-field">
|
||||
<legend>Output variants</legend>
|
||||
<p class="hint">FHD is the source copy. Enable HD / SD to also publish scaled HLS playlists as separate streams.</p>
|
||||
<div class="variant-toggles" id="create-variants">
|
||||
<label class="variant-card on locked">
|
||||
<input type="checkbox" data-id="fhd" checked disabled />
|
||||
<span class="v-title">FHD</span>
|
||||
<span class="v-meta">source · copy</span>
|
||||
</label>
|
||||
<label class="variant-card">
|
||||
<input type="checkbox" data-id="hd" data-height="720" data-vbr="2800k" data-abr="128k" />
|
||||
<span class="v-title">HD</span>
|
||||
<span class="v-meta">720p · 2800k</span>
|
||||
</label>
|
||||
<label class="variant-card">
|
||||
<input type="checkbox" data-id="sd" data-height="480" data-vbr="1200k" data-abr="96k" />
|
||||
<span class="v-title">SD</span>
|
||||
<span class="v-meta">480p · 1200k</span>
|
||||
</label>
|
||||
<!-- The shell is static; every view is rendered into #view by the router. -->
|
||||
<div id="app" hidden>
|
||||
<aside id="sidebar">
|
||||
<div class="brand">
|
||||
<span class="logo" aria-hidden="true"></span>
|
||||
<span class="brand-name">streamd</span>
|
||||
<button type="button" id="nav-close" class="icon-btn only-mobile" aria-label="Close menu">×</button>
|
||||
</div>
|
||||
<nav id="nav">
|
||||
<a href="#/" data-nav="/">
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="2" width="5" height="5" rx="1"/><rect x="9" y="2" width="5" height="5" rx="1"/><rect x="2" y="9" width="5" height="5" rx="1"/><rect x="9" y="9" width="5" height="5" rx="1"/></svg></span>
|
||||
Dashboard
|
||||
</a>
|
||||
<a href="#/streams" data-nav="/streams">
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 4h12M2 8h12M2 12h8"/></svg></span>
|
||||
Streams
|
||||
</a>
|
||||
<a href="#/schedule" data-nav="/schedule">
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="8" cy="8" r="5.5"/><path d="M8 5v3.5l2.5 1.5"/></svg></span>
|
||||
Schedule
|
||||
</a>
|
||||
<a href="#/settings" data-nav="/settings" data-admin>
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.8v1.6M8 12.6v1.6M1.8 8h1.6M12.6 8h1.6M3.4 3.4l1.1 1.1M11.5 11.5l1.1 1.1M3.4 12.6l1.1-1.1M11.5 4.5l1.1-1.1"/></svg></span>
|
||||
Settings
|
||||
</a>
|
||||
<a href="#/people" data-nav="/people" data-admin>
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="6" cy="5.5" r="2.2"/><path d="M1.8 13c0-2.3 1.9-4.2 4.2-4.2s4.2 1.9 4.2 4.2"/><path d="M11 7.2a2 2 0 1 0 0-4"/><path d="M12.8 13c0-1.5-.7-2.8-1.8-3.5"/></svg></span>
|
||||
People & keys
|
||||
</a>
|
||||
<a href="#/audit" data-nav="/audit" data-admin>
|
||||
<span class="ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M4 2.5h6.5L13 5v8.5H4z"/><path d="M10.5 2.5V5H13"/><path d="M6 8h4M6 10.5h3"/></svg></span>
|
||||
Audit log
|
||||
</a>
|
||||
</nav>
|
||||
<div class="sidebar-foot">
|
||||
<div id="agent-chip" class="chip" title="Capture agents connected">
|
||||
<span class="chip-label">Agents</span>
|
||||
<span class="chip-val">—</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="span2 actions">
|
||||
<button type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
<p id="form-msg" class="msg"></p>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="row-between">
|
||||
<h2>Streams</h2>
|
||||
<div class="row-actions">
|
||||
<span id="agents-status" class="muted">agents: —</span>
|
||||
<button type="button" id="refresh" class="ghost">Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>name</th>
|
||||
<th>app / channel</th>
|
||||
<th>health</th>
|
||||
<th>claim</th>
|
||||
<th>age</th>
|
||||
<th>links</th>
|
||||
<th>actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="rows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p id="list-msg" class="msg muted">Loading…</p>
|
||||
</section>
|
||||
|
||||
<dialog id="edit-dlg">
|
||||
<form method="dialog" id="edit-form" class="grid">
|
||||
<h2 class="span2">Edit stream</h2>
|
||||
<input type="hidden" name="id" />
|
||||
<label>title <input name="title" /></label>
|
||||
<label>channel <input name="channel" /></label>
|
||||
<label class="span2">mpd <input name="mpd" /></label>
|
||||
<label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY (one per line)" spellcheck="false"></textarea></label>
|
||||
<label class="span2">proxy <input name="proxy" placeholder="socks5://127.0.0.1:1080" /></label>
|
||||
<label class="span2">headers JSON <input name="headers_json" /></label>
|
||||
<fieldset class="span2 variants-field">
|
||||
<legend>Output variants</legend>
|
||||
<p class="hint">Each enabled rung publishes its own <code>m3u8</code>. FHD stays the source; HD/SD are live-transcoded.</p>
|
||||
<div class="variant-toggles" id="edit-variants">
|
||||
<label class="variant-card on locked">
|
||||
<input type="checkbox" data-id="fhd" checked disabled />
|
||||
<span class="v-title">FHD</span>
|
||||
<span class="v-meta">source · copy</span>
|
||||
</label>
|
||||
<label class="variant-card">
|
||||
<input type="checkbox" data-id="hd" data-height="720" data-vbr="2800k" data-abr="128k" />
|
||||
<span class="v-title">HD</span>
|
||||
<span class="v-meta">720p · 2800k</span>
|
||||
</label>
|
||||
<label class="variant-card">
|
||||
<input type="checkbox" data-id="sd" data-height="480" data-vbr="1200k" data-abr="96k" />
|
||||
<span class="v-title">SD</span>
|
||||
<span class="v-meta">480p · 1200k</span>
|
||||
</label>
|
||||
<div id="deps-chip" class="chip" title="Media tool availability">
|
||||
<span class="chip-label">Tools</span>
|
||||
<span class="chip-val">—</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="span2 actions">
|
||||
<button type="submit" value="save">Save</button>
|
||||
<button type="button" id="edit-cancel" class="ghost">Cancel</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div id="main">
|
||||
<header id="topbar">
|
||||
<button type="button" id="nav-open" class="icon-btn only-mobile" aria-label="Open menu">☰</button>
|
||||
<h1 id="page-title">Dashboard</h1>
|
||||
<div class="spacer"></div>
|
||||
<span id="conn" class="conn" title="Live connection">Live</span>
|
||||
<span id="uptime" class="muted" title="Server uptime"></span>
|
||||
<button type="button" id="theme-btn" aria-label="Switch colour theme">
|
||||
<span id="theme-btn-label">Dark</span>
|
||||
</button>
|
||||
<div class="who">
|
||||
<span id="who-name" class="mono"></span>
|
||||
<span id="who-role" class="pill role"></span>
|
||||
<button type="button" id="logout-btn" class="ghost sm">Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
<main id="view" tabindex="-1"></main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Login / first-run setup. Shown before #app, so nothing leaks to an
|
||||
unauthenticated visitor. -->
|
||||
<div id="gate" hidden>
|
||||
<form id="login-form" class="auth-card">
|
||||
<span class="logo big" aria-hidden="true"></span>
|
||||
<h2 id="gate-title">Sign in to streamd</h2>
|
||||
<p class="auth-sub">Null DRM restream control</p>
|
||||
<p id="gate-note" class="hint"></p>
|
||||
<label id="setup-row" hidden>Setup token
|
||||
<input name="setup_token" autocomplete="off" spellcheck="false" />
|
||||
<small class="hint">Printed in the streamd startup log.</small>
|
||||
</label>
|
||||
<label>Username <input name="username" autocomplete="username" required /></label>
|
||||
<label>Password <input name="password" type="password" autocomplete="current-password" required /></label>
|
||||
<p id="gate-msg" class="msg" role="alert"></p>
|
||||
<button type="submit" id="gate-submit">Sign in</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="toast-stack" aria-live="polite"></div>
|
||||
|
||||
<dialog id="modal">
|
||||
<div id="modal-body"></div>
|
||||
</dialog>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
|
||||
<script src="/static/app.js"></script>
|
||||
<script type="module" src="/static/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
645
apps/streamd/internal/ui/static/app.css
Normal file
645
apps/streamd/internal/ui/static/app.css
Normal 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; }
|
||||
}
|
||||
134
apps/streamd/internal/ui/static/js/api.js
Normal file
134
apps/streamd/internal/ui/static/js/api.js
Normal 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"),
|
||||
};
|
||||
331
apps/streamd/internal/ui/static/js/app.js
Normal file
331
apps/streamd/internal/ui/static/js/app.js
Normal 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();
|
||||
375
apps/streamd/internal/ui/static/js/components.js
Normal file
375
apps/streamd/internal/ui/static/js/components.js
Normal 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;
|
||||
}
|
||||
200
apps/streamd/internal/ui/static/js/store.js
Normal file
200
apps/streamd/internal/ui/static/js/store.js
Normal 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);
|
||||
}
|
||||
350
apps/streamd/internal/ui/static/js/util.js
Normal file
350
apps/streamd/internal/ui/static/js/util.js
Normal 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;
|
||||
}
|
||||
562
apps/streamd/internal/ui/static/js/views/admin.js
Normal file
562
apps/streamd/internal/ui/static/js/views/admin.js
Normal 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 };
|
||||
180
apps/streamd/internal/ui/static/js/views/dashboard.js
Normal file
180
apps/streamd/internal/ui/static/js/views/dashboard.js
Normal 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(", ");
|
||||
}
|
||||
263
apps/streamd/internal/ui/static/js/views/stream-form.js
Normal file
263
apps/streamd/internal/ui/static/js/views/stream-form.js
Normal 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();
|
||||
}
|
||||
816
apps/streamd/internal/ui/static/js/views/stream.js
Normal file
816
apps/streamd/internal/ui/static/js/views/stream.js
Normal 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);
|
||||
}
|
||||
292
apps/streamd/internal/ui/static/js/views/streams.js
Normal file
292
apps/streamd/internal/ui/static/js/views/streams.js
Normal 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;
|
||||
}
|
||||
13
apps/streamd/internal/ui/static/vendor/README.md
vendored
Normal file
13
apps/streamd/internal/ui/static/vendor/README.md
vendored
Normal 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.
|
||||
2
apps/streamd/internal/ui/static/vendor/hls.min.js
vendored
Normal file
2
apps/streamd/internal/ui/static/vendor/hls.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -1,14 +1,20 @@
|
|||
// Package ui serves the embedded dashboard: one HTML shell plus ES modules
|
||||
// and a vendored copy of hls.js. There is no build step, which is why the
|
||||
// JavaScript is plain modules rather than a bundle.
|
||||
package ui
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed index.html app.css app.js
|
||||
//go:embed index.html all:static
|
||||
var files embed.FS
|
||||
|
||||
// Handler serves the single-page shell for every non-asset path, so the hash
|
||||
// router can own navigation.
|
||||
func Handler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" && r.URL.Path != "/index.html" {
|
||||
|
|
@ -17,18 +23,37 @@ func Handler() http.Handler {
|
|||
}
|
||||
b, err := files.ReadFile("index.html")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
// The shell references hashed-by-content assets only loosely, so keep
|
||||
// it uncached to avoid serving a stale page against new modules.
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
_, _ = w.Write(b)
|
||||
})
|
||||
}
|
||||
|
||||
// Static serves the dashboard assets. Directory listings are refused: the
|
||||
// asset tree is not interesting, and an index is one more thing to leak.
|
||||
func Static() http.Handler {
|
||||
sub, err := fs.Sub(files, ".")
|
||||
sub, err := fs.Sub(files, "static")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return http.FileServer(http.FS(sub))
|
||||
fileServer := http.FileServer(http.FS(sub))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "" || r.URL.Path == "/" || strings.HasSuffix(r.URL.Path, "/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// The vendored library is immutable for a given version; the rest is
|
||||
// revalidated so an updated build is picked up on reload.
|
||||
if strings.HasPrefix(r.URL.Path, "/vendor/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=86400")
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package ws
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -10,6 +10,7 @@ import (
|
|||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
|
|
@ -19,21 +20,26 @@ const (
|
|||
claimRenewTTL = 90 * time.Second
|
||||
writeWait = 10 * time.Second
|
||||
pongWait = 60 * time.Second
|
||||
// captureDebounce stops a flapping stream from spamming every agent with
|
||||
// the same request. One push per stream per window is plenty.
|
||||
captureDebounce = 30 * time.Second
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
// Hub tracks agent WebSocket sessions and UI listeners.
|
||||
type Hub struct {
|
||||
Store *db.Store
|
||||
Token string
|
||||
Log *log.Logger
|
||||
Log *slog.Logger
|
||||
// AllowedOrigins are extra origins permitted to open a socket, beyond the
|
||||
// server's own. Empty means same-origin only.
|
||||
AllowedOrigins []string
|
||||
|
||||
mu sync.Mutex
|
||||
agents map[string]*agentConn // agent_id -> conn
|
||||
uis map[*websocket.Conn]struct{}
|
||||
// lastCapture debounces capture pushes per stream id.
|
||||
lastCapture map[int64]time.Time
|
||||
|
||||
upgrader websocket.Upgrader
|
||||
}
|
||||
|
||||
type agentConn struct {
|
||||
|
|
@ -55,19 +61,70 @@ type outbound struct {
|
|||
Error string `json:"error,omitempty"`
|
||||
Agents []any `json:"agents,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
|
||||
// Capture request fields. The agent needs enough to enqueue a job without
|
||||
// a round trip, and deliberately never receives the credentials.
|
||||
StreamID int64 `json:"stream_id,omitempty"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
App string `json:"app,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
func NewHub(store *db.Store, token string, lg *log.Logger) *Hub {
|
||||
func NewHub(store *db.Store, lg *slog.Logger, allowedOrigins []string) *Hub {
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
lg = slog.Default()
|
||||
}
|
||||
return &Hub{
|
||||
Store: store,
|
||||
Token: token,
|
||||
Log: lg,
|
||||
agents: map[string]*agentConn{},
|
||||
uis: map[*websocket.Conn]struct{}{},
|
||||
h := &Hub{
|
||||
Store: store,
|
||||
Log: lg,
|
||||
AllowedOrigins: allowedOrigins,
|
||||
agents: map[string]*agentConn{},
|
||||
uis: map[*websocket.Conn]struct{}{},
|
||||
lastCapture: map[int64]time.Time{},
|
||||
}
|
||||
// A WebSocket handshake is not subject to the same-origin policy, so
|
||||
// without this check any page on the internet could open /ws/ui against a
|
||||
// logged-in operator's browser and read the event stream.
|
||||
h.upgrader = websocket.Upgrader{CheckOrigin: h.checkOrigin}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Hub) checkOrigin(r *http.Request) bool {
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
// Non-browser clients (the agent) send no Origin. They are
|
||||
// authenticated by bearer token instead.
|
||||
return true
|
||||
}
|
||||
host := strings.ToLower(hostOnly(origin))
|
||||
if host != "" && host == strings.ToLower(hostOnly("//"+r.Host)) {
|
||||
return true
|
||||
}
|
||||
for _, allowed := range h.AllowedOrigins {
|
||||
allowed = strings.TrimRight(strings.TrimSpace(allowed), "/")
|
||||
if allowed == "" {
|
||||
continue
|
||||
}
|
||||
if allowed == "*" || strings.EqualFold(allowed, strings.TrimRight(origin, "/")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
h.Log.Warn("ws: rejected cross-origin handshake", "origin", origin, "host", r.Host)
|
||||
return false
|
||||
}
|
||||
|
||||
// hostOnly extracts host[:port] from an origin or //host form.
|
||||
func hostOnly(u string) string {
|
||||
if i := strings.Index(u, "://"); i >= 0 {
|
||||
u = u[i+3:]
|
||||
} else {
|
||||
u = strings.TrimPrefix(u, "//")
|
||||
}
|
||||
if i := strings.IndexAny(u, "/?#"); i >= 0 {
|
||||
u = u[:i]
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func (h *Hub) Mount(mux *http.ServeMux) {
|
||||
|
|
@ -93,9 +150,9 @@ func (h *Hub) RunExpireLoop(stop <-chan struct{}) {
|
|||
func (h *Hub) tick() {
|
||||
n, err := h.Store.ExpireClaims()
|
||||
if err != nil {
|
||||
h.Log.Printf("ws: expire claims: %v", err)
|
||||
h.Log.Error("ws: expire claims", "err", err)
|
||||
} else if n > 0 {
|
||||
h.Log.Printf("ws: expired %d stale claim(s)", n)
|
||||
h.Log.Info("ws: expired stale claims", "count", n)
|
||||
h.broadcastUI(outbound{Type: "claims_changed", Message: "expired"})
|
||||
}
|
||||
|
||||
|
|
@ -109,36 +166,29 @@ func (h *Hub) tick() {
|
|||
}
|
||||
h.mu.Unlock()
|
||||
for _, id := range stale {
|
||||
h.Log.Printf("ws: agent %s heartbeat stale — releasing claims", id)
|
||||
h.Log.Warn("ws: agent heartbeat stale — releasing claims", "agent", id)
|
||||
h.dropAgent(id, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) authToken(r *http.Request) bool {
|
||||
if h.Token == "" {
|
||||
return true
|
||||
}
|
||||
tok := r.URL.Query().Get("token")
|
||||
if tok == "" {
|
||||
auth := r.Header.Get("Authorization")
|
||||
tok = strings.TrimPrefix(auth, "Bearer ")
|
||||
}
|
||||
if tok == "" {
|
||||
tok = r.Header.Get("X-Streamd-Token")
|
||||
}
|
||||
return tok == h.Token
|
||||
}
|
||||
|
||||
func (h *Hub) handleAgentsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"agents": h.snapshotAgents()})
|
||||
}
|
||||
|
||||
// handleUI serves the dashboard's event stream. It now requires a principal:
|
||||
// it previously had no authentication at all.
|
||||
func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -159,24 +209,51 @@ func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) {
|
|||
})
|
||||
// Push initial agent list.
|
||||
h.sendJSON(conn, outbound{Type: "agents", Agents: h.snapshotAgents()})
|
||||
|
||||
// Keep the socket alive from this side too, so an idle dashboard behind a
|
||||
// proxy with an idle timeout is not disconnected every minute.
|
||||
stop := make(chan struct{})
|
||||
defer close(stop)
|
||||
go func() {
|
||||
t := time.NewTicker(agentHeartbeatEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-t.C:
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.authToken(r) {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
// Agents authenticate with a bearer API key. The ?token= query form is
|
||||
// gone: it leaked the secret into proxy logs.
|
||||
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
agentID := strings.TrimSpace(r.URL.Query().Get("agent_id"))
|
||||
if agentID == "" {
|
||||
agentID = p.AgentID
|
||||
}
|
||||
if agentID == "" {
|
||||
http.Error(w, `{"error":"agent_id required"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -184,7 +261,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
|||
conn: conn,
|
||||
agentID: agentID,
|
||||
lastSeen: time.Now().UTC(),
|
||||
send: make(chan []byte, 8),
|
||||
send: make(chan []byte, 16),
|
||||
}
|
||||
h.mu.Lock()
|
||||
if old, ok := h.agents[agentID]; ok {
|
||||
|
|
@ -193,7 +270,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
h.agents[agentID] = ac
|
||||
h.mu.Unlock()
|
||||
h.Log.Printf("ws: agent connected id=%s", agentID)
|
||||
h.Log.Info("ws: agent connected", "agent", agentID, "key", p.Name)
|
||||
h.broadcastUI(outbound{Type: "agent_online", AgentID: agentID, Agents: h.snapshotAgents()})
|
||||
|
||||
go h.agentWriter(ac)
|
||||
|
|
@ -263,12 +340,12 @@ func (h *Hub) dropAgent(agentID string, releaseClaims bool) {
|
|||
if releaseClaims {
|
||||
n, err := h.Store.ReleaseAgentClaims(agentID)
|
||||
if err != nil {
|
||||
h.Log.Printf("ws: release claims for %s: %v", agentID, err)
|
||||
h.Log.Error("ws: release claims", "agent", agentID, "err", err)
|
||||
} else if n > 0 {
|
||||
h.Log.Printf("ws: released %d claim(s) for disconnected agent %s", n, agentID)
|
||||
h.Log.Info("ws: released claims for disconnected agent", "agent", agentID, "count", n)
|
||||
}
|
||||
}
|
||||
h.Log.Printf("ws: agent disconnected id=%s", agentID)
|
||||
h.Log.Info("ws: agent disconnected", "agent", agentID)
|
||||
h.broadcastUI(outbound{Type: "agent_offline", AgentID: agentID, Agents: h.snapshotAgents()})
|
||||
}
|
||||
|
||||
|
|
@ -299,12 +376,80 @@ func (h *Hub) queue(ac *agentConn, msg outbound) {
|
|||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Never block the caller on a wedged agent: dropping a heartbeat ack is
|
||||
// harmless, and a capture request will be retried on the next poll.
|
||||
select {
|
||||
case ac.send <- b:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// RequestCapture asks every connected agent to refresh this stream's
|
||||
// credentials now. Returns how many agents were notified.
|
||||
//
|
||||
// This is what makes an on-demand wake and a scheduled pre-roll responsive:
|
||||
// without it the agent would not notice until its next poll, up to 30s later,
|
||||
// with a viewer already waiting.
|
||||
func (h *Hub) RequestCapture(st db.Stream, reason string) int {
|
||||
h.mu.Lock()
|
||||
if last, ok := h.lastCapture[st.ID]; ok && time.Since(last) < captureDebounce {
|
||||
h.mu.Unlock()
|
||||
return 0
|
||||
}
|
||||
h.lastCapture[st.ID] = time.Now()
|
||||
// Keep the debounce map from growing with deleted streams.
|
||||
if len(h.lastCapture) > 1000 {
|
||||
for id, t := range h.lastCapture {
|
||||
if time.Since(t) > 10*time.Minute {
|
||||
delete(h.lastCapture, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
conns := make([]*agentConn, 0, len(h.agents))
|
||||
for _, a := range h.agents {
|
||||
conns = append(conns, a)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
if len(conns) == 0 {
|
||||
return 0
|
||||
}
|
||||
msg := outbound{
|
||||
Type: "capture_requested",
|
||||
StreamID: st.ID,
|
||||
StreamName: st.Name,
|
||||
App: st.App,
|
||||
Channel: st.Channel,
|
||||
Reason: reason,
|
||||
}
|
||||
for _, ac := range conns {
|
||||
h.queue(ac, msg)
|
||||
}
|
||||
h.Log.Info("ws: capture requested", "stream", st.Name, "reason", reason, "agents", len(conns))
|
||||
return len(conns)
|
||||
}
|
||||
|
||||
// NotifyStreamChanged tells the dashboard to refresh, and nudges agents to
|
||||
// re-poll rather than wait out their interval.
|
||||
func (h *Hub) NotifyStreamChanged(name, reason string) {
|
||||
h.broadcastUI(outbound{Type: "streams_changed", StreamName: name, Reason: reason})
|
||||
h.mu.Lock()
|
||||
conns := make([]*agentConn, 0, len(h.agents))
|
||||
for _, a := range h.agents {
|
||||
conns = append(conns, a)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, ac := range conns {
|
||||
h.queue(ac, outbound{Type: "stream_changed", StreamName: name, Reason: reason})
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyRuntime pushes a live health delta to the dashboard, so it does not
|
||||
// have to poll the whole stream list on a timer.
|
||||
func (h *Hub) NotifyRuntime(name, health string) {
|
||||
h.broadcastUI(outbound{Type: "runtime", StreamName: name, Message: health})
|
||||
}
|
||||
|
||||
func (h *Hub) sendJSON(conn *websocket.Conn, msg outbound) {
|
||||
b, _ := json.Marshal(msg)
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@ package servecmd
|
|||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
|
@ -16,9 +16,14 @@ import (
|
|||
"time"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/api"
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/deps"
|
||||
"drmdecryption/apps/streamd/internal/hlsgate"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
"drmdecryption/apps/streamd/internal/scheduler"
|
||||
"drmdecryption/apps/streamd/internal/supervisor"
|
||||
"drmdecryption/apps/streamd/internal/tsfanout"
|
||||
"drmdecryption/apps/streamd/internal/ui"
|
||||
"drmdecryption/apps/streamd/internal/ws"
|
||||
)
|
||||
|
|
@ -52,29 +57,73 @@ Usage:
|
|||
streamd serve [flags]
|
||||
|
||||
serve flags:
|
||||
--bind listen address (default 0.0.0.0:8083)
|
||||
--data data dir for sqlite + www + work (default .cache/streamd)
|
||||
--token shared bearer token for mutating API (or STREAMD_TOKEN)
|
||||
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
|
||||
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
|
||||
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
|
||||
--bin-dir where to install/look for media tools (default <repo>/bin)
|
||||
--skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt
|
||||
--bind listen address (default 127.0.0.1:8083)
|
||||
--data data dir for sqlite + www + work (default .cache/streamd)
|
||||
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
|
||||
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
|
||||
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
|
||||
--bin-dir where to install/look for media tools (default <repo>/bin)
|
||||
--skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt
|
||||
--log-level debug | info | warn | error (default info)
|
||||
|
||||
access control:
|
||||
--admin-user create this admin account on first run (with --admin-pass)
|
||||
--admin-pass password for --admin-user (prefer STREAMD_ADMIN_PASS)
|
||||
--token legacy shared bearer token, treated as an admin API key
|
||||
(or STREAMD_TOKEN). Prefer per-agent keys in the dashboard.
|
||||
--session-ttl how long a login lasts without activity (default 12h)
|
||||
--trusted-proxies CIDRs allowed to set X-Forwarded-For/-Proto (e.g. 127.0.0.1/32)
|
||||
--allowed-origins extra CORS origins, comma separated (default same-origin only)
|
||||
--cookie-secure always mark cookies Secure (set this behind a TLS proxy)
|
||||
--audit-retain how long to keep audit rows (default 2160h / 90d)
|
||||
|
||||
on-demand and scheduling:
|
||||
--ondemand-wait hold a viewer request this long while a stream starts
|
||||
--ondemand-capture-wait as above, when credentials must be captured first
|
||||
--schedule-preroll refresh credentials this far before a scheduled start
|
||||
--ts-fanout-buffer live MPEG-TS bytes buffered per stream for /live/
|
||||
|
||||
Bind defaults to 127.0.0.1 — put a TLS-terminating reverse proxy in front and
|
||||
set --trusted-proxies to that proxy. Use --bind 0.0.0.0:8083 only deliberately.
|
||||
`)
|
||||
}
|
||||
|
||||
func serveCmd(args []string) {
|
||||
fs := flag.NewFlagSet("serve", flag.ExitOnError)
|
||||
bind := fs.String("bind", "0.0.0.0:8083", "listen address")
|
||||
// Loopback by default. This used to be 0.0.0.0, which published the API —
|
||||
// and before redaction, the Widevine keys — to the whole network.
|
||||
bind := fs.String("bind", "127.0.0.1:8083", "listen address")
|
||||
data := fs.String("data", "", "data directory (sqlite, www, work, logs)")
|
||||
token := fs.String("token", "", "API bearer token (default: STREAMD_TOKEN env)")
|
||||
token := fs.String("token", "", "legacy admin API token (default: STREAMD_TOKEN env)")
|
||||
nre := fs.String("nre", "", "N_m3u8DL-RE binary")
|
||||
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
|
||||
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
|
||||
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
|
||||
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
|
||||
logLevel := fs.String("log-level", "info", "debug | info | warn | error")
|
||||
adminUser := fs.String("admin-user", "", "create this admin account on first run")
|
||||
adminPass := fs.String("admin-pass", "", "password for --admin-user (or STREAMD_ADMIN_PASS)")
|
||||
sessionTTL := fs.Duration("session-ttl", auth.DefaultSessionTTL, "login lifetime without activity")
|
||||
trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For")
|
||||
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated")
|
||||
cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure")
|
||||
auditRetain := fs.Duration("audit-retain", 90*24*time.Hour, "how long to keep audit rows")
|
||||
tsBuffer := fs.Int("ts-fanout-buffer", tsfanout.DefaultBufferBytes,
|
||||
"bytes of live MPEG-TS buffered per stream for /live/<name>.ts")
|
||||
ondemandWait := fs.Duration("ondemand-wait", hlsgate.DefaultWait,
|
||||
"how long to hold a viewer request while an on-demand stream starts")
|
||||
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", hlsgate.DefaultCaptureWait,
|
||||
"as --ondemand-wait, but when credentials must be captured first")
|
||||
preroll := fs.Duration("schedule-preroll", scheduler.DefaultPreroll,
|
||||
"how far ahead of a scheduled start to refresh credentials")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
lg := newLogger(*logLevel)
|
||||
slog.SetDefault(lg)
|
||||
// deps still wants a *log.Logger; bridge it onto the same handler so one
|
||||
// stream of output stays coherent.
|
||||
depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo)
|
||||
|
||||
dataDir := *data
|
||||
if dataDir == "" {
|
||||
dataDir = filepath.Join(".", ".cache", "streamd")
|
||||
|
|
@ -84,159 +133,255 @@ func serveCmd(args []string) {
|
|||
tok = os.Getenv("STREAMD_TOKEN")
|
||||
}
|
||||
|
||||
trust := httpx.Trust{}
|
||||
if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil {
|
||||
lg.Error("invalid --trusted-proxies", "err", err)
|
||||
os.Exit(2)
|
||||
} else {
|
||||
trust.Proxies = nets
|
||||
}
|
||||
origins := splitList(*allowedOrigins)
|
||||
|
||||
for _, sub := range []string{"www", "work", "logs"} {
|
||||
if err := os.MkdirAll(filepath.Join(dataDir, sub), 0o755); err != nil {
|
||||
log.Fatal(err)
|
||||
lg.Error("create data dir", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := db.Open(dataDir)
|
||||
if err != nil {
|
||||
log.Fatalf("db: %v", err)
|
||||
lg.Error("open database", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
authStore, err := auth.New(store.DB, tok)
|
||||
if err != nil {
|
||||
lg.Error("init auth tables", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
mw := auth.NewMiddleware(authStore, trust, *cookieSecure)
|
||||
mw.SessionTTL = *sessionTTL
|
||||
authH := auth.NewHandler(authStore, mw, lg)
|
||||
|
||||
bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass)
|
||||
|
||||
depStatus, _ := deps.Ensure(deps.Options{
|
||||
BinDir: *binDir,
|
||||
SkipDownload: *skipDeps,
|
||||
Log: log.Default(),
|
||||
Log: depsLog,
|
||||
}, *nre, *ffmpeg, *mp4decrypt)
|
||||
nrePath := depStatus.NRE
|
||||
ffPath := depStatus.FFmpeg
|
||||
decPath := depStatus.MP4Decrypt
|
||||
|
||||
fanout := tsfanout.NewSet(*tsBuffer)
|
||||
hub := ws.NewHub(store, lg, origins)
|
||||
|
||||
sup := supervisor.NewMedia(supervisor.Options{
|
||||
Store: store,
|
||||
DataDir: dataDir,
|
||||
NRE: nrePath,
|
||||
FFmpeg: ffPath,
|
||||
MP4Decrypt: decPath,
|
||||
Log: log.Default(),
|
||||
NRE: depStatus.NRE,
|
||||
FFmpeg: depStatus.FFmpeg,
|
||||
MP4Decrypt: depStatus.MP4Decrypt,
|
||||
Log: lg,
|
||||
Fanout: fanout,
|
||||
Notifier: hub,
|
||||
})
|
||||
defer sup.Close()
|
||||
|
||||
gate := hlsgate.New(hlsgate.Config{
|
||||
Store: store,
|
||||
WWWRoot: filepath.Join(dataDir, "www"),
|
||||
Sup: sup,
|
||||
Fanout: fanout,
|
||||
Capture: hub,
|
||||
Trust: trust,
|
||||
Log: lg,
|
||||
Wait: *ondemandWait,
|
||||
CaptureWait: *ondemandCaptureWait,
|
||||
})
|
||||
// The supervisor records viewer counts in its metrics series, and the
|
||||
// gate is what knows them.
|
||||
sup.ViewersFn = gate.ViewersFor
|
||||
|
||||
sched := scheduler.New(store, sup, hub, lg, *preroll)
|
||||
|
||||
apiH := &api.Handler{
|
||||
Store: store,
|
||||
Token: tok,
|
||||
Auth: authStore,
|
||||
Trust: trust,
|
||||
Supervisor: sup,
|
||||
Capture: hub,
|
||||
StartedAt: time.Now(),
|
||||
Deps: depStatus,
|
||||
WWWRoot: filepath.Join(dataDir, "www"),
|
||||
LogRoot: filepath.Join(dataDir, "logs"),
|
||||
Notifier: hub,
|
||||
Viewers: gate,
|
||||
Scheduler: sched,
|
||||
Log: lg,
|
||||
}
|
||||
hub := ws.NewHub(store, tok, log.Default())
|
||||
|
||||
mux := http.NewServeMux()
|
||||
apiH.Mount(mux)
|
||||
authH.Mount(mux)
|
||||
hub.Mount(mux)
|
||||
// The media paths are served by the gate, not a bare FileServer: it wakes
|
||||
// on-demand streams, counts viewers, sets cache headers per file kind and
|
||||
// refuses directory listings.
|
||||
gate.Mount(mux)
|
||||
mux.Handle("/", ui.Handler())
|
||||
mux.Handle("/static/", http.StripPrefix("/static/", ui.Static()))
|
||||
mux.Handle("/hls/", http.StripPrefix("/hls/", http.FileServer(http.Dir(filepath.Join(dataDir, "www")))))
|
||||
|
||||
// Order matters: the access log wraps everything so it sees final statuses,
|
||||
// then CORS and security headers, then principal resolution, then the mux.
|
||||
var handler http.Handler = mux
|
||||
handler = mw.Attach(handler)
|
||||
handler = httpx.SecurityHeaders(trust, handler)
|
||||
handler = httpx.CORS(origins, handler)
|
||||
handler = httpx.AccessLog(lg, trust, handler)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: *bind,
|
||||
Handler: withCORS(mux),
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
// No WriteTimeout: HLS responses, SSE log tails and websockets are all
|
||||
// long-lived and a write deadline would cut them off.
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
log.Printf("streamd listening on http://%s data=%s", *bind, dataDir)
|
||||
log.Printf("media: nre=%s", nrePath)
|
||||
log.Printf("media: ffmpeg=%s", ffPath)
|
||||
log.Printf("media: mp4decrypt=%s", decPath)
|
||||
log.Printf("ws: agents=/ws/agent ui=/ws/ui")
|
||||
if tok == "" {
|
||||
log.Printf("warning: no --token / STREAMD_TOKEN set; mutating API is open")
|
||||
lg.Info("streamd listening", "addr", *bind, "data", dataDir)
|
||||
lg.Info("media tools", "nre", depStatus.NRE, "ffmpeg", depStatus.FFmpeg, "mp4decrypt", depStatus.MP4Decrypt)
|
||||
if len(trust.Proxies) == 0 {
|
||||
lg.Info("no --trusted-proxies set: forwarded headers are ignored and client IPs come from the peer address")
|
||||
}
|
||||
if tok != "" {
|
||||
lg.Warn("--token / STREAMD_TOKEN is in use as an admin API key; create per-agent keys in the dashboard and drop it")
|
||||
}
|
||||
if host, _, err := net.SplitHostPort(*bind); err == nil {
|
||||
switch strings.ToLower(host) {
|
||||
case "127.0.0.1", "localhost", "::1":
|
||||
// Loopback is the safe default.
|
||||
default:
|
||||
lg.Warn("listening on a non-loopback address — the dashboard and API are reachable on the network; put a TLS reverse proxy in front, or bind 127.0.0.1",
|
||||
"bind", *bind)
|
||||
}
|
||||
}
|
||||
|
||||
stopBG := make(chan struct{})
|
||||
go hub.RunExpireLoop(stopBG)
|
||||
|
||||
// Resume enabled streams that already have credentials (staggered).
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
list, err := store.ListStreams()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, st := range list {
|
||||
if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
|
||||
continue
|
||||
}
|
||||
mpd := strings.ToLower(strings.TrimSpace(st.MPD))
|
||||
if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") {
|
||||
log.Printf("auto-start skip %s: mpd is not an http(s) URL", st.Name)
|
||||
continue
|
||||
}
|
||||
log.Printf("auto-start enabled stream %s", st.Name)
|
||||
func(id int64, name string) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("auto-start %s panic: %v", name, r)
|
||||
}
|
||||
}()
|
||||
if err := sup.Start(id); err != nil {
|
||||
log.Printf("auto-start %s: %v", name, err)
|
||||
}
|
||||
}(st.ID, st.Name)
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
go authStore.RunMaintenance(stopBG, *auditRetain)
|
||||
go store.RunHistoryMaintenance(stopBG)
|
||||
go gate.RunIdleLoop(stopBG)
|
||||
go sched.Run(stopBG)
|
||||
go resumeEnabledStreams(lg, store, sup)
|
||||
|
||||
go func() {
|
||||
ch := make(chan os.Signal, 1)
|
||||
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
|
||||
<-ch
|
||||
log.Printf("shutting down…")
|
||||
lg.Info("shutting down")
|
||||
close(stopBG)
|
||||
sup.Close()
|
||||
_ = authStore.FlushAudit()
|
||||
_ = srv.Close()
|
||||
}()
|
||||
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
lg.Error("listen", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func withCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
func newLogger(level string) *slog.Logger {
|
||||
var lv slog.Level
|
||||
switch strings.ToLower(strings.TrimSpace(level)) {
|
||||
case "debug":
|
||||
lv = slog.LevelDebug
|
||||
case "warn", "warning":
|
||||
lv = slog.LevelWarn
|
||||
case "error":
|
||||
lv = slog.LevelError
|
||||
default:
|
||||
lv = slog.LevelInfo
|
||||
}
|
||||
// A text handler keeps the console output as readable as the old
|
||||
// log.Printf lines while giving every record structured attributes.
|
||||
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lv}))
|
||||
}
|
||||
|
||||
// bootstrapAdmin creates the first account from flags when asked, or prints a
|
||||
// one-time setup token so the dashboard can create it.
|
||||
func bootstrapAdmin(lg *slog.Logger, store *auth.Store, h *auth.Handler, user, pass string) {
|
||||
n, err := store.CountUsers()
|
||||
if err != nil {
|
||||
lg.Error("count users", "err", err)
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
h.SetSetupToken("")
|
||||
return
|
||||
}
|
||||
if pass == "" {
|
||||
pass = os.Getenv("STREAMD_ADMIN_PASS")
|
||||
}
|
||||
if user != "" && pass != "" {
|
||||
if _, err := store.CreateUser(user, pass, auth.RoleAdmin); err != nil {
|
||||
lg.Error("create admin account", "err", err)
|
||||
} else {
|
||||
lg.Info("created initial admin account", "user", strings.ToLower(strings.TrimSpace(user)))
|
||||
h.SetSetupToken("")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
tok := auth.NewSetupToken()
|
||||
h.SetSetupToken(tok)
|
||||
lg.Warn("no accounts exist yet — open the dashboard and use this one-time setup token to create the first admin",
|
||||
"setup_token", tok)
|
||||
}
|
||||
|
||||
func firstExisting(explicit string, candidates ...string) string {
|
||||
if explicit != "" {
|
||||
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
|
||||
return explicit
|
||||
}
|
||||
// still return explicit so exec fails clearly if user set a bad path
|
||||
if filepath.IsAbs(explicit) || containsSep(explicit) {
|
||||
return explicit
|
||||
}
|
||||
// resumeEnabledStreams restarts streams that were running before a restart.
|
||||
// On-demand streams are deliberately left stopped: a viewer's first request
|
||||
// starts them, which is the whole point.
|
||||
func resumeEnabledStreams(lg *slog.Logger, store *db.Store, sup *supervisor.Media) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
list, err := store.ListStreams()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if c == "" {
|
||||
for _, st := range list {
|
||||
if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
|
||||
continue
|
||||
}
|
||||
if st, err := os.Stat(c); err == nil && !st.IsDir() {
|
||||
return c
|
||||
if st.OnDemand {
|
||||
lg.Info("auto-start skipped: on-demand stream waits for a viewer", "stream", st.Name)
|
||||
continue
|
||||
}
|
||||
if p, err := execLookPath(c); err == nil {
|
||||
return p
|
||||
mpd := strings.ToLower(strings.TrimSpace(st.MPD))
|
||||
if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") {
|
||||
lg.Warn("auto-start skipped: mpd is not an http(s) URL", "stream", st.Name)
|
||||
continue
|
||||
}
|
||||
lg.Info("auto-starting enabled stream", "stream", st.Name)
|
||||
func(id int64, name string) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
lg.Error("auto-start panicked", "stream", name, "panic", r)
|
||||
}
|
||||
}()
|
||||
if err := sup.Start(id); err != nil {
|
||||
lg.Error("auto-start failed", "stream", name, "err", err)
|
||||
}
|
||||
}(st.ID, st.Name)
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func splitList(s string) []string {
|
||||
var out []string
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return explicit
|
||||
}
|
||||
|
||||
func containsSep(s string) bool {
|
||||
return filepath.Base(s) != s
|
||||
}
|
||||
|
||||
func execLookPath(file string) (string, error) {
|
||||
return exec.LookPath(file)
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue