Null-DRM-Official/apps/agent/internal/poller/poller.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

162 lines
4.4 KiB
Go

package poller
import (
"fmt"
"log"
"strings"
"time"
"drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/queue"
)
type Poller struct {
API *client.Client
Queue *queue.Store
MaxAttempts int
Interval time.Duration
Log *log.Logger
}
func (p *Poller) Once() error {
streams, err := p.API.ListStreams()
if err != nil {
return err
}
for _, st := range streams {
if !st.Enabled {
continue
}
reason := needsRefresh(st)
if reason == "" {
continue
}
j, added, err := p.Queue.EnqueueIfIdle(st.ID, st.Name, st.App, st.Channel, reason, p.MaxAttempts)
if err != nil {
return err
}
if added {
p.logf("enqueued job=%d stream=%s reason=%s", j.ID, st.Name, reason)
continue
}
if active, ok, err := p.Queue.ActiveJobForStream(st.ID); err == nil && ok {
extra := ""
if active.Status == queue.StatusQueued && !active.NotBefore.IsZero() && active.NotBefore.After(time.Now().UTC()) {
extra = fmt.Sprintf(" backoff_until=%s", active.NotBefore.Format(time.RFC3339))
}
p.logf("stream %s needs %s but job=%d already %s (attempts %d/%d)%s",
st.Name, reason, active.ID, active.Status, active.Attempts, active.MaxAttempts, extra)
}
}
return nil
}
// EnqueueNow is the entry point for a capture streamd has pushed over the
// websocket, for a viewer waking an on-demand stream or a scheduled event
// about to start. It jumps ahead of routine refreshes because somebody is
// waiting on it.
func (p *Poller) EnqueueNow(streamID int64, name, app, channel, reason string) {
if reason == "" {
reason = "requested"
}
j, added, err := p.Queue.EnqueueIfIdlePriority(
streamID, name, app, channel, reason, p.MaxAttempts, queue.PriorityInteractive)
switch {
case err != nil:
p.logf("push capture for stream %s failed: %v", name, err)
case added:
p.logf("enqueued job=%d stream=%s reason=%s (pushed by streamd, priority)", j.ID, name, reason)
default:
// Already queued or running: EnqueueIfIdlePriority promoted it.
p.logf("push capture for stream %s: a job is already pending (promoted)", name)
}
}
func (p *Poller) Loop(stop <-chan struct{}) {
t := time.NewTicker(p.Interval)
defer t.Stop()
_ = p.Once()
for {
select {
case <-stop:
return
case <-t.C:
if err := p.Once(); err != nil {
p.logf("poll error: %v", err)
}
}
}
}
// needsRefresh decides whether a stream wants fresh credentials.
//
// The verdict comes from streamd, not from inspecting the key: credentials are
// redacted out of the stream list, so a local "is the key empty?" test would
// see every stream as broken and queue a capture for all of them forever.
// streamd also knows things this agent does not — whether the stream is clear
// rather than encrypted, whether it is an idle on-demand stream, and whether
// it is still inside its start-up window.
func needsRefresh(st client.Stream) string {
if !st.NeedsCapture {
return ""
}
switch {
case strings.TrimSpace(st.MPD) == "":
return "missing_credentials"
case st.DRMRequired && !st.HasKey:
return "missing_credentials"
case st.DRMRequired && !st.KeyValid:
return "invalid_credentials"
}
h := strings.ToLower(strings.TrimSpace(st.Health))
switch h {
case "down", "error", "failed":
return "down"
}
return "stale"
}
// ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
// ignored). The authoritative check lives in streamd; this copy exists only
// to sanity-check what a worker is about to POST.
func ValidKeyPair(key string) bool {
for _, line := range splitKeyLines(key) {
kid, k, ok := strings.Cut(line, ":")
if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
return false
}
}
return len(splitKeyLines(key)) > 0
}
// splitKeyLines mirrors how streamd and the packager split a key field, so a
// multi-KID capture is not mistaken for a malformed one.
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()
}
func (p *Poller) logf(format string, args ...any) {
if p.Log != nil {
p.Log.Printf(format, args...)
return
}
log.Printf(format, args...)
}