Null-DRM-Official/apps/streamd/internal/api/control.go
404errordeveloper 066e018749
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s
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
2026-10-09 20:57:43 +02:00

620 lines
18 KiB
Go

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
}