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
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue