streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
All checks were successful
release / build-and-upload (push) Successful in 7m2s
All checks were successful
release / build-and-upload (push) Successful in 7m2s
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions. WireGuard netns resolv.conf + missing-deps WARN. Support donations card. Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries, modhost YAML enrich, DRM SetCredentials requires keys.
This commit is contained in:
parent
3ae1dd58b3
commit
a091922efa
34 changed files with 2391 additions and 154 deletions
|
|
@ -28,14 +28,16 @@ expire by themselves if the agent dies.
|
|||
# terminal 1 — control plane
|
||||
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
|
||||
# terminal 2 — agent (operator API key from streamd Settings → API keys)
|
||||
# terminal 2 — agent in the background (Linux / macOS / Windows)
|
||||
export STREAMD_API_KEY=ndk_…
|
||||
# or legacy: export STREAMD_TOKEN=…
|
||||
./bin/streamd agent run --config apps/agent/agent.yaml
|
||||
./bin/streamd agent start --config apps/agent/agent.yaml
|
||||
./bin/streamd agent status --config apps/agent/agent.yaml
|
||||
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
|
||||
# stop / restart: ./bin/streamd agent stop|restart --config …
|
||||
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
|
||||
```
|
||||
|
||||
```bash
|
||||
./bin/streamd agent status
|
||||
./bin/streamd agent devices
|
||||
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
||||
./bin/streamd agent cancel --job 3
|
||||
|
|
@ -52,12 +54,18 @@ whichever module a stream names and contains no provider logic.
|
|||
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
|
||||
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
|
||||
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
|
||||
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`.
|
||||
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`,
|
||||
`job_backoff` (default false — exponential delays only when several agents
|
||||
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
|
||||
`keep_old` for `agent start|stop|update`.
|
||||
|
||||
Create the key in the streamd dashboard (role **operator**). The legacy shared
|
||||
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
||||
|
||||
`wvd` must be set or key fetches fail.
|
||||
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
|
||||
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
|
||||
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
|
||||
a hand-made venv.
|
||||
|
||||
## Build
|
||||
|
||||
|
|
|
|||
|
|
@ -19,8 +19,18 @@ sync_modules: true
|
|||
# modules_dir: # optional; default <data_dir>/modules
|
||||
# modules_sync_interval_sec: 300
|
||||
# modules_prune: false # delete local modules absent from the panel
|
||||
# Required for key fetch. Relative paths resolve from the repo root
|
||||
# (DRM-Decryption/), not from C:\Users\admin\Programming\.
|
||||
wvd:
|
||||
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
|
||||
# Set true only when several agents share the same streams.
|
||||
# job_backoff: false
|
||||
# Background daemon (streamd agent start|stop|update):
|
||||
# log_file: agent.log
|
||||
# pid_file: agent.pid
|
||||
# channel: stable # or beta — used by agent update
|
||||
# asset: # optional streamd-* override
|
||||
# keep_old: 10
|
||||
# Required for key fetch. Relative paths resolve from the install/repo root.
|
||||
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
|
||||
# python: # optional override; default = <root>/.venv/…
|
||||
wvd: data/device.wvd
|
||||
# user_agent: "" # optional license-request User-Agent
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"text/tabwriter"
|
||||
|
||||
|
|
@ -21,6 +22,8 @@ import (
|
|||
"streamd/apps/agent/internal/worker"
|
||||
"streamd/apps/agent/internal/wsclient"
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"streamd/wvkey"
|
||||
)
|
||||
|
||||
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
||||
|
|
@ -36,6 +39,14 @@ func Run(args []string) error {
|
|||
switch sub {
|
||||
case "run":
|
||||
runCmd(sub, rest)
|
||||
case "start":
|
||||
return startDaemonCmd(rest)
|
||||
case "stop":
|
||||
return stopDaemonCmd(rest)
|
||||
case "restart":
|
||||
return restartDaemonCmd(rest)
|
||||
case "update":
|
||||
return updateDaemonCmd(rest)
|
||||
case "status":
|
||||
statusCmd(sub, rest)
|
||||
case "devices":
|
||||
|
|
@ -58,8 +69,13 @@ func Usage() {
|
|||
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
||||
|
||||
Usage:
|
||||
agent run [--config apps/agent/agent.yaml]
|
||||
agent status [--config ...]
|
||||
agent start [--config agent.yaml] # background (pid + log)
|
||||
agent stop [--config ...]
|
||||
agent restart [--config ...]
|
||||
agent status [--config ...] # process + recent jobs
|
||||
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
|
||||
agent run [--config ...] # foreground (debug)
|
||||
|
||||
agent devices [--config ...]
|
||||
agent enqueue --stream NAME [--reason manual] [--config ...]
|
||||
agent cancel --job ID [--config ...]
|
||||
|
|
@ -68,6 +84,9 @@ Polls streamd for enabled streams that are down / missing credentials,
|
|||
enqueues jobs, claims a free phone that already has the app, captures
|
||||
via MITM, POSTs credentials, then force-stops the app.
|
||||
|
||||
Job retries default to immediate (job_backoff: false). Set job_backoff: true
|
||||
in agent.yaml for exponential delays when several agents share work.
|
||||
|
||||
Does not install apps. Does not run NRE/ffmpeg.
|
||||
`)
|
||||
}
|
||||
|
|
@ -117,6 +136,18 @@ func runCmd(sub string, args []string) {
|
|||
"create an operator API key in the streamd dashboard", me.Role)
|
||||
}
|
||||
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
|
||||
|
||||
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
|
||||
// once per install root so Windows / Linux / macOS agents all work.
|
||||
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
|
||||
log.Fatalf("widevine helper: %v", err)
|
||||
} else {
|
||||
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
|
||||
if strings.TrimSpace(cfg.Python) == "" {
|
||||
cfg.Python = rt.Python
|
||||
}
|
||||
}
|
||||
|
||||
q := openQueue(cfg)
|
||||
defer q.Close()
|
||||
|
||||
|
|
@ -125,6 +156,16 @@ func runCmd(sub string, args []string) {
|
|||
} else if n > 0 {
|
||||
log.Printf("re-queued %d stuck running job(s) from previous run", n)
|
||||
}
|
||||
if n, err := q.ClearAllBackoffs(); err != nil {
|
||||
log.Printf("clear backoffs: %v", err)
|
||||
} else if n > 0 {
|
||||
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
|
||||
}
|
||||
if cfg.JobBackoffEnabled() {
|
||||
log.Printf("job_backoff=true (exponential delays after failures)")
|
||||
} else {
|
||||
log.Printf("job_backoff=false (retry failed captures immediately)")
|
||||
}
|
||||
|
||||
pool := device.New("", cfg.Devices)
|
||||
stop := make(chan struct{})
|
||||
|
|
@ -205,6 +246,7 @@ func runCmd(sub string, args []string) {
|
|||
Python: cfg.Python,
|
||||
WVD: cfg.WVD,
|
||||
UserAgent: cfg.UserAgent,
|
||||
JobBackoff: cfg.JobBackoffEnabled(),
|
||||
Log: log.Default(),
|
||||
}
|
||||
go w.Loop(stop)
|
||||
|
|
@ -225,6 +267,7 @@ func runCmd(sub string, args []string) {
|
|||
|
||||
func statusCmd(sub string, args []string) {
|
||||
cfg, _ := loadCfg(sub, args)
|
||||
printDaemonStatus(cfg)
|
||||
q := openQueue(cfg)
|
||||
defer q.Close()
|
||||
jobs, err := q.ListRecent(40)
|
||||
|
|
|
|||
177
apps/agent/agentcmd/daemon.go
Normal file
177
apps/agent/agentcmd/daemon.go
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
package agentcmd
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
func readPID(pidFile string) (int, error) {
|
||||
b, err := os.ReadFile(pidFile)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return strconv.Atoi(strings.TrimSpace(string(b)))
|
||||
}
|
||||
|
||||
func writePID(pidFile string, pid int) error {
|
||||
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func removePID(pidFile string) { _ = os.Remove(pidFile) }
|
||||
|
||||
func runningPID(cfg config.Config) (int, bool) {
|
||||
pid, err := readPID(cfg.PIDFile)
|
||||
if err != nil || pid <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
return pid, false
|
||||
}
|
||||
return pid, true
|
||||
}
|
||||
|
||||
func printDaemonStatus(cfg config.Config) {
|
||||
fmt.Printf("config: %s\n", cfgPathHint(cfg))
|
||||
fmt.Printf("pid: %s\n", cfg.PIDFile)
|
||||
fmt.Printf("log: %s\n", cfg.LogFile)
|
||||
if pid, ok := runningPID(cfg); ok {
|
||||
fmt.Printf("agent: running pid=%d\n", pid)
|
||||
} else {
|
||||
fmt.Println("agent: stopped")
|
||||
}
|
||||
}
|
||||
|
||||
func cfgPathHint(cfg config.Config) string {
|
||||
// Best-effort: show data dir; exact yaml path was already resolved by Load.
|
||||
return cfg.DataDir
|
||||
}
|
||||
|
||||
func startDaemonCmd(args []string) error {
|
||||
cfg, cfgFile := loadCfgWithPath("start", args)
|
||||
if pid, ok := runningPID(cfg); ok {
|
||||
fmt.Printf("agent already running (pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = resolved
|
||||
}
|
||||
runArgs := []string{"agent", "run"}
|
||||
if cfgFile != "" {
|
||||
runArgs = append(runArgs, "--config", cfgFile)
|
||||
}
|
||||
cmd := exec.Command(exe, runArgs...)
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.Stdout = logF
|
||||
cmd.Stderr = logF
|
||||
cmd.Stdin = nil
|
||||
detachProcess(cmd)
|
||||
if err := cmd.Start(); err != nil {
|
||||
_ = logF.Close()
|
||||
return fmt.Errorf("start agent: %w", err)
|
||||
}
|
||||
pid := cmd.Process.Pid
|
||||
_ = cmd.Process.Release()
|
||||
_ = logF.Close()
|
||||
if err := writePID(cfg.PIDFile, pid); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
|
||||
}
|
||||
fmt.Printf("agent started pid=%d\n", pid)
|
||||
fmt.Printf("logs: %s\n", cfg.LogFile)
|
||||
return nil
|
||||
}
|
||||
|
||||
func stopDaemonCmd(args []string) error {
|
||||
cfg, _ := loadCfgWithPath("stop", args)
|
||||
pid, err := readPID(cfg.PIDFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
fmt.Println("agent is not running")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Println("agent is not running (stale pid file removed)")
|
||||
return nil
|
||||
}
|
||||
if err := signalTerminate(pid); err != nil {
|
||||
return fmt.Errorf("stop pid %d: %w", pid, err)
|
||||
}
|
||||
deadline := time.Now().Add(8 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Printf("agent stopped (was pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
_ = signalKill(pid)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Printf("agent killed (pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
|
||||
func restartDaemonCmd(args []string) error {
|
||||
_ = stopDaemonCmd(args)
|
||||
return startDaemonCmd(args)
|
||||
}
|
||||
|
||||
// loadCfgWithPath returns config and the resolved --config path (may be empty).
|
||||
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
|
||||
fs := flag.NewFlagSet(sub, flag.ExitOnError)
|
||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
||||
_ = fs.Parse(args)
|
||||
path := strings.TrimSpace(*cfgPath)
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "[!]", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if path == "" {
|
||||
// Mirror config.Load default discovery for daemon child argv.
|
||||
path = defaultConfigPath()
|
||||
} else if !filepath.IsAbs(path) {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err == nil {
|
||||
path = abs
|
||||
}
|
||||
}
|
||||
return cfg, path
|
||||
}
|
||||
|
||||
// defaultConfigPath matches config.Load("") discovery so the background child
|
||||
// reopens the same yaml the parent resolved.
|
||||
func defaultConfigPath() string {
|
||||
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
|
||||
}
|
||||
37
apps/agent/agentcmd/daemon_unix.go
Normal file
37
apps/agent/agentcmd/daemon_unix.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
//go:build unix
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func detachProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
}
|
||||
|
||||
func signalAlive(pid int) bool {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return p.Signal(syscall.Signal(0)) == nil
|
||||
}
|
||||
|
||||
func signalTerminate(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Signal(syscall.SIGTERM)
|
||||
}
|
||||
|
||||
func signalKill(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Signal(syscall.SIGKILL)
|
||||
}
|
||||
46
apps/agent/agentcmd/daemon_windows.go
Normal file
46
apps/agent/agentcmd/daemon_windows.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
//go:build windows
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func detachProcess(cmd *exec.Cmd) {
|
||||
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
|
||||
// stdout/stderr still reach the log file opened by the parent.
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
|
||||
}
|
||||
}
|
||||
|
||||
func signalAlive(pid int) bool {
|
||||
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
|
||||
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
var code uint32
|
||||
if err := windows.GetExitCodeProcess(h, &code); err != nil {
|
||||
return false
|
||||
}
|
||||
const stillActive = 259 // STILL_ACTIVE
|
||||
return code == stillActive
|
||||
}
|
||||
|
||||
func signalTerminate(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Kill()
|
||||
}
|
||||
|
||||
func signalKill(pid int) error {
|
||||
return signalTerminate(pid)
|
||||
}
|
||||
282
apps/agent/agentcmd/update.go
Normal file
282
apps/agent/agentcmd/update.go
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
package agentcmd
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
const (
|
||||
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
|
||||
defaultChannel = "stable"
|
||||
)
|
||||
|
||||
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
|
||||
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
|
||||
|
||||
func defaultAssetName() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-linux-amd64"
|
||||
case "arm64":
|
||||
return "streamd-linux-arm64"
|
||||
}
|
||||
case "darwin":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-darwin-amd64"
|
||||
case "arm64":
|
||||
return "streamd-darwin-arm64"
|
||||
}
|
||||
case "windows":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-windows-amd64.exe"
|
||||
case "arm64":
|
||||
return "streamd-windows-arm64.exe"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func updateURL(base, ref, asset string) string {
|
||||
base = strings.TrimRight(base, "/")
|
||||
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
|
||||
}
|
||||
|
||||
func updateDaemonCmd(args []string) error {
|
||||
fs := flag.NewFlagSet("update", flag.ExitOnError)
|
||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
||||
beta := fs.Bool("beta", false, "use beta channel")
|
||||
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
|
||||
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
|
||||
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
path := strings.TrimSpace(*cfgPath)
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if path == "" {
|
||||
path = defaultConfigPath()
|
||||
} else if !filepath.IsAbs(path) {
|
||||
if abs, err := filepath.Abs(path); err == nil {
|
||||
path = abs
|
||||
}
|
||||
}
|
||||
|
||||
channel := cfg.Channel
|
||||
if channel == "" {
|
||||
channel = defaultChannel
|
||||
}
|
||||
if *beta {
|
||||
channel = "beta"
|
||||
}
|
||||
ref := channel
|
||||
if strings.TrimSpace(*tag) != "" {
|
||||
ref = strings.TrimSpace(*tag)
|
||||
}
|
||||
asset := cfg.Asset
|
||||
if asset == "" {
|
||||
asset = defaultAssetName()
|
||||
}
|
||||
if asset == "" {
|
||||
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
keepN := 10
|
||||
if cfg.KeepOld != nil {
|
||||
keepN = *cfg.KeepOld
|
||||
}
|
||||
if *keep >= 0 {
|
||||
keepN = *keep
|
||||
}
|
||||
|
||||
installRoot := repo.Root()
|
||||
url := updateURL(releaseBaseURL, ref, asset)
|
||||
fmt.Printf("agent update: downloading %s\n", url)
|
||||
|
||||
tmp, err := downloadToTemp(installRoot, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp)
|
||||
|
||||
if err := smokeTestBinary(tmp); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = resolved
|
||||
}
|
||||
target := exe
|
||||
wantName := "streamd"
|
||||
if runtime.GOOS == "windows" {
|
||||
wantName = "streamd.exe"
|
||||
}
|
||||
// Prefer well-known names in the install / Downloads tree.
|
||||
for _, candidate := range []string{
|
||||
filepath.Join(installRoot, wantName),
|
||||
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
|
||||
filepath.Join(installRoot, "streamd-linux-amd64"),
|
||||
filepath.Join(installRoot, "bin", wantName),
|
||||
} {
|
||||
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
|
||||
target = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
// If the running exe is already a streamd binary in this tree, prefer it.
|
||||
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
|
||||
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
|
||||
target = exe
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := runningPID(cfg); ok {
|
||||
fmt.Println("agent update: stopping running agent…")
|
||||
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
oldDir := filepath.Join(filepath.Dir(target), "old")
|
||||
if err := os.MkdirAll(oldDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
stamp := time.Now().UTC().Format("20060102T150405Z")
|
||||
archive := filepath.Join(oldDir, "streamd."+stamp)
|
||||
if runtime.GOOS == "windows" {
|
||||
archive += ".exe"
|
||||
}
|
||||
if _, err := os.Stat(archive); err == nil {
|
||||
archive += "." + fmt.Sprint(os.Getpid())
|
||||
}
|
||||
|
||||
if *noRestart {
|
||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
|
||||
} else {
|
||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
|
||||
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
|
||||
}
|
||||
if err := replaceBinary(target, tmp, archive); err != nil {
|
||||
if err == errUpdateDeferred {
|
||||
return nil // helper finishes after exit; treat as success for CLI
|
||||
}
|
||||
return err
|
||||
}
|
||||
fmt.Printf("agent update: archived previous → %s\n", archive)
|
||||
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
|
||||
pruneOldBinaries(oldDir, keepN)
|
||||
|
||||
if *noRestart {
|
||||
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
|
||||
return nil
|
||||
}
|
||||
fmt.Println("agent update: starting…")
|
||||
return startDaemonCmd([]string{"--config", path})
|
||||
}
|
||||
|
||||
func downloadToTemp(dir, url string) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".streamd-download-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := f.Name()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
|
||||
}
|
||||
n, err := io.Copy(f, resp.Body)
|
||||
closeErr := f.Close()
|
||||
if err != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", err
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", closeErr
|
||||
}
|
||||
if n < 1024 {
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
|
||||
}
|
||||
head, _ := os.ReadFile(path)
|
||||
if len(head) > 32 {
|
||||
h := strings.ToLower(string(head[:32]))
|
||||
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
|
||||
}
|
||||
}
|
||||
_ = os.Chmod(path, 0o755)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func smokeTestBinary(path string) error {
|
||||
cmd := exec.Command(path, "help")
|
||||
out, err := cmd.CombinedOutput()
|
||||
text := string(out)
|
||||
if err != nil {
|
||||
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
|
||||
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneOldBinaries(oldDir string, keep int) {
|
||||
if keep <= 0 {
|
||||
return
|
||||
}
|
||||
ents, err := os.ReadDir(oldDir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, e := range ents {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
n := e.Name()
|
||||
if strings.HasPrefix(n, "streamd.") {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
if len(names) <= keep {
|
||||
return
|
||||
}
|
||||
for _, n := range names[:len(names)-keep] {
|
||||
_ = os.Remove(filepath.Join(oldDir, n))
|
||||
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
|
||||
}
|
||||
}
|
||||
21
apps/agent/agentcmd/update_unix.go
Normal file
21
apps/agent/agentcmd/update_unix.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
//go:build unix
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// replaceBinary moves the live binary to archive, then moves next into place.
|
||||
func replaceBinary(target, next, archive string) error {
|
||||
if err := os.Rename(target, archive); err != nil {
|
||||
return fmt.Errorf("archive current binary: %w", err)
|
||||
}
|
||||
if err := os.Rename(next, target); err != nil {
|
||||
_ = os.Rename(archive, target)
|
||||
return fmt.Errorf("install new binary: %w", err)
|
||||
}
|
||||
_ = os.Chmod(target, 0o755)
|
||||
return nil
|
||||
}
|
||||
125
apps/agent/agentcmd/update_windows.go
Normal file
125
apps/agent/agentcmd/update_windows.go
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
//go:build windows
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
|
||||
// 1. Move target → archive when target is not our own running image.
|
||||
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
|
||||
// waits for this PID to exit, then swaps and optionally starts the agent.
|
||||
func replaceBinary(target, next, archive string) error {
|
||||
self, _ := os.Executable()
|
||||
if resolved, err := filepath.EvalSymlinks(self); err == nil {
|
||||
self = resolved
|
||||
}
|
||||
same, _ := sameFile(self, target)
|
||||
|
||||
if !same {
|
||||
if err := os.Rename(target, archive); err != nil {
|
||||
if err2 := copyFile(target, archive); err2 != nil {
|
||||
return fmt.Errorf("archive current binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(target)
|
||||
}
|
||||
if err := os.Rename(next, target); err != nil {
|
||||
if err2 := copyFile(next, target); err2 != nil {
|
||||
_ = os.Rename(archive, target)
|
||||
return fmt.Errorf("install new binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(next)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
newPath := target + ".new"
|
||||
_ = os.Remove(newPath)
|
||||
if err := os.Rename(next, newPath); err != nil {
|
||||
if err2 := copyFile(next, newPath); err2 != nil {
|
||||
return fmt.Errorf("stage new binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(next)
|
||||
}
|
||||
|
||||
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
|
||||
pid := os.Getpid()
|
||||
startLine := ""
|
||||
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
|
||||
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
|
||||
if cfg != "" {
|
||||
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
|
||||
} else {
|
||||
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
|
||||
}
|
||||
}
|
||||
script := fmt.Sprintf(""+
|
||||
"@echo off\r\n"+
|
||||
":wait\r\n"+
|
||||
"timeout /t 1 /nobreak >nul\r\n"+
|
||||
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
|
||||
"if not errorlevel 1 goto wait\r\n"+
|
||||
"move /Y \"%s\" \"%s\"\r\n"+
|
||||
"move /Y \"%s\" \"%s\"\r\n"+
|
||||
"%s"+
|
||||
"del \"%%~f0\"\r\n",
|
||||
pid, pid,
|
||||
escapeCmd(target), escapeCmd(archive),
|
||||
escapeCmd(newPath), escapeCmd(target),
|
||||
startLine,
|
||||
)
|
||||
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.Command("cmd.exe", "/C", helper)
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
detachProcess(cmd)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start update helper: %w", err)
|
||||
}
|
||||
_ = cmd.Process.Release()
|
||||
fmt.Println("agent update: scheduled file swap after this process exits")
|
||||
fmt.Println("agent update: agent will restart automatically in 1–2s")
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
return errUpdateDeferred
|
||||
}
|
||||
|
||||
func escapeCmd(p string) string {
|
||||
return p
|
||||
}
|
||||
|
||||
func sameFile(a, b string) (bool, error) {
|
||||
absA, err := filepath.Abs(a)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
absB, err := filepath.Abs(b)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return filepath.Clean(absA) == filepath.Clean(absB), nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := out.ReadFrom(in)
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
|
@ -36,6 +36,16 @@ type Config struct {
|
|||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
||||
// of routine refreshes in the queue.
|
||||
OnDemandPriority *bool `yaml:"ondemand_priority"`
|
||||
// JobBackoff enables exponential retry delays after a failed capture
|
||||
// (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
|
||||
// Set job_backoff: true when several agents share the same streams.
|
||||
JobBackoff *bool `yaml:"job_backoff"`
|
||||
// Daemon / update (streamd agent start|stop|update)
|
||||
LogFile string `yaml:"log_file"` // default agent.log next to config / install root
|
||||
PIDFile string `yaml:"pid_file"` // default agent.pid
|
||||
Channel string `yaml:"channel"` // stable|beta for agent update
|
||||
Asset string `yaml:"asset"` // optional streamd-* asset override
|
||||
KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
|
||||
}
|
||||
|
||||
// PushedCapturesArePriority reports whether pushed captures jump the queue.
|
||||
|
|
@ -44,6 +54,12 @@ func (c Config) PushedCapturesArePriority() bool {
|
|||
return c.OnDemandPriority == nil || *c.OnDemandPriority
|
||||
}
|
||||
|
||||
// JobBackoffEnabled is the exponential multi-agent retry delay.
|
||||
// Defaults to false so a lone agent retries immediately after a failure.
|
||||
func (c Config) JobBackoffEnabled() bool {
|
||||
return c.JobBackoff != nil && *c.JobBackoff
|
||||
}
|
||||
|
||||
func (c Config) PollInterval() time.Duration {
|
||||
if c.PollIntervalSec <= 0 {
|
||||
return 30 * time.Second
|
||||
|
|
@ -125,6 +141,9 @@ func applyDefaults(cfg Config, root string) Config {
|
|||
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
||||
cfg.WVD = filepath.Join(root, cfg.WVD)
|
||||
}
|
||||
if cfg.Python != "" && !filepath.IsAbs(cfg.Python) {
|
||||
cfg.Python = filepath.Join(root, cfg.Python)
|
||||
}
|
||||
if cfg.ModulesDir == "" {
|
||||
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
||||
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
||||
|
|
@ -133,6 +152,25 @@ func applyDefaults(cfg Config, root string) Config {
|
|||
if cfg.ModulesSyncIntervalSec <= 0 {
|
||||
cfg.ModulesSyncIntervalSec = 300
|
||||
}
|
||||
if cfg.LogFile == "" {
|
||||
cfg.LogFile = "agent.log"
|
||||
}
|
||||
if !filepath.IsAbs(cfg.LogFile) {
|
||||
cfg.LogFile = filepath.Join(root, cfg.LogFile)
|
||||
}
|
||||
if cfg.PIDFile == "" {
|
||||
cfg.PIDFile = "agent.pid"
|
||||
}
|
||||
if !filepath.IsAbs(cfg.PIDFile) {
|
||||
cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
|
||||
}
|
||||
if cfg.Channel == "" {
|
||||
cfg.Channel = "stable"
|
||||
}
|
||||
if cfg.KeepOld == nil {
|
||||
k := 10
|
||||
cfg.KeepOld = &k
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -232,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
|
||||
// MarkFailed increments attempts. Re-queues unless maxed out.
|
||||
// waitingDevice=true keeps status queued without burning an attempt.
|
||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
|
||||
// backoff is how long to wait before the job is runnable again (0 = immediate).
|
||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
|
||||
j, err := s.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if waitingDevice {
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
|
||||
msg, id)
|
||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
|
||||
msg, now(), id)
|
||||
return err
|
||||
}
|
||||
attempts := j.Attempts + 1
|
||||
|
|
@ -252,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
|
|||
attempts, msg, now(), id)
|
||||
return err
|
||||
}
|
||||
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||
if backoff > 15*time.Minute {
|
||||
backoff = 15 * time.Minute
|
||||
if backoff < 0 {
|
||||
backoff = 0
|
||||
}
|
||||
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
||||
_, err = s.DB.Exec(`
|
||||
|
|
@ -263,6 +263,29 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
|
|||
return err
|
||||
}
|
||||
|
||||
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
|
||||
func ExponentialBackoff(attempts int) time.Duration {
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||
if d > 15*time.Minute {
|
||||
d = 15 * time.Minute
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
|
||||
// after fixing modules, or when job_backoff is disabled).
|
||||
func (s *Store) ClearAllBackoffs() (int, error) {
|
||||
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
|
|
|
|||
|
|
@ -27,7 +27,10 @@ type Worker struct {
|
|||
Python string
|
||||
WVD string
|
||||
UserAgent string
|
||||
Log *log.Logger
|
||||
// JobBackoff enables exponential delays between failed capture attempts.
|
||||
// When false (default), failed jobs are re-queued immediately.
|
||||
JobBackoff bool
|
||||
Log *log.Logger
|
||||
|
||||
lastDelayLog time.Time
|
||||
}
|
||||
|
|
@ -67,13 +70,18 @@ func (w *Worker) tick() {
|
|||
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
||||
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
||||
w.logf("job=%d waiting: %v", job.ID, err)
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
|
||||
return
|
||||
}
|
||||
w.logf("job=%d failed: %v", job.ID, err)
|
||||
w.event(job, client.EventCaptureFailed, err.Error(),
|
||||
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
|
||||
backoff := time.Duration(0)
|
||||
if w.JobBackoff {
|
||||
backoff = queue.ExponentialBackoff(job.Attempts + 1)
|
||||
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
|
||||
}
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
|
||||
return
|
||||
}
|
||||
_ = w.Queue.MarkOK(job.ID)
|
||||
|
|
@ -119,8 +127,8 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
_ = w.Queue.SetDevice(job.ID, serial)
|
||||
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
||||
|
||||
// Short TTL; /ws/agent heartbeats renew while this process is alive.
|
||||
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
|
||||
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
|
||||
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
|
||||
return fmt.Errorf("streamd claim: %w", err)
|
||||
}
|
||||
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
||||
|
|
@ -140,6 +148,19 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
return err
|
||||
}
|
||||
|
||||
needsKeys := true
|
||||
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
|
||||
needsKeys = false
|
||||
}
|
||||
hasKey := poller.ValidKeyPair(res.Key)
|
||||
if needsKeys && !hasKey {
|
||||
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
|
||||
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
|
||||
}
|
||||
if strings.TrimSpace(res.MPD) == "" {
|
||||
return fmt.Errorf("refusing to post credentials without mpd")
|
||||
}
|
||||
|
||||
cred := client.Credentials{
|
||||
MPD: res.MPD,
|
||||
Key: res.Key,
|
||||
|
|
@ -150,15 +171,25 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
||||
return fmt.Errorf("post credentials: %w", err)
|
||||
}
|
||||
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
|
||||
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
|
||||
// Report what was captured, never the key itself.
|
||||
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
||||
"device": serial,
|
||||
"has_key": strings.TrimSpace(res.Key) != "",
|
||||
"key_valid": poller.ValidKeyPair(res.Key),
|
||||
"key_valid": hasKey,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func trimURL(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) <= 96 {
|
||||
return s
|
||||
}
|
||||
return s[:96] + "…"
|
||||
}
|
||||
|
||||
// event posts a stream event to streamd. A timeline entry is never worth
|
||||
// failing a capture over, so errors are logged and dropped.
|
||||
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
||||
|
|
|
|||
6
apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
Normal file
6
apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
# Dependencies for wvkey.py (the only Python in the project).
|
||||
# Install into a venv at the repo root:
|
||||
# python -m venv .venv
|
||||
# .venv/bin/pip install -r apps/wvkey/requirements.txt
|
||||
pywidevine==1.9.0
|
||||
requests==2.34.2
|
||||
367
apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
Normal file
367
apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Thin Widevine CDM helper for the Go capture tooling.
|
||||
|
||||
Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
|
||||
Exit code 0 on success.
|
||||
|
||||
Example:
|
||||
.venv/Scripts/python.exe wvkey.py \\
|
||||
--wvd path/to/device.wvd \\
|
||||
--pssh 'AAAA…' \\
|
||||
--license-url 'https://…' \\
|
||||
--auth 'Basic …' \\
|
||||
--pid 'xxxx' \\
|
||||
--quiet
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from pywidevine.cdm import Cdm
|
||||
from pywidevine.device import Device
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
|
||||
def fetch_content_keys_modulardrm(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
auth: str,
|
||||
release_pid: str,
|
||||
license_url: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
||||
payload = {
|
||||
"getWidevineLicense": {
|
||||
"releasePid": release_pid,
|
||||
"widevineChallenge": challenge_b64,
|
||||
}
|
||||
}
|
||||
headers = {
|
||||
"Accept-Encoding": "gzip",
|
||||
"Authorization": auth,
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(license_url, json=payload, headers=headers, timeout=30)
|
||||
data = response.json()
|
||||
if data.get("isException"):
|
||||
raise RuntimeError(data.get("description") or "license server exception")
|
||||
license_b64 = (
|
||||
data.get("getWidevineLicenseResponse", {}).get("license")
|
||||
or data.get("license")
|
||||
)
|
||||
if not license_b64:
|
||||
raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
|
||||
cdm.parse_license(session_id, base64.b64decode(license_b64))
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
def fetch_content_keys_raw(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
license_url: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
headers = {
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(
|
||||
license_url, data=challenge, headers=headers, timeout=30
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
||||
)
|
||||
body = response.content
|
||||
if not body:
|
||||
raise RuntimeError("empty license response body")
|
||||
# Some servers wrap base64 text; try raw first, then b64.
|
||||
try:
|
||||
cdm.parse_license(session_id, body)
|
||||
except Exception:
|
||||
try:
|
||||
cdm.parse_license(session_id, base64.b64decode(body))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"parse_license failed ({len(body)} bytes): {exc}"
|
||||
) from exc
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
_CHALLENGE_KEYS = (
|
||||
"request",
|
||||
"licenseRequest",
|
||||
"license_request",
|
||||
"widevineChallenge",
|
||||
"widevine_challenge",
|
||||
"challenge",
|
||||
"payload",
|
||||
"rawLicenseRequestBase64",
|
||||
"message",
|
||||
"drm_info",
|
||||
)
|
||||
|
||||
|
||||
def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
|
||||
"""Replace the Widevine challenge field inside a captured JSON license body."""
|
||||
if isinstance(obj, dict):
|
||||
for key in _CHALLENGE_KEYS:
|
||||
if key not in obj:
|
||||
continue
|
||||
val = obj[key]
|
||||
if key == "drm_info" and isinstance(val, list):
|
||||
obj[key] = list(challenge_bytes)
|
||||
return True
|
||||
if isinstance(val, str) and len(val) >= 8:
|
||||
obj[key] = challenge_b64
|
||||
return True
|
||||
if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
for val in obj.values():
|
||||
if _replace_challenge(val, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
elif isinstance(obj, list):
|
||||
for item in obj:
|
||||
if _replace_challenge(item, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _license_bytes_from_response(response: requests.Response) -> bytes:
|
||||
body = response.content
|
||||
if not body:
|
||||
raise RuntimeError("empty license response body")
|
||||
# Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
|
||||
try:
|
||||
data = response.json()
|
||||
except Exception:
|
||||
data = None
|
||||
if isinstance(data, dict):
|
||||
for path in (
|
||||
("license",),
|
||||
("licenseResponse",),
|
||||
("license_response",),
|
||||
("payload",),
|
||||
("message",),
|
||||
("getWidevineLicenseResponse", "license"),
|
||||
("status", "license"),
|
||||
):
|
||||
cur: object = data
|
||||
ok = True
|
||||
for key in path:
|
||||
if not isinstance(cur, dict) or key not in cur:
|
||||
ok = False
|
||||
break
|
||||
cur = cur[key]
|
||||
if ok and isinstance(cur, str) and cur:
|
||||
try:
|
||||
return base64.b64decode(cur)
|
||||
except Exception:
|
||||
return cur.encode("utf-8")
|
||||
# Some LSP responses nest the blob under status.success payload.
|
||||
if data.get("status", {}).get("success") is False:
|
||||
raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
|
||||
return body
|
||||
|
||||
|
||||
def fetch_content_keys_wrap(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
license_url: str,
|
||||
wrap_json: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""Re-POST a captured JSON license body with a fresh local CDM challenge.
|
||||
|
||||
Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
|
||||
octet-stream (HTTP 415) and need the phone's token fields intact.
|
||||
"""
|
||||
try:
|
||||
template = json.loads(wrap_json)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
|
||||
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
||||
if not _replace_challenge(template, challenge_b64, challenge):
|
||||
raise RuntimeError(
|
||||
"wrap-json has no recognisable challenge field "
|
||||
f"(tried {', '.join(_CHALLENGE_KEYS)})"
|
||||
)
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, */*",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(
|
||||
license_url, json=template, headers=headers, timeout=30
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
||||
)
|
||||
license_bytes = _license_bytes_from_response(response)
|
||||
try:
|
||||
cdm.parse_license(session_id, license_bytes)
|
||||
except Exception:
|
||||
try:
|
||||
cdm.parse_license(session_id, base64.b64decode(license_bytes))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"parse_license failed ({len(license_bytes)} bytes): {exc}"
|
||||
) from exc
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
|
||||
p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
|
||||
p.add_argument("--pssh", required=True, help="Base64 PSSH box")
|
||||
p.add_argument(
|
||||
"--mode",
|
||||
choices=("modulardrm", "raw", "wrap"),
|
||||
default="modulardrm",
|
||||
help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
|
||||
)
|
||||
p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
|
||||
p.add_argument("--pid", default="", help="releasePid (modulardrm)")
|
||||
p.add_argument(
|
||||
"--wrap-json",
|
||||
default="",
|
||||
help="Captured phone license POST JSON (wrap mode)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--license-url",
|
||||
required=True,
|
||||
help="Widevine license server URL",
|
||||
)
|
||||
p.add_argument(
|
||||
"--user-agent",
|
||||
default="",
|
||||
help="Optional User-Agent for the license request",
|
||||
)
|
||||
p.add_argument(
|
||||
"--quiet",
|
||||
action="store_true",
|
||||
help="Print only KID:KEY lines (for Go tooling)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--all",
|
||||
action="store_true",
|
||||
help="Print every CONTENT key (default: first only)",
|
||||
)
|
||||
args = p.parse_args(argv)
|
||||
|
||||
if not args.wvd.is_file():
|
||||
print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
try:
|
||||
if args.mode == "raw":
|
||||
keys = fetch_content_keys_raw(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
license_url=args.license_url,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
elif args.mode == "wrap":
|
||||
if not args.wrap_json.strip():
|
||||
print(
|
||||
"[!] --wrap-json required for wrap mode "
|
||||
"(phone must complete a license POST during capture)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
keys = fetch_content_keys_wrap(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
license_url=args.license_url,
|
||||
wrap_json=args.wrap_json,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
else:
|
||||
if not args.auth or not args.pid:
|
||||
print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
|
||||
return 2
|
||||
keys = fetch_content_keys_modulardrm(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
auth=args.auth,
|
||||
release_pid=args.pid,
|
||||
license_url=args.license_url,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"[!] {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
out = keys if args.all else keys[:1]
|
||||
if not args.quiet:
|
||||
print("[+] Keys:", file=sys.stderr)
|
||||
for pair in out:
|
||||
print(f"--key {pair}", file=sys.stderr)
|
||||
for pair in out:
|
||||
print(pair)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -105,5 +105,9 @@ func Load(root, name string) (Module, string, Describe, error) {
|
|||
if d.Name == "" {
|
||||
d.Name = m.Name
|
||||
}
|
||||
// Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
|
||||
// exe-adjacent layout, leaving package empty (breaks transparent MITM —
|
||||
// iptables then treats the listen port as the package name).
|
||||
enrichDescribeFromYAML(&d, m.Dir)
|
||||
return m, bin, d, nil
|
||||
}
|
||||
|
|
|
|||
77
apps/pkg/modhost/yaml_enrich.go
Normal file
77
apps/pkg/modhost/yaml_enrich.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
package modhost
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// enrichDescribeFromYAML fills gaps left by older module binaries that do not
|
||||
// load panel/agent module.yaml (empty package breaks transparent MITM).
|
||||
func enrichDescribeFromYAML(d *Describe, modDir string) {
|
||||
if d == nil || strings.TrimSpace(modDir) == "" {
|
||||
return
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
|
||||
if err != nil {
|
||||
raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
var doc struct {
|
||||
Package string `yaml:"package"`
|
||||
LicenseURL string `yaml:"license_url"`
|
||||
KeyMode string `yaml:"key_mode"`
|
||||
ProxyBin string `yaml:"proxy_bin"`
|
||||
CAHash string `yaml:"ca_hash"`
|
||||
TransparentMITM *bool `yaml:"transparent_mitm"`
|
||||
RequireWVD *bool `yaml:"require_wvd"`
|
||||
Rewriter string `yaml:"rewriter"`
|
||||
Channels map[string]struct {
|
||||
Label string `yaml:"label"`
|
||||
} `yaml:"channels"`
|
||||
}
|
||||
if err := yaml.Unmarshal(raw, &doc); err != nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
|
||||
d.Package = strings.TrimSpace(doc.Package)
|
||||
}
|
||||
if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
|
||||
d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
|
||||
}
|
||||
if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
|
||||
d.KeyMode = strings.TrimSpace(doc.KeyMode)
|
||||
}
|
||||
if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
|
||||
d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
|
||||
}
|
||||
if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
|
||||
d.CAHash = strings.TrimSpace(doc.CAHash)
|
||||
}
|
||||
if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
|
||||
d.Rewriter = strings.TrimSpace(doc.Rewriter)
|
||||
}
|
||||
if !d.TransparentMITM && doc.TransparentMITM != nil {
|
||||
d.TransparentMITM = *doc.TransparentMITM
|
||||
}
|
||||
if !d.RequireWVD && doc.RequireWVD != nil {
|
||||
d.RequireWVD = *doc.RequireWVD
|
||||
}
|
||||
if len(d.Channels) == 0 && len(doc.Channels) > 0 {
|
||||
for id, ch := range doc.Channels {
|
||||
label := strings.TrimSpace(ch.Label)
|
||||
if label == "" {
|
||||
label = id
|
||||
}
|
||||
d.Channels = append(d.Channels, Channel{ID: id, Label: label})
|
||||
}
|
||||
}
|
||||
if !d.ValuesLoaded {
|
||||
d.ValuesLoaded = true
|
||||
d.ValuesPath = filepath.Join(modDir, "module.yaml")
|
||||
}
|
||||
}
|
||||
|
|
@ -206,17 +206,21 @@ func Run(opt Options) (res Result, err error) {
|
|||
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
||||
useTProxy = true
|
||||
}
|
||||
pkgName := strings.TrimSpace(a.Package())
|
||||
if useTProxy && pkgName == "" {
|
||||
return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
|
||||
}
|
||||
|
||||
if useTProxy {
|
||||
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
||||
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
||||
proxy.ClearHTTPProxy(c)
|
||||
remoteDir := "/data/local/tmp/capture/" + a.Package()
|
||||
remoteDir := "/data/local/tmp/capture/" + pkgName
|
||||
var mitmHosts []string
|
||||
if mh, ok := a.(app.MitmHostList); ok {
|
||||
mitmHosts = mh.MitmHosts()
|
||||
}
|
||||
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||
return res, fmt.Errorf("transparent MITM start: %w", err)
|
||||
}
|
||||
defer proxy.StopTransparent(c)
|
||||
|
|
@ -238,17 +242,6 @@ func Run(opt Options) (res Result, err error) {
|
|||
proxy.ReinjectCA(c, caHash)
|
||||
}
|
||||
|
||||
if err := a.Launch(c); err != nil {
|
||||
return res, fmt.Errorf("launch: %w", err)
|
||||
}
|
||||
if !opt.NoAutoPlay {
|
||||
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
||||
return res, fmt.Errorf("auto-play: %w", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
||||
}
|
||||
|
||||
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
|
||||
serialTag := c.Serial
|
||||
if serialTag == "" {
|
||||
|
|
@ -256,107 +249,161 @@ func Run(opt Options) (res Result, err error) {
|
|||
}
|
||||
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
|
||||
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
|
||||
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
|
||||
_ = os.WriteFile(localLog, nil, 0o644)
|
||||
_ = os.Remove(localCap)
|
||||
stop := make(chan struct{})
|
||||
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
||||
defer close(stop)
|
||||
|
||||
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||
if keyMode == "" || keyMode == "auto" {
|
||||
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||
}
|
||||
needsKeys := keyMode != "none" && keyMode != "clear"
|
||||
|
||||
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
|
||||
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
|
||||
attempts := 1
|
||||
waitPer := opt.Wait
|
||||
if needsKeys {
|
||||
attempts = 3
|
||||
waitPer = 90 * time.Second
|
||||
if opt.Wait > 0 && opt.Wait < waitPer {
|
||||
waitPer = opt.Wait
|
||||
}
|
||||
}
|
||||
|
||||
need := hints.Require
|
||||
if len(need) == 0 {
|
||||
need = []string{"manifest"}
|
||||
}
|
||||
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
|
||||
fmt.Println(" watch:", localLog)
|
||||
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
|
||||
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||
if keyMode == "" || keyMode == "auto" {
|
||||
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||
}
|
||||
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
||||
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
||||
// Skip for clear/MPD-only apps (KeyMode none).
|
||||
if keyMode != "none" && keyMode != "clear" {
|
||||
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
|
||||
curPSSH := strings.TrimSpace(capData.Get("pssh"))
|
||||
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
|
||||
if needPSSH && mpdForPSSH != "" {
|
||||
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
|
||||
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
|
||||
if curPSSH != "" && curPSSH != pssh {
|
||||
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
|
||||
}
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil && curPSSH == "" {
|
||||
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
|
||||
}
|
||||
} else if curPSSH == "" {
|
||||
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mpdURL := strings.TrimSpace(capData.Get("mpd"))
|
||||
// Console: always surface the MPD we will use (BBC clear streams only need this).
|
||||
fmt.Println()
|
||||
fmt.Println("========== MPD ==========")
|
||||
if mpdURL != "" {
|
||||
fmt.Println(mpdURL)
|
||||
} else {
|
||||
fmt.Println("(none)")
|
||||
}
|
||||
fmt.Println("=========================")
|
||||
fmt.Println()
|
||||
fmt.Println("[+] Capture:")
|
||||
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
|
||||
v := capData.Get(k)
|
||||
if k == "license_url" {
|
||||
v = first(v, licenseURL)
|
||||
var (
|
||||
capData capture.Data
|
||||
licenseURL string
|
||||
mpdURL string
|
||||
key string
|
||||
lastErr error
|
||||
)
|
||||
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if attempt > 1 {
|
||||
fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
|
||||
c.ForceStop(a.Package())
|
||||
time.Sleep(800 * time.Millisecond)
|
||||
}
|
||||
if v == "" {
|
||||
|
||||
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
|
||||
_ = os.WriteFile(localLog, nil, 0o644)
|
||||
_ = os.Remove(localCap)
|
||||
|
||||
if err := a.Launch(c); err != nil {
|
||||
lastErr = fmt.Errorf("launch: %w", err)
|
||||
continue
|
||||
}
|
||||
label := k
|
||||
switch k {
|
||||
case "license_url":
|
||||
label = "license"
|
||||
case "license_body":
|
||||
label = "license_body"
|
||||
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
|
||||
if !opt.NoAutoPlay {
|
||||
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
||||
lastErr = fmt.Errorf("auto-play: %w", err)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
||||
}
|
||||
fmt.Println(" ", label+":", trim(v, 120))
|
||||
}
|
||||
|
||||
key := ""
|
||||
if keyMode == "none" || keyMode == "clear" {
|
||||
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
||||
} else {
|
||||
var kerr error
|
||||
key, kerr = fetchKey(opt, root, capData, licenseURL)
|
||||
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
|
||||
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
|
||||
fmt.Println(" watch:", localLog)
|
||||
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
capData = cap
|
||||
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
|
||||
|
||||
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
||||
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
||||
if needsKeys {
|
||||
enrichWidevinePSSH(capData)
|
||||
}
|
||||
|
||||
mpdURL = strings.TrimSpace(capData.Get("mpd"))
|
||||
fmt.Println()
|
||||
fmt.Println("========== MPD ==========")
|
||||
if mpdURL != "" {
|
||||
fmt.Println(mpdURL)
|
||||
} else {
|
||||
fmt.Println("(none)")
|
||||
}
|
||||
fmt.Println("=========================")
|
||||
fmt.Println()
|
||||
fmt.Println("[+] Capture:")
|
||||
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
|
||||
v := capData.Get(k)
|
||||
if k == "license_url" {
|
||||
v = first(v, licenseURL)
|
||||
}
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
label := k
|
||||
switch k {
|
||||
case "license_url":
|
||||
label = "license"
|
||||
case "license_body":
|
||||
label = "license_body"
|
||||
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
|
||||
}
|
||||
fmt.Println(" ", label+":", trim(v, 120))
|
||||
}
|
||||
|
||||
if !needsKeys {
|
||||
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
||||
lastErr = nil
|
||||
break
|
||||
}
|
||||
|
||||
k, kerr := fetchKey(opt, root, capData, licenseURL)
|
||||
if kerr != nil {
|
||||
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
|
||||
// unless the app requires keys (e.g. c4).
|
||||
lastErr = kerr
|
||||
// Missing --wvd on a manual grab-all can soft-save MPD-only; agents
|
||||
// always pass WVD so this path is for interactive capture only.
|
||||
softOK := strings.Contains(kerr.Error(), "requires --wvd")
|
||||
if softOK {
|
||||
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
|
||||
return res, kerr
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
|
||||
} else {
|
||||
return res, kerr
|
||||
key = ""
|
||||
lastErr = nil
|
||||
break
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
|
||||
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
|
||||
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
|
||||
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
key = k
|
||||
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
|
||||
lastErr = nil
|
||||
break
|
||||
}
|
||||
|
||||
if lastErr != nil {
|
||||
if needsKeys {
|
||||
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
|
||||
}
|
||||
return res, lastErr
|
||||
}
|
||||
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
|
||||
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
|
||||
}
|
||||
|
||||
sess := session.Session{
|
||||
|
|
@ -384,6 +431,62 @@ func Run(opt Options) (res Result, err error) {
|
|||
return res, nil
|
||||
}
|
||||
|
||||
func enrichWidevinePSSH(capData capture.Data) {
|
||||
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
|
||||
curPSSH := strings.TrimSpace(capData.Get("pssh"))
|
||||
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
|
||||
if !needPSSH || mpdForPSSH == "" {
|
||||
return
|
||||
}
|
||||
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
|
||||
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
|
||||
if curPSSH != "" && curPSSH != pssh {
|
||||
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
|
||||
}
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil && curPSSH == "" {
|
||||
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if curPSSH == "" {
|
||||
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func looksLikeKey(raw string) bool {
|
||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
kid, k, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hexDigits(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()
|
||||
}
|
||||
|
||||
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
|
||||
func ClearProxyLater(c *adb.Client) {
|
||||
proxy.ClearHTTPProxy(c)
|
||||
|
|
@ -414,16 +517,18 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
|||
if strings.TrimSpace(opt.WVD) == "" {
|
||||
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
||||
}
|
||||
py := opt.Python
|
||||
if py == "" {
|
||||
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
|
||||
if _, err := os.Stat(py); err != nil {
|
||||
py = filepath.Join(root, ".venv", "bin", "python")
|
||||
}
|
||||
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
|
||||
rt, err := wvkey.EnsureRuntime(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
py := rt.Python
|
||||
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
|
||||
py = p
|
||||
}
|
||||
wopt := wvkey.Options{
|
||||
Python: py,
|
||||
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
|
||||
Script: rt.Script,
|
||||
WVD: opt.WVD,
|
||||
PSSH: cap.Get("pssh"),
|
||||
Auth: cap.Get("auth"),
|
||||
|
|
@ -465,6 +570,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
|||
}
|
||||
}
|
||||
|
||||
func fileExistsPath(path string) bool {
|
||||
st, err := os.Stat(path)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
func first(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
|
|
|
|||
|
|
@ -481,10 +481,14 @@ const (
|
|||
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
||||
// mode otherwise only MITMs open.live.bbc.co.uk.
|
||||
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
|
||||
pkg = strings.TrimSpace(pkg)
|
||||
if pkg == "" {
|
||||
return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
|
||||
}
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
if remoteDir == "" {
|
||||
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
|
||||
remoteDir = RemoteCaptureRoot + "/" + pkg
|
||||
}
|
||||
stopProxy(c)
|
||||
|
|
|
|||
172
apps/pkg/wvkey/ensure.go
Normal file
172
apps/pkg/wvkey/ensure.go
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
package wvkey
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
|
||||
type Runtime struct {
|
||||
Python string
|
||||
Script string
|
||||
}
|
||||
|
||||
// ScriptPath returns <root>/apps/wvkey/wvkey.py.
|
||||
func ScriptPath(root string) string {
|
||||
return filepath.Join(root, "apps", "wvkey", "wvkey.py")
|
||||
}
|
||||
|
||||
// VenvPython returns the platform venv interpreter under root, if present.
|
||||
func VenvPython(root string) string {
|
||||
candidates := []string{
|
||||
filepath.Join(root, ".venv", "Scripts", "python.exe"),
|
||||
filepath.Join(root, ".venv", "bin", "python"),
|
||||
filepath.Join(root, ".venv", "bin", "python3"),
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if fileExists(c) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// EnsureRuntime makes sure wvkey.py exists and a usable Python with
|
||||
// pywidevine is available under root (creating .venv when needed).
|
||||
// Works on Windows, Linux, and macOS.
|
||||
func EnsureRuntime(root string) (Runtime, error) {
|
||||
var zero Runtime
|
||||
if root == "" {
|
||||
return zero, fmt.Errorf("wvkey: install root required")
|
||||
}
|
||||
script := ScriptPath(root)
|
||||
if !fileExists(script) {
|
||||
return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
|
||||
}
|
||||
req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
|
||||
|
||||
if py := VenvPython(root); py != "" {
|
||||
if hasPywidevine(py) {
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
if err := pipInstall(py, req); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if !hasPywidevine(py) {
|
||||
return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
|
||||
}
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
|
||||
base, err := findSystemPython()
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
venvDir := filepath.Join(root, ".venv")
|
||||
fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
|
||||
if err := createVenv(base, venvDir); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
py := VenvPython(root)
|
||||
if py == "" {
|
||||
return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
|
||||
}
|
||||
if err := pipInstall(py, req); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if !hasPywidevine(py) {
|
||||
return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
|
||||
// FindPython prefers an existing install-root venv, then PATH helpers.
|
||||
func FindPython(root string) string {
|
||||
if root != "" {
|
||||
if py := VenvPython(root); py != "" {
|
||||
return py
|
||||
}
|
||||
}
|
||||
return findPython()
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
st, err := os.Stat(path)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
func hasPywidevine(py string) bool {
|
||||
cmd := exec.Command(py, "-c", "import pywidevine")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
func pipInstall(py, requirements string) error {
|
||||
if !fileExists(requirements) {
|
||||
return fmt.Errorf("wvkey: requirements missing at %s", requirements)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
|
||||
cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createVenv(basePython, venvDir string) error {
|
||||
cmd := exec.Command(basePython, "-m", "venv", venvDir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findSystemPython() (string, error) {
|
||||
var names []string
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
// Prefer the py launcher (real install) over the Store stub named "python".
|
||||
names = []string{"py", "python3", "python"}
|
||||
default:
|
||||
names = []string{"python3", "python"}
|
||||
}
|
||||
for _, name := range names {
|
||||
if name == "py" {
|
||||
// `py -3` on Windows
|
||||
if p, err := exec.LookPath("py"); err == nil {
|
||||
cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
|
||||
out, err := cmd.Output()
|
||||
if err == nil {
|
||||
exe := strings.TrimSpace(string(out))
|
||||
if fileExists(exe) {
|
||||
return exe, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if p, err := exec.LookPath(name); err == nil {
|
||||
// Skip the WindowsApps Store alias stub when it cannot run -m venv.
|
||||
if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
|
||||
cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
exe := strings.TrimSpace(string(out))
|
||||
if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
|
||||
continue
|
||||
}
|
||||
return exe, nil
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
|
||||
}
|
||||
|
|
@ -58,14 +58,21 @@ func FetchWrapAll(opt Options) ([]string, error) {
|
|||
}
|
||||
|
||||
func run(opt Options, mode string, all bool) ([]string, error) {
|
||||
py := opt.Python
|
||||
if py == "" {
|
||||
py = findPython()
|
||||
}
|
||||
py := resolvePython(opt.Python)
|
||||
script := opt.Script
|
||||
if script == "" {
|
||||
return nil, fmt.Errorf("wvkey script path required")
|
||||
}
|
||||
if !fileExists(script) {
|
||||
return nil, fmt.Errorf("wvkey script not found: %s", script)
|
||||
}
|
||||
if !fileExists(py) {
|
||||
// Bare names like "python3" are OK via LookPath inside resolvePython;
|
||||
// absolute/relative paths must exist.
|
||||
if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
|
||||
return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(opt.WVD) == "" {
|
||||
return nil, fmt.Errorf("wvkey --wvd path required")
|
||||
}
|
||||
|
|
@ -120,12 +127,30 @@ func run(opt Options, mode string, all bool) ([]string, error) {
|
|||
return out, nil
|
||||
}
|
||||
|
||||
// resolvePython uses an explicit path only when the file exists; otherwise
|
||||
// discovers a usable interpreter. Passing a missing absolute path used to make
|
||||
// exec fail with a confusing "not found in %PATH%" on Windows.
|
||||
func resolvePython(explicit string) string {
|
||||
if strings.TrimSpace(explicit) != "" {
|
||||
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
|
||||
return explicit
|
||||
}
|
||||
if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
|
||||
if p, err := exec.LookPath(explicit); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
return findPython()
|
||||
}
|
||||
|
||||
func findPython() string {
|
||||
candidates := []string{
|
||||
filepath.Join(".venv", "Scripts", "python.exe"),
|
||||
filepath.Join(".venv", "bin", "python"),
|
||||
"python3",
|
||||
"python",
|
||||
"py",
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
||||
|
|
|
|||
|
|
@ -363,6 +363,10 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
_ = h.Store.FlushHistory()
|
||||
recent, _ := h.Store.RecentEvents(25)
|
||||
sessions, _ := h.Store.ListRecentSessions(50)
|
||||
if sessions == nil {
|
||||
sessions = []db.StreamSession{}
|
||||
}
|
||||
out := map[string]any{
|
||||
"totals": map[string]any{
|
||||
"streams": len(list),
|
||||
|
|
@ -374,7 +378,8 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
|||
"viewers": viewers,
|
||||
"needs_capture": needCapture,
|
||||
},
|
||||
"recent_events": recent,
|
||||
"recent_events": recent,
|
||||
"recent_sessions": sessions,
|
||||
}
|
||||
if h.Scheduler != nil {
|
||||
out["upcoming"] = h.Scheduler.Upcoming(10)
|
||||
|
|
|
|||
|
|
@ -247,7 +247,10 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
if err := s.migrateSchedules(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateEgress()
|
||||
if err := s.migrateEgress(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateSessions()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -791,7 +794,16 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
|
|||
if mpd == "" {
|
||||
return Stream{}, fmt.Errorf("mpd required")
|
||||
}
|
||||
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
|
||||
st, err := s.GetStream(id)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
// Encrypted streams must receive usable KID:KEY lines — MPD alone leaves
|
||||
// the packager rainbow-decrypting forever.
|
||||
if st.DRMRequired && !ValidKeyPairs(key) {
|
||||
return Stream{}, fmt.Errorf("key required for DRM stream %q (got mpd but no valid KID:KEY)", st.Name)
|
||||
}
|
||||
_, 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
|
||||
|
|
|
|||
|
|
@ -408,6 +408,13 @@ GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
|||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
sessionCutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`
|
||||
DELETE FROM stream_sessions
|
||||
WHERE ended_at <> '' AND ended_at < ?`, sessionCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
|
|
|
|||
211
apps/streamd/internal/db/sessions.go
Normal file
211
apps/streamd/internal/db/sessions.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Session end reasons recorded when a run closes.
|
||||
const (
|
||||
SessionStopped = "stopped"
|
||||
SessionNREExit = "nre_exit"
|
||||
SessionOrphaned = "orphaned"
|
||||
SessionTimeout = "timeout"
|
||||
)
|
||||
|
||||
// SessionRetention is how long closed run history is kept.
|
||||
const SessionRetention = 90 * 24 * time.Hour
|
||||
|
||||
// StreamSession is one media worker run: start → stop/crash with a duration.
|
||||
type StreamSession struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
StreamTitle string `json:"stream_title,omitempty"`
|
||||
StartedAt string `json:"started_at"`
|
||||
EndedAt string `json:"ended_at,omitempty"`
|
||||
DurationS float64 `json:"duration_s"`
|
||||
EndReason string `json:"end_reason,omitempty"`
|
||||
HealthAtEnd string `json:"health_at_end,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) migrateSessions() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS stream_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
started_at TEXT NOT NULL,
|
||||
ended_at TEXT NOT NULL DEFAULT '',
|
||||
duration_s REAL NOT NULL DEFAULT 0,
|
||||
end_reason TEXT NOT NULL DEFAULT '',
|
||||
health_at_end TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_stream_started ON stream_sessions(stream_id, started_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_ended ON stream_sessions(ended_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_open ON stream_sessions(stream_id, ended_at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// OpenSession records a new run for streamID. Any previously open row for the
|
||||
// same stream is closed as orphaned (e.g. process crash without a clean stop).
|
||||
func (s *Store) OpenSession(streamID int64) (int64, error) {
|
||||
if streamID == 0 {
|
||||
return 0, fmt.Errorf("stream id required")
|
||||
}
|
||||
_ = s.CloseOpenSessions(streamID, SessionOrphaned, "stopped")
|
||||
started := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO stream_sessions(stream_id, started_at)
|
||||
VALUES(?, ?)`, streamID, started)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// CloseSession ends one open session by id. Already-closed rows are a no-op.
|
||||
func (s *Store) CloseSession(id int64, reason, healthAtEnd string) error {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
var started string
|
||||
var ended string
|
||||
err := s.DB.QueryRow(`SELECT started_at, ended_at FROM stream_sessions WHERE id=?`, id).
|
||||
Scan(&started, &ended)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ended != "" {
|
||||
return nil
|
||||
}
|
||||
endedAt := now()
|
||||
dur := durationSeconds(started, endedAt)
|
||||
if reason == "" {
|
||||
reason = SessionStopped
|
||||
}
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE stream_sessions
|
||||
SET ended_at=?, duration_s=?, end_reason=?, health_at_end=?
|
||||
WHERE id=? AND ended_at=''`,
|
||||
endedAt, dur, reason, healthAtEnd, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// CloseOpenSessions ends every open session for a stream.
|
||||
func (s *Store) CloseOpenSessions(streamID int64, reason, healthAtEnd string) error {
|
||||
if streamID == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT id FROM stream_sessions WHERE stream_id=? AND ended_at=''`, streamID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := s.CloseSession(id, reason, healthAtEnd); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListRecentSessions returns the newest closed runs across all streams.
|
||||
func (s *Store) ListRecentSessions(limit int) ([]StreamSession, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
|
||||
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
|
||||
FROM stream_sessions ss
|
||||
LEFT JOIN streams st ON st.id = ss.stream_id
|
||||
WHERE ss.ended_at <> ''
|
||||
ORDER BY ss.ended_at DESC, ss.id DESC
|
||||
LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StreamSession
|
||||
for rows.Next() {
|
||||
var ss StreamSession
|
||||
if err := rows.Scan(
|
||||
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
|
||||
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ss)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListStreamSessions returns recent closed runs for one stream.
|
||||
func (s *Store) ListStreamSessions(streamID int64, limit int) ([]StreamSession, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
|
||||
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
|
||||
FROM stream_sessions ss
|
||||
LEFT JOIN streams st ON st.id = ss.stream_id
|
||||
WHERE ss.stream_id=? AND ss.ended_at <> ''
|
||||
ORDER BY ss.ended_at DESC, ss.id DESC
|
||||
LIMIT ?`, streamID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StreamSession
|
||||
for rows.Next() {
|
||||
var ss StreamSession
|
||||
if err := rows.Scan(
|
||||
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
|
||||
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ss)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PruneSessions drops closed sessions older than SessionRetention.
|
||||
func (s *Store) PruneSessions() error {
|
||||
cutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
|
||||
_, err := s.DB.Exec(`
|
||||
DELETE FROM stream_sessions
|
||||
WHERE ended_at <> '' AND ended_at < ?`, cutoff)
|
||||
return err
|
||||
}
|
||||
|
||||
func durationSeconds(startedAt, endedAt string) float64 {
|
||||
start, err1 := time.Parse(time.RFC3339, startedAt)
|
||||
end, err2 := time.Parse(time.RFC3339, endedAt)
|
||||
if err1 != nil || err2 != nil {
|
||||
return 0
|
||||
}
|
||||
d := end.Sub(start).Seconds()
|
||||
if d < 0 {
|
||||
return 0
|
||||
}
|
||||
return d
|
||||
}
|
||||
114
apps/streamd/internal/db/sessions_test.go
Normal file
114
apps/streamd/internal/db/sessions_test.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStreamSessionsOpenCloseList(t *testing.T) {
|
||||
store, err := Open(filepath.Join(t.TempDir(), "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
st, err := store.CreateStream(CreateStream{
|
||||
Name: "bbc1", Title: "BBC One", MPD: "https://example.test/a.mpd",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id1, err := store.OpenSession(st.ID)
|
||||
if err != nil || id1 == 0 {
|
||||
t.Fatalf("OpenSession: id=%d err=%v", id1, err)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if err := store.CloseSession(id1, SessionStopped, "stopped"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Second open should orphan-close nothing (already closed) and create a new row.
|
||||
id2, err := store.OpenSession(st.ID)
|
||||
if err != nil || id2 == 0 || id2 == id1 {
|
||||
t.Fatalf("second OpenSession: id=%d (first=%d) err=%v", id2, id1, err)
|
||||
}
|
||||
if err := store.CloseSession(id2, SessionNREExit, "down"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Idempotent close.
|
||||
if err := store.CloseSession(id2, SessionStopped, "stopped"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
recent, err := store.ListRecentSessions(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recent) != 2 {
|
||||
t.Fatalf("recent len=%d want 2", len(recent))
|
||||
}
|
||||
// Newest ended first.
|
||||
if recent[0].ID != id2 || recent[0].EndReason != SessionNREExit {
|
||||
t.Fatalf("newest = %+v", recent[0])
|
||||
}
|
||||
if recent[1].ID != id1 || recent[1].EndReason != SessionStopped {
|
||||
t.Fatalf("older = %+v", recent[1])
|
||||
}
|
||||
if recent[0].StreamName != "bbc1" || recent[0].DurationS < 0 {
|
||||
t.Fatalf("row fields: %+v", recent[0])
|
||||
}
|
||||
|
||||
per, err := store.ListStreamSessions(st.ID, 5)
|
||||
if err != nil || len(per) != 2 {
|
||||
t.Fatalf("ListStreamSessions: len=%d err=%v", len(per), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionClosesOrphan(t *testing.T) {
|
||||
store, err := Open(filepath.Join(t.TempDir(), "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
st, err := store.CreateStream(CreateStream{
|
||||
Name: "rte1", MPD: "https://example.test/b.mpd",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
orphan, err := store.OpenSession(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := store.OpenSession(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next == orphan {
|
||||
t.Fatal("expected a new session id")
|
||||
}
|
||||
|
||||
var ended, reason string
|
||||
if err := store.DB.QueryRow(
|
||||
`SELECT ended_at, end_reason FROM stream_sessions WHERE id=?`, orphan,
|
||||
).Scan(&ended, &reason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ended == "" || reason != SessionOrphaned {
|
||||
t.Fatalf("orphan close: ended=%q reason=%q", ended, reason)
|
||||
}
|
||||
|
||||
_ = store.CloseSession(next, SessionStopped, "stopped")
|
||||
recent, err := store.ListRecentSessions(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recent) != 2 {
|
||||
t.Fatalf("want 2 closed sessions, got %d", len(recent))
|
||||
}
|
||||
}
|
||||
|
|
@ -55,6 +55,23 @@ func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Ma
|
|||
}
|
||||
}
|
||||
|
||||
// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
|
||||
// on every platform; non-Linux hosts skip the check.
|
||||
func (m *Manager) WarnMissingDeps() {
|
||||
if runtime.GOOS != "linux" {
|
||||
return
|
||||
}
|
||||
for _, bin := range []string{"ip", "wg"} {
|
||||
if _, err := exec.LookPath(bin); err != nil {
|
||||
m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
|
||||
"bin", bin)
|
||||
}
|
||||
}
|
||||
if _, err := m.findSocksBin(); err != nil {
|
||||
m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) logger() *slog.Logger {
|
||||
if m.Log != nil {
|
||||
return m.Log
|
||||
|
|
|
|||
|
|
@ -77,6 +77,13 @@ func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
|
|||
return err
|
||||
}
|
||||
}
|
||||
// DNS inside the netns: host /etc/resolv.conf often points at
|
||||
// 127.0.0.53 (systemd-resolved), which is unreachable from the ns.
|
||||
// ip netns exec bind-mounts /etc/netns/<name>/resolv.conf over /etc/resolv.conf.
|
||||
if err := writeNetnsResolv(nsName); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
// Loopback inside ns.
|
||||
_ = nsExec("ip", "link", "set", "lo", "up")
|
||||
|
||||
|
|
@ -221,6 +228,26 @@ func (m *Manager) teardownWireGuard(name string, _ int64) error {
|
|||
runQuiet("ip", "link", "del", wgDev) // if still in init ns
|
||||
runQuiet("ip", "netns", "del", nsName)
|
||||
_ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
|
||||
_ = os.RemoveAll(filepath.Join("/etc/netns", nsName))
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeNetnsResolv installs public resolvers for processes inside the netns
|
||||
// (microsocks, curl probe). Without this, SOCKS5 hostname connects fail with
|
||||
// error 0x01 when the host uses systemd-resolved's 127.0.0.53 stub.
|
||||
func writeNetnsResolv(nsName string) error {
|
||||
dir := filepath.Join("/etc/netns", nsName)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("netns resolv dir: %w", err)
|
||||
}
|
||||
body := "# streamd egress — public DNS (host 127.0.0.53 is unreachable in netns)\n" +
|
||||
"nameserver 1.1.1.1\n" +
|
||||
"nameserver 1.0.0.1\n" +
|
||||
"nameserver 8.8.8.8\n"
|
||||
path := filepath.Join(dir, "resolv.conf")
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
return fmt.Errorf("netns resolv.conf: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -247,16 +274,29 @@ func hostVethName(name string) string {
|
|||
|
||||
func probeEgressIP(nsName string) string {
|
||||
// Best-effort: ask a public echo over the ns default route.
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName,
|
||||
"wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip")
|
||||
out, err = cmd.Output()
|
||||
for _, url := range []string{
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://1.1.1.1/cdn-cgi/trace", // fallback parse below if needed
|
||||
} {
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", url)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
continue
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
if strings.Contains(url, "cdn-cgi/trace") {
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
if strings.HasPrefix(line, "ip=") {
|
||||
return strings.TrimPrefix(line, "ip=")
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if s != "" && !strings.Contains(s, " ") {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ type streamProc struct {
|
|||
nre *exec.Cmd
|
||||
ffmpeg *exec.Cmd
|
||||
started time.Time
|
||||
sessionID int64 // stream_sessions row opened when NRE starts
|
||||
workDir string
|
||||
wwwDir string
|
||||
tsPath string
|
||||
|
|
@ -337,17 +338,19 @@ func (m *Media) Start(id int64) error {
|
|||
}
|
||||
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
|
||||
|
||||
sessionID, _ := m.Store.OpenSession(id)
|
||||
sp := &streamProc{
|
||||
id: id,
|
||||
name: st.Name,
|
||||
nre: nreCmd,
|
||||
started: time.Now(),
|
||||
workDir: workDir,
|
||||
wwwDir: wwwDir,
|
||||
tsPath: tsPath,
|
||||
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
||||
nreLog: nreLog,
|
||||
mpdProxy: mpdProxy,
|
||||
id: id,
|
||||
name: st.Name,
|
||||
nre: nreCmd,
|
||||
started: time.Now(),
|
||||
sessionID: sessionID,
|
||||
workDir: workDir,
|
||||
wwwDir: wwwDir,
|
||||
tsPath: tsPath,
|
||||
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
||||
nreLog: nreLog,
|
||||
mpdProxy: mpdProxy,
|
||||
|
||||
variantSpecs: variantSpecs,
|
||||
outputSpecs: outputSpecs,
|
||||
|
|
@ -438,6 +441,7 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
|||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
|
||||
})
|
||||
m.closeSession(sp, db.SessionNREExit, "down")
|
||||
m.cleanupProc(sp.id)
|
||||
return
|
||||
}
|
||||
|
|
@ -589,9 +593,11 @@ func (m *Media) Stop(id int64) error {
|
|||
if st.Name != "" {
|
||||
name = st.Name
|
||||
}
|
||||
_ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped")
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
|
||||
return nil
|
||||
}
|
||||
m.closeSession(sp, db.SessionStopped, "stopped")
|
||||
m.stopAllVariants(sp)
|
||||
nrePID, ffPID := 0, 0
|
||||
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
|
||||
|
|
@ -624,6 +630,15 @@ func (m *Media) Stop(id int64) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// closeSession ends the open stream_sessions row for this process, if any.
|
||||
func (m *Media) closeSession(sp *streamProc, reason, health string) {
|
||||
if sp == nil || sp.sessionID == 0 {
|
||||
return
|
||||
}
|
||||
_ = m.Store.CloseSession(sp.sessionID, reason, health)
|
||||
sp.sessionID = 0
|
||||
}
|
||||
|
||||
func (m *Media) Restart(id int64) error {
|
||||
m.Log.Info("hard restart", "stream_id", id)
|
||||
_ = m.Stop(id)
|
||||
|
|
@ -702,6 +717,7 @@ func (m *Media) refreshHealth(id int64) {
|
|||
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
|
||||
})
|
||||
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
|
||||
m.closeSession(sp, db.SessionNREExit, "down")
|
||||
m.report(sp, "down")
|
||||
m.cleanupProc(id)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export const state = {
|
|||
agents: [],
|
||||
deps: null,
|
||||
uptimeS: 0,
|
||||
refreshedAt: 0,
|
||||
connected: false,
|
||||
lastError: "",
|
||||
};
|
||||
|
|
@ -57,6 +58,7 @@ export async function refresh(reason = "poll") {
|
|||
state.uptimeS = health.uptime_s || 0;
|
||||
if (health.deps) state.deps = health.deps;
|
||||
}
|
||||
state.refreshedAt = Date.now();
|
||||
state.lastError = "";
|
||||
} catch (err) {
|
||||
state.lastError = err.message || String(err);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,26 @@
|
|||
// Dashboard: the headline numbers, what is scheduled next, and recent events.
|
||||
|
||||
import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js";
|
||||
import {
|
||||
el, pill, fmtRelative, fmtDateTime, fmtSeconds, setText, reconcile, copyText,
|
||||
} from "../util.js";
|
||||
import { state, subscribe, refresh } from "../store.js";
|
||||
import { timeline } from "../components.js";
|
||||
|
||||
const DONATIONS = [
|
||||
{ coin: "ETH", addr: "0xa6314ce4deaa8329abba301802e3f511b3fa80a6" },
|
||||
{ coin: "LTC", addr: "ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6" },
|
||||
{ coin: "BTC", addr: "bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha" },
|
||||
];
|
||||
|
||||
export function dashboard(root) {
|
||||
const alarmTiles = el("div.tiles");
|
||||
const trafficTiles = el("div.tiles");
|
||||
const upcomingBody = el("tbody");
|
||||
const feed = el("div");
|
||||
const attention = el("div.stack");
|
||||
const uptimeBody = el("tbody");
|
||||
const sessionsBody = el("tbody");
|
||||
const supportBody = el("div.stack");
|
||||
|
||||
root.append(el("div.stack",
|
||||
el("div.tile-band",
|
||||
|
|
@ -24,6 +35,38 @@ export function dashboard(root) {
|
|||
el("div.card-head", el("h2", { text: "Needs attention" })),
|
||||
attention,
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Live uptimes" }),
|
||||
el("span.spacer"),
|
||||
el("a", { href: "#/streams", text: "All streams" }),
|
||||
),
|
||||
el("div.table-wrap",
|
||||
el("table",
|
||||
el("thead", el("tr",
|
||||
el("th", { text: "Stream" }),
|
||||
el("th", { text: "Health" }),
|
||||
el("th", { text: "Uptime" }),
|
||||
)),
|
||||
uptimeBody,
|
||||
),
|
||||
),
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head", el("h2", { text: "Recent runs" })),
|
||||
el("div.table-wrap",
|
||||
el("table",
|
||||
el("thead", el("tr",
|
||||
el("th", { text: "Stream" }),
|
||||
el("th", { text: "Started" }),
|
||||
el("th", { text: "Ended" }),
|
||||
el("th", { text: "Duration" }),
|
||||
el("th", { text: "Reason" }),
|
||||
)),
|
||||
sessionsBody,
|
||||
),
|
||||
),
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Coming up" }),
|
||||
|
|
@ -46,8 +89,36 @@ export function dashboard(root) {
|
|||
el("div.card-head", el("h2", { text: "Recent activity" })),
|
||||
feed,
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head", el("h2", { text: "Support the project" })),
|
||||
el("p.sub", {
|
||||
text: "If Streamd saves you time, donations keep development going.",
|
||||
}),
|
||||
supportBody,
|
||||
),
|
||||
));
|
||||
|
||||
supportBody.replaceChildren(...DONATIONS.map((d) =>
|
||||
el("div.row",
|
||||
el("span.pill", { text: d.coin }),
|
||||
el("code.mono", { text: d.addr }),
|
||||
el("span.spacer"),
|
||||
el("button.tiny.ghost", {
|
||||
type: "button",
|
||||
text: "Copy",
|
||||
onclick: (ev) => copyText(d.addr, d.coin + " address", ev.currentTarget),
|
||||
}),
|
||||
),
|
||||
));
|
||||
|
||||
function liveUptimeSeconds(s) {
|
||||
const health = s.health || "";
|
||||
if (health !== "ok" && health !== "starting") return null;
|
||||
const base = Number(s.uptime_s) || 0;
|
||||
const fetched = state.refreshedAt || Date.now();
|
||||
return base + Math.max(0, (Date.now() - fetched) / 1000);
|
||||
}
|
||||
|
||||
function paint() {
|
||||
const t = (state.overview && state.overview.totals) || {};
|
||||
const streams = state.streams || [];
|
||||
|
|
@ -126,6 +197,75 @@ export function dashboard(root) {
|
|||
);
|
||||
}
|
||||
|
||||
// Live uptimes: prefer enabled streams; fall back to all if none enabled.
|
||||
const uptimeRows = (() => {
|
||||
const enabled = streams.filter((s) => s.enabled);
|
||||
return (enabled.length ? enabled : streams).slice().sort((a, b) =>
|
||||
String(a.title || a.name).localeCompare(String(b.title || b.name)));
|
||||
})();
|
||||
if (!uptimeRows.length) {
|
||||
reconcile(uptimeBody, [{ id: "none" }], (x) => x.id,
|
||||
() => el("tr", el("td.empty", { colspan: "3", text: "No streams yet." })), () => {});
|
||||
} else {
|
||||
reconcile(uptimeBody, uptimeRows, (s) => s.id,
|
||||
() => el("tr",
|
||||
el("td.who"),
|
||||
el("td.health"),
|
||||
el("td.uptime.mono"),
|
||||
),
|
||||
(tr, s) => {
|
||||
const who = tr.querySelector(".who");
|
||||
who.replaceChildren(el("a", {
|
||||
href: `#/stream/${s.id}`, text: s.title || s.name,
|
||||
}));
|
||||
tr.querySelector(".health").replaceChildren(pill(s.health || "stopped"));
|
||||
const live = liveUptimeSeconds(s);
|
||||
setText(tr.querySelector(".uptime"),
|
||||
live == null ? "—" : fmtSeconds(live));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const sessions = (state.overview && state.overview.recent_sessions) || [];
|
||||
if (!sessions.length) {
|
||||
reconcile(sessionsBody, [{ id: "none" }], (x) => x.id,
|
||||
() => el("tr", el("td.empty", {
|
||||
colspan: "5",
|
||||
text: "No completed runs yet — start a stream to begin history.",
|
||||
})), () => {});
|
||||
} else {
|
||||
reconcile(sessionsBody, sessions, (s) => s.id,
|
||||
() => el("tr",
|
||||
el("td.who"),
|
||||
el("td.started"),
|
||||
el("td.ended"),
|
||||
el("td.dur.mono"),
|
||||
el("td.reason"),
|
||||
),
|
||||
(tr, s) => {
|
||||
const who = tr.querySelector(".who");
|
||||
who.replaceChildren(el("a", {
|
||||
href: `#/stream/${s.stream_id}`,
|
||||
text: s.stream_title || s.stream_name || `#${s.stream_id}`,
|
||||
}));
|
||||
const started = tr.querySelector(".started");
|
||||
started.replaceChildren(
|
||||
el("div", { text: fmtRelative(s.started_at) }),
|
||||
el("div.sub", { text: fmtDateTime(s.started_at) }),
|
||||
);
|
||||
const ended = tr.querySelector(".ended");
|
||||
ended.replaceChildren(
|
||||
el("div", { text: fmtRelative(s.ended_at) }),
|
||||
el("div.sub", { text: fmtDateTime(s.ended_at) }),
|
||||
);
|
||||
setText(tr.querySelector(".dur"), fmtSeconds(s.duration_s));
|
||||
tr.querySelector(".reason").replaceChildren(
|
||||
pill(s.end_reason || s.health_at_end || "—"),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const upcoming = (state.overview && state.overview.upcoming) || [];
|
||||
if (!upcoming.length) {
|
||||
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
|
||||
|
|
@ -160,8 +300,8 @@ export function dashboard(root) {
|
|||
const off = subscribe(paint);
|
||||
paint();
|
||||
refresh("dashboard");
|
||||
// Keep the relative times honest without a full refetch.
|
||||
const tick = setInterval(paint, 30000);
|
||||
// Keep relative times and live uptimes honest without a full refetch.
|
||||
const tick = setInterval(paint, 1000);
|
||||
return () => {
|
||||
off();
|
||||
clearInterval(tick);
|
||||
|
|
|
|||
|
|
@ -432,6 +432,7 @@ func runServe(opt ServeOptions) {
|
|||
hub := ws.NewHub(store, lg, origins)
|
||||
|
||||
eg := egress.New(dataDir, store, lg, "")
|
||||
eg.WarnMissingDeps()
|
||||
eg.StartEnabled()
|
||||
defer eg.StopAll()
|
||||
|
||||
|
|
|
|||
50
docs/releases/v0.2.2.md
Normal file
50
docs/releases/v0.2.2.md
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# Streamd v0.2.2
|
||||
|
||||
Host release after v0.2.1. Retargets the rolling **`stable`** channel.
|
||||
|
||||
## Highlights
|
||||
|
||||
### Dashboard: live uptimes + run history
|
||||
- **Live uptimes** card below Needs attention — per-stream health and ticking uptime
|
||||
- **Recent runs** — durable `stream_sessions` rows (start → stop/crash) with duration and end reason
|
||||
- `GET /api/overview` includes `recent_sessions` (newest closed runs first)
|
||||
|
||||
### Support / donations
|
||||
- Dashboard **Support the project** card with copyable ETH / LTC / BTC addresses (same as README)
|
||||
|
||||
### WireGuard egress DNS
|
||||
- On Linux Up, write `/etc/netns/streamd-<name>/resolv.conf` with public resolvers so SOCKS hostname lookups work when the host uses systemd-resolved (`127.0.0.53`)
|
||||
- Startup WARN if `ip`, `wg`, or `microsocks`/`gost` are missing from `PATH`
|
||||
- Docs updated in `docs/streamd-server-setup.md` §7 and `docs/streamd.md`
|
||||
|
||||
### Agent / Widevine / modules (included from prior work)
|
||||
- Agent lifecycle: `streamd agent start|stop|restart|status|update`
|
||||
- `job_backoff` defaults off (immediate retries)
|
||||
- Widevine auto-venv + embedded `apps/wvkey`; phonecap 90s×3 license retries
|
||||
- Module panel YAML enrich / empty-package guards; DRM credential posts require keys
|
||||
|
||||
## Known limits
|
||||
|
||||
- **BBC Live from datacenter IPs** can still get CDN **403** after SOCKS/DNS is healthy. Needs UK residential egress — out of scope for this release.
|
||||
|
||||
## Assets
|
||||
|
||||
| Asset | Platform |
|
||||
|---|---|
|
||||
| `streamd-windows-amd64.exe` | Windows x86_64 |
|
||||
| `streamd-windows-arm64.exe` | Windows ARM64 |
|
||||
| `streamd-linux-amd64` | Linux x86_64 |
|
||||
| `streamd-linux-arm64` | Linux ARM64 |
|
||||
| `streamd-darwin-amd64` | macOS Intel |
|
||||
| `streamd-darwin-arm64` | macOS Apple Silicon |
|
||||
| `proxy-android-arm64` | On-device MITM |
|
||||
| `SHA256SUMS.txt` | Checksums |
|
||||
|
||||
Built with `CGO_ENABLED=0`. Provider zips remain on separate **`modules-v*`** releases.
|
||||
|
||||
```bash
|
||||
curl -fL -o streamd \
|
||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
|
||||
chmod +x streamd
|
||||
./streamd serve update # or: stop → replace → start
|
||||
```
|
||||
|
|
@ -496,6 +496,15 @@ sudo apt-get install -y wireguard wireguard-tools iproute2 microsocks
|
|||
`CAP_SYS_ADMIN`, or run as root). A full-tunnel client conf (`AllowedIPs = 0.0.0.0/0`)
|
||||
is fine — traffic is isolated inside `streamd-<name>` netns.
|
||||
|
||||
On **Up**, streamd also writes `/etc/netns/streamd-<name>/resolv.conf` with public
|
||||
resolvers (`1.1.1.1`, `1.0.0.1`, `8.8.8.8`). Without that, SOCKS hostname lookups
|
||||
fail when the host uses systemd-resolved’s `127.0.0.53` stub (unreachable inside
|
||||
the netns). Writing under `/etc/netns/` needs the same privileges as `ip netns`.
|
||||
Teardown removes that directory with the namespace.
|
||||
|
||||
If `ip`, `wg`, or `microsocks`/`gost` are missing from `PATH`, `streamd serve`
|
||||
logs a WARN at startup so WireGuard profiles fail clearly instead of silently.
|
||||
|
||||
### Dashboard
|
||||
|
||||
1. **Settings → Egress tunnels → Add profile**
|
||||
|
|
|
|||
|
|
@ -45,8 +45,14 @@ warning.
|
|||
- Per-stream **`egress`** names a profile from **Settings → Egress** (WireGuard
|
||||
netns + local SOCKS on Linux, or a plain SOCKS URL profile). Resolve order:
|
||||
explicit `proxy` → named egress SOCKS → direct. Full-tunnel WG stays inside
|
||||
`streamd-<name>` netns so SSH/UI keep the host route. See
|
||||
`streamd-<name>` netns so SSH/UI keep the host route. On Linux Up, streamd
|
||||
writes `/etc/netns/streamd-<name>/resolv.conf` (public DNS) so SOCKS hostname
|
||||
lookups work when the host uses `127.0.0.53`. See
|
||||
[streamd-server-setup.md](streamd-server-setup.md) §7.
|
||||
- The dashboard **Live uptimes** and **Recent runs** cards use
|
||||
`stream_runtime.uptime_s` plus durable `stream_sessions` rows (opened when
|
||||
NRE starts, closed on stop / NRE exit). `GET /api/overview` includes
|
||||
`recent_sessions`.
|
||||
- **Variants** (FHD / HD / SD): FHD is the source copy at `/hls/<name>/index.m3u8`.
|
||||
Enabling HD/SD starts live ffmpeg ladders at `/hls/<name>-hd/` and
|
||||
`/hls/<name>-sd/`. The dashboard Copy button copies the absolute m3u8 URL
|
||||
|
|
@ -57,6 +63,7 @@ warning.
|
|||
| Route | Purpose |
|
||||
|---|---|
|
||||
| `GET /api/health` | liveness + uptime + `deps` paths |
|
||||
| `GET /api/overview` | dashboard totals, upcoming, recent events + sessions |
|
||||
| `GET /api/apps` | modules under the panel store (`--data/modules`), channels, rewriters |
|
||||
| `GET /api/modules` | list panel modules with yaml/package hashes + arches |
|
||||
| `GET /api/modules/:name` | metadata; `?include=yaml` returns YAML (operator+) |
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue