Null-DRM-Official/apps/streamd/internal/db/db.go
404errordeveloper 8fc7e4c0b8 streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
2026-10-10 18:05:51 +02:00

912 lines
28 KiB
Go

package db
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
_ "modernc.org/sqlite"
)
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"`
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
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"`
Health string `json:"health,omitempty"`
PID int64 `json:"pid,omitempty"`
PlayPath string `json:"play_path,omitempty"`
UptimeS float64 `json:"uptime_s,omitempty"`
BitrateMbps float64 `json:"bitrate_mbps,omitempty"`
PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
LastError string `json:"last_error,omitempty"`
RuntimeAt string `json:"runtime_updated_at,omitempty"`
// 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"`
HasEgress bool `json:"has_egress"`
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"`
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"`
Egress string `json:"egress"`
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"`
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"`
Egress *string `json:"egress"`
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 {
MPD string `json:"mpd"`
Key string `json:"key"` // optional for clear streams
PSSH string `json:"pssh,omitempty"`
Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"`
}
func Open(dataDir string) (*Store, error) {
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return nil, err
}
path := filepath.Join(dataDir, "streamd.db")
dsn := fmt.Sprintf("file:%s?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)", filepath.ToSlash(path))
sqlDB, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
sqlDB.SetMaxOpenConns(1)
s := &Store{DB: sqlDB}
if err := s.migrate(); err != nil {
_ = sqlDB.Close()
return nil, err
}
return s, nil
}
func (s *Store) Close() error {
return s.DB.Close()
}
func (s *Store) migrate() error {
_, err := s.DB.Exec(`
CREATE TABLE IF NOT EXISTS streams (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
title TEXT NOT NULL DEFAULT '',
app TEXT NOT NULL DEFAULT '',
channel TEXT NOT NULL DEFAULT '',
mpd TEXT NOT NULL DEFAULT '',
key_kid_key TEXT NOT NULL DEFAULT '',
headers_json TEXT NOT NULL DEFAULT '{}',
proxy TEXT NOT NULL DEFAULT '',
video_select TEXT NOT NULL DEFAULT '',
audio_select TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 0,
rewriter TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS stream_runtime (
stream_id INTEGER PRIMARY KEY REFERENCES streams(id) ON DELETE CASCADE,
health TEXT NOT NULL DEFAULT 'stopped',
pid INTEGER NOT NULL DEFAULT 0,
play_path TEXT NOT NULL DEFAULT '',
uptime_s REAL NOT NULL DEFAULT 0,
bitrate_mbps REAL NOT NULL DEFAULT 0,
playlist_age_s REAL NOT NULL DEFAULT 0,
last_error TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS agent_claims (
stream_id INTEGER PRIMARY KEY REFERENCES streams(id) ON DELETE CASCADE,
agent_id TEXT NOT NULL,
claimed_at TEXT NOT NULL,
expires_at TEXT NOT NULL
);
`)
if err != nil {
return err
}
// 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`,
`ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`,
} {
_, _ = s.DB.Exec(stmt)
}
if err := s.migrateHistory(); err != nil {
return err
}
if err := s.migrateSettings(); err != nil {
return err
}
if err := s.migrateSchedules(); err != nil {
return err
}
return s.migrateEgress()
}
func now() string {
return time.Now().UTC().Format(time.RFC3339)
}
func slug(name string) string {
name = strings.TrimSpace(strings.ToLower(name))
var b strings.Builder
for _, r := range name {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
b.WriteRune(r)
case r == '-' || r == '_' || r == ' ':
b.WriteByte('-')
}
}
out := strings.Trim(b.String(), "-")
for strings.Contains(out, "--") {
out = strings.ReplaceAll(out, "--", "-")
}
return out
}
// Slug normalises a name the same way stream and egress profile names are stored.
func Slug(name string) string { return slug(name) }
const streamSelect = `
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,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
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,''),
COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
FROM streams s
LEFT JOIN stream_runtime r ON r.stream_id = s.id
LEFT JOIN agent_claims c ON c.stream_id = s.id`
func (s *Store) ListStreams() ([]Stream, error) {
rows, err := s.DB.Query(streamSelect + ` ORDER BY s.name`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Stream
for rows.Next() {
st, err := scanStream(rows)
if err != nil {
return nil, err
}
out = append(out, st)
}
return out, rows.Err()
}
func (s *Store) GetStream(id int64) (Stream, error) {
row := s.DB.QueryRow(streamSelect+` WHERE s.id = ?`, id)
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, onDemand, public int
err := row.Scan(
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
&st.Proxy, &st.Egress, &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,
)
if err != nil {
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"
}
if st.PlayPath == "" {
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()) {
st.ClaimedBy = ""
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) != ""
st.HasEgress = strings.TrimSpace(st.Egress) != ""
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.
func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playlistAge float64) []VariantStatus {
specs := ParseVariantsJSON(variantsJSON)
out := make([]VariantStatus, 0, len(specs))
for _, v := range specs {
vs := VariantStatus{
VariantSpec: v,
PlayPath: VariantPlayPath(streamName, v.ID, v.Height),
}
if !v.Enabled {
vs.Health = "off"
} else if v.Height <= 0 && !v.AudioOnly {
vs.Health = streamHealth
vs.PlaylistAgeS = playlistAge
} else {
vs.Health = "pending"
}
out = append(out, vs)
}
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 == "" {
return Stream{}, fmt.Errorf("name required")
}
if in.HeadersJSON == "" {
in.HeadersJSON = "{}"
}
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, 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,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress,
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),
slug(strings.TrimSpace(in.Egress)),
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
if err != nil {
return Stream{}, err
}
id, _ := res.LastInsertId()
_, _ = s.DB.Exec(`INSERT OR IGNORE INTO stream_runtime(stream_id,health,play_path,updated_at) VALUES(?,?,?,?)`,
id, "stopped", "/hls/"+name+"/index.m3u8", ts)
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 {
return Stream{}, err
}
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
}
if in.Channel != nil {
cur.Channel = *in.Channel
}
if in.MPD != nil {
cur.MPD = *in.MPD
}
if in.Key != nil {
cur.Key = *in.Key
}
if in.HeadersJSON != nil {
if !json.Valid([]byte(*in.HeadersJSON)) {
return Stream{}, fmt.Errorf("headers_json must be valid JSON")
}
cur.HeadersJSON = *in.HeadersJSON
}
if in.Proxy != nil {
cur.Proxy = strings.TrimSpace(*in.Proxy)
}
if in.Egress != nil {
cur.Egress = slug(strings.TrimSpace(*in.Egress))
}
if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect
}
if in.AudioSelect != nil {
cur.AudioSelect = *in.AudioSelect
}
if in.Rewriter != nil {
cur.Rewriter = *in.Rewriter
}
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
}
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
}
if encoded != "" {
cur.OutputsJSON = encoded
}
}
enabled := 0
if cur.Enabled {
enabled = 1
}
if in.Enabled != nil {
if *in.Enabled {
enabled = 1
} else {
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=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
headers_json=?, proxy=?, egress=?, 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.Egress, 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
}
return s.GetStream(id)
}
func (s *Store) DeleteStream(id int64) error {
_, err := s.DB.Exec(`DELETE FROM streams WHERE id=?`, id)
return err
}
func (s *Store) SetEnabled(id int64, enabled bool) (Stream, error) {
v := 0
if enabled {
v = 1
}
_, err := s.DB.Exec(`UPDATE streams SET enabled=?, updated_at=? WHERE id=?`, v, now(), id)
if err != nil {
return Stream{}, err
}
health := "stopped"
if enabled {
health = "starting"
}
_, _ = s.DB.Exec(`
INSERT INTO stream_runtime(stream_id,health,play_path,updated_at)
VALUES(?,?, (SELECT '/hls/'||name||'/index.m3u8' FROM streams WHERE id=?), ?)
ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, play_path=excluded.play_path, updated_at=excluded.updated_at`,
id, health, id, now())
return s.GetStream(id)
}
func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
mpd := strings.TrimSpace(cred.MPD)
key := strings.TrimSpace(cred.Key)
if mpd == "" {
return Stream{}, fmt.Errorf("mpd required")
}
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
mpd, key, now(), id)
if err != nil {
return Stream{}, err
}
return s.GetStream(id)
}
func (s *Store) Claim(id int64, agentID string, ttl time.Duration) (Stream, error) {
if agentID == "" {
agentID = "agent"
}
if ttl <= 0 {
ttl = 90 * time.Second
}
// Drop expired rows first so a dead agent cannot block forever.
_, _ = s.ExpireClaims()
st, err := s.GetStream(id)
if err != nil {
return Stream{}, err
}
nowT := time.Now().UTC()
if st.ClaimedBy != "" && st.ClaimExp != "" {
if exp, e := time.Parse(time.RFC3339, st.ClaimExp); e == nil && exp.After(nowT) && st.ClaimedBy != agentID {
return Stream{}, fmt.Errorf("claimed")
}
}
claimedAt := nowT.Format(time.RFC3339)
expires := nowT.Add(ttl).Format(time.RFC3339)
_, err = s.DB.Exec(`
INSERT INTO agent_claims(stream_id,agent_id,claimed_at,expires_at) VALUES(?,?,?,?)
ON CONFLICT(stream_id) DO UPDATE SET agent_id=excluded.agent_id, claimed_at=excluded.claimed_at, expires_at=excluded.expires_at`,
id, agentID, claimedAt, expires)
if err != nil {
return Stream{}, err
}
return s.GetStream(id)
}
func (s *Store) ReleaseClaim(id int64, agentID string) error {
if agentID == "" {
_, err := s.DB.Exec(`DELETE FROM agent_claims WHERE stream_id=?`, id)
return err
}
_, err := s.DB.Exec(`DELETE FROM agent_claims WHERE stream_id=? AND agent_id=?`, id, agentID)
return err
}
// ExpireClaims deletes claims whose expires_at is in the past. Returns rows removed.
func (s *Store) ExpireClaims() (int64, error) {
res, err := s.DB.Exec(`DELETE FROM agent_claims WHERE expires_at <> '' AND expires_at < ?`, now())
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// RenewAgentClaims extends expires_at for every claim held by agentID.
func (s *Store) RenewAgentClaims(agentID string, ttl time.Duration) (int64, error) {
if agentID == "" {
return 0, nil
}
if ttl <= 0 {
ttl = 90 * time.Second
}
exp := time.Now().UTC().Add(ttl).Format(time.RFC3339)
res, err := s.DB.Exec(`UPDATE agent_claims SET expires_at=? WHERE agent_id=?`, exp, agentID)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// ReleaseAgentClaims drops every claim for agentID (used on WS disconnect).
func (s *Store) ReleaseAgentClaims(agentID string) (int64, error) {
if agentID == "" {
return 0, nil
}
res, err := s.DB.Exec(`DELETE FROM agent_claims WHERE agent_id=?`, agentID)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// RuntimePatch updates live worker fields for a stream.
type RuntimePatch struct {
Health string
PID int64
PlayPath string
UptimeS float64
BitrateMbps float64
PlaylistAgeS float64
LastError string
}
func (s *Store) SetRuntime(id int64, p RuntimePatch) error {
play := p.PlayPath
if play == "" {
st, err := s.GetStream(id)
if err == nil {
play = "/hls/" + st.Name + "/index.m3u8"
}
}
_, err := s.DB.Exec(`
INSERT INTO stream_runtime(stream_id,health,pid,play_path,uptime_s,bitrate_mbps,playlist_age_s,last_error,updated_at)
VALUES(?,?,?,?,?,?,?,?,?)
ON CONFLICT(stream_id) DO UPDATE SET
health=excluded.health,
pid=excluded.pid,
play_path=excluded.play_path,
uptime_s=excluded.uptime_s,
bitrate_mbps=excluded.bitrate_mbps,
playlist_age_s=excluded.playlist_age_s,
last_error=excluded.last_error,
updated_at=excluded.updated_at`,
id, p.Health, p.PID, play, p.UptimeS, p.BitrateMbps, p.PlaylistAgeS, p.LastError, now())
return err
}