Compare commits
No commits in common. "main" and "v0.2.1" have entirely different histories.
38 changed files with 175 additions and 2615 deletions
|
|
@ -28,16 +28,14 @@ expire by themselves if the agent dies.
|
||||||
# terminal 1 — control plane
|
# terminal 1 — control plane
|
||||||
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||||
|
|
||||||
# terminal 2 — agent in the background (Linux / macOS / Windows)
|
# terminal 2 — agent (operator API key from streamd Settings → API keys)
|
||||||
export STREAMD_API_KEY=ndk_…
|
export STREAMD_API_KEY=ndk_…
|
||||||
./bin/streamd agent start --config apps/agent/agent.yaml
|
# or legacy: export STREAMD_TOKEN=…
|
||||||
./bin/streamd agent status --config apps/agent/agent.yaml
|
./bin/streamd agent run --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
|
```bash
|
||||||
|
./bin/streamd agent status
|
||||||
./bin/streamd agent devices
|
./bin/streamd agent devices
|
||||||
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
||||||
./bin/streamd agent cancel --job 3
|
./bin/streamd agent cancel --job 3
|
||||||
|
|
@ -54,18 +52,12 @@ whichever module a stream names and contains no provider logic.
|
||||||
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
|
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
|
||||||
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
|
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
|
||||||
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
|
`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
|
Create the key in the streamd dashboard (role **operator**). The legacy shared
|
||||||
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
||||||
|
|
||||||
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
|
`wvd` must be set or key fetches fail.
|
||||||
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
|
## Build
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,18 +19,8 @@ sync_modules: true
|
||||||
# modules_dir: # optional; default <data_dir>/modules
|
# modules_dir: # optional; default <data_dir>/modules
|
||||||
# modules_sync_interval_sec: 300
|
# modules_sync_interval_sec: 300
|
||||||
# modules_prune: false # delete local modules absent from the panel
|
# modules_prune: false # delete local modules absent from the panel
|
||||||
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
|
# Required for key fetch. Relative paths resolve from the repo root
|
||||||
# Set true only when several agents share the same streams.
|
# (DRM-Decryption/), not from C:\Users\admin\Programming\.
|
||||||
# job_backoff: false
|
wvd:
|
||||||
# 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
|
# user_agent: "" # optional license-request User-Agent
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
|
||||||
|
|
@ -22,8 +21,6 @@ import (
|
||||||
"streamd/apps/agent/internal/worker"
|
"streamd/apps/agent/internal/worker"
|
||||||
"streamd/apps/agent/internal/wsclient"
|
"streamd/apps/agent/internal/wsclient"
|
||||||
"streamd/modhost"
|
"streamd/modhost"
|
||||||
"streamd/repo"
|
|
||||||
"streamd/wvkey"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
||||||
|
|
@ -39,14 +36,6 @@ func Run(args []string) error {
|
||||||
switch sub {
|
switch sub {
|
||||||
case "run":
|
case "run":
|
||||||
runCmd(sub, rest)
|
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":
|
case "status":
|
||||||
statusCmd(sub, rest)
|
statusCmd(sub, rest)
|
||||||
case "devices":
|
case "devices":
|
||||||
|
|
@ -69,13 +58,8 @@ func Usage() {
|
||||||
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
agent start [--config agent.yaml] # background (pid + log)
|
agent run [--config apps/agent/agent.yaml]
|
||||||
agent stop [--config ...]
|
agent status [--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 devices [--config ...]
|
||||||
agent enqueue --stream NAME [--reason manual] [--config ...]
|
agent enqueue --stream NAME [--reason manual] [--config ...]
|
||||||
agent cancel --job ID [--config ...]
|
agent cancel --job ID [--config ...]
|
||||||
|
|
@ -84,9 +68,6 @@ Polls streamd for enabled streams that are down / missing credentials,
|
||||||
enqueues jobs, claims a free phone that already has the app, captures
|
enqueues jobs, claims a free phone that already has the app, captures
|
||||||
via MITM, POSTs credentials, then force-stops the app.
|
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.
|
Does not install apps. Does not run NRE/ffmpeg.
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|
@ -136,18 +117,6 @@ func runCmd(sub string, args []string) {
|
||||||
"create an operator API key in the streamd dashboard", me.Role)
|
"create an operator API key in the streamd dashboard", me.Role)
|
||||||
}
|
}
|
||||||
log.Printf("authenticated to streamd as %q (role %s)", me.Name, 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)
|
q := openQueue(cfg)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
|
|
@ -156,16 +125,6 @@ func runCmd(sub string, args []string) {
|
||||||
} else if n > 0 {
|
} else if n > 0 {
|
||||||
log.Printf("re-queued %d stuck running job(s) from previous run", n)
|
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)
|
pool := device.New("", cfg.Devices)
|
||||||
stop := make(chan struct{})
|
stop := make(chan struct{})
|
||||||
|
|
@ -246,7 +205,6 @@ func runCmd(sub string, args []string) {
|
||||||
Python: cfg.Python,
|
Python: cfg.Python,
|
||||||
WVD: cfg.WVD,
|
WVD: cfg.WVD,
|
||||||
UserAgent: cfg.UserAgent,
|
UserAgent: cfg.UserAgent,
|
||||||
JobBackoff: cfg.JobBackoffEnabled(),
|
|
||||||
Log: log.Default(),
|
Log: log.Default(),
|
||||||
}
|
}
|
||||||
go w.Loop(stop)
|
go w.Loop(stop)
|
||||||
|
|
@ -267,7 +225,6 @@ func runCmd(sub string, args []string) {
|
||||||
|
|
||||||
func statusCmd(sub string, args []string) {
|
func statusCmd(sub string, args []string) {
|
||||||
cfg, _ := loadCfg(sub, args)
|
cfg, _ := loadCfg(sub, args)
|
||||||
printDaemonStatus(cfg)
|
|
||||||
q := openQueue(cfg)
|
q := openQueue(cfg)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
jobs, err := q.ListRecent(40)
|
jobs, err := q.ListRecent(40)
|
||||||
|
|
|
||||||
|
|
@ -1,177 +0,0 @@
|
||||||
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")
|
|
||||||
}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
//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)
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
//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)
|
|
||||||
}
|
|
||||||
|
|
@ -1,282 +0,0 @@
|
||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
//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
|
|
||||||
}
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
//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,16 +36,6 @@ type Config struct {
|
||||||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
// an on-demand stream, or a scheduled event about to start — jump ahead
|
||||||
// of routine refreshes in the queue.
|
// of routine refreshes in the queue.
|
||||||
OnDemandPriority *bool `yaml:"ondemand_priority"`
|
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.
|
// PushedCapturesArePriority reports whether pushed captures jump the queue.
|
||||||
|
|
@ -54,12 +44,6 @@ func (c Config) PushedCapturesArePriority() bool {
|
||||||
return c.OnDemandPriority == nil || *c.OnDemandPriority
|
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 {
|
func (c Config) PollInterval() time.Duration {
|
||||||
if c.PollIntervalSec <= 0 {
|
if c.PollIntervalSec <= 0 {
|
||||||
return 30 * time.Second
|
return 30 * time.Second
|
||||||
|
|
@ -141,9 +125,6 @@ func applyDefaults(cfg Config, root string) Config {
|
||||||
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
||||||
cfg.WVD = filepath.Join(root, 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 == "" {
|
if cfg.ModulesDir == "" {
|
||||||
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
||||||
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
||||||
|
|
@ -152,25 +133,6 @@ func applyDefaults(cfg Config, root string) Config {
|
||||||
if cfg.ModulesSyncIntervalSec <= 0 {
|
if cfg.ModulesSyncIntervalSec <= 0 {
|
||||||
cfg.ModulesSyncIntervalSec = 300
|
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
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -232,18 +232,17 @@ func (s *Store) MarkOK(id int64) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarkFailed increments attempts. Re-queues unless maxed out.
|
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
|
||||||
// waitingDevice=true keeps status queued without burning an attempt.
|
// waitingDevice=true keeps status queued without burning an attempt.
|
||||||
// backoff is how long to wait before the job is runnable again (0 = immediate).
|
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
|
||||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
|
|
||||||
j, err := s.Get(id)
|
j, err := s.Get(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if waitingDevice {
|
if waitingDevice {
|
||||||
_, err = s.DB.Exec(`
|
_, err = s.DB.Exec(`
|
||||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
|
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
|
||||||
msg, now(), id)
|
msg, id)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
attempts := j.Attempts + 1
|
attempts := j.Attempts + 1
|
||||||
|
|
@ -253,8 +252,9 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
|
||||||
attempts, msg, now(), id)
|
attempts, msg, now(), id)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if backoff < 0 {
|
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||||
backoff = 0
|
if backoff > 15*time.Minute {
|
||||||
|
backoff = 15 * time.Minute
|
||||||
}
|
}
|
||||||
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
||||||
_, err = s.DB.Exec(`
|
_, err = s.DB.Exec(`
|
||||||
|
|
@ -263,29 +263,6 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
|
||||||
return err
|
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 {
|
func min(a, b int) int {
|
||||||
if a < b {
|
if a < b {
|
||||||
return a
|
return a
|
||||||
|
|
|
||||||
|
|
@ -27,9 +27,6 @@ type Worker struct {
|
||||||
Python string
|
Python string
|
||||||
WVD string
|
WVD string
|
||||||
UserAgent string
|
UserAgent string
|
||||||
// JobBackoff enables exponential delays between failed capture attempts.
|
|
||||||
// When false (default), failed jobs are re-queued immediately.
|
|
||||||
JobBackoff bool
|
|
||||||
Log *log.Logger
|
Log *log.Logger
|
||||||
|
|
||||||
lastDelayLog time.Time
|
lastDelayLog time.Time
|
||||||
|
|
@ -70,18 +67,13 @@ func (w *Worker) tick() {
|
||||||
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
||||||
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
||||||
w.logf("job=%d waiting: %v", job.ID, err)
|
w.logf("job=%d waiting: %v", job.ID, err)
|
||||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
|
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.logf("job=%d failed: %v", job.ID, err)
|
w.logf("job=%d failed: %v", job.ID, err)
|
||||||
w.event(job, client.EventCaptureFailed, err.Error(),
|
w.event(job, client.EventCaptureFailed, err.Error(),
|
||||||
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
||||||
backoff := time.Duration(0)
|
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
|
||||||
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
|
return
|
||||||
}
|
}
|
||||||
_ = w.Queue.MarkOK(job.ID)
|
_ = w.Queue.MarkOK(job.ID)
|
||||||
|
|
@ -127,8 +119,8 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
_ = w.Queue.SetDevice(job.ID, serial)
|
_ = w.Queue.SetDevice(job.ID, serial)
|
||||||
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
||||||
|
|
||||||
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
|
// Short TTL; /ws/agent heartbeats renew while this process is alive.
|
||||||
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
|
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
|
||||||
return fmt.Errorf("streamd claim: %w", err)
|
return fmt.Errorf("streamd claim: %w", err)
|
||||||
}
|
}
|
||||||
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
||||||
|
|
@ -148,19 +140,6 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
return err
|
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{
|
cred := client.Credentials{
|
||||||
MPD: res.MPD,
|
MPD: res.MPD,
|
||||||
Key: res.Key,
|
Key: res.Key,
|
||||||
|
|
@ -171,25 +150,15 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
||||||
return fmt.Errorf("post credentials: %w", err)
|
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.
|
// Report what was captured, never the key itself.
|
||||||
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
||||||
"device": serial,
|
"device": serial,
|
||||||
"has_key": strings.TrimSpace(res.Key) != "",
|
"has_key": strings.TrimSpace(res.Key) != "",
|
||||||
"key_valid": hasKey,
|
"key_valid": poller.ValidKeyPair(res.Key),
|
||||||
})
|
})
|
||||||
return nil
|
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
|
// event posts a stream event to streamd. A timeline entry is never worth
|
||||||
// failing a capture over, so errors are logged and dropped.
|
// failing a capture over, so errors are logged and dropped.
|
||||||
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,367 +0,0 @@
|
||||||
#!/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,9 +105,5 @@ func Load(root, name string) (Module, string, Describe, error) {
|
||||||
if d.Name == "" {
|
if d.Name == "" {
|
||||||
d.Name = m.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
|
return m, bin, d, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
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,21 +206,17 @@ func Run(opt Options) (res Result, err error) {
|
||||||
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
||||||
useTProxy = true
|
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 {
|
if useTProxy {
|
||||||
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
||||||
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
||||||
proxy.ClearHTTPProxy(c)
|
proxy.ClearHTTPProxy(c)
|
||||||
remoteDir := "/data/local/tmp/capture/" + pkgName
|
remoteDir := "/data/local/tmp/capture/" + a.Package()
|
||||||
var mitmHosts []string
|
var mitmHosts []string
|
||||||
if mh, ok := a.(app.MitmHostList); ok {
|
if mh, ok := a.(app.MitmHostList); ok {
|
||||||
mitmHosts = mh.MitmHosts()
|
mitmHosts = mh.MitmHosts()
|
||||||
}
|
}
|
||||||
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
|
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||||
return res, fmt.Errorf("transparent MITM start: %w", err)
|
return res, fmt.Errorf("transparent MITM start: %w", err)
|
||||||
}
|
}
|
||||||
defer proxy.StopTransparent(c)
|
defer proxy.StopTransparent(c)
|
||||||
|
|
@ -242,6 +238,17 @@ func Run(opt Options) (res Result, err error) {
|
||||||
proxy.ReinjectCA(c, caHash)
|
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)
|
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
|
||||||
serialTag := c.Serial
|
serialTag := c.Serial
|
||||||
if serialTag == "" {
|
if serialTag == "" {
|
||||||
|
|
@ -249,86 +256,57 @@ func Run(opt Options) (res Result, err error) {
|
||||||
}
|
}
|
||||||
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
|
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
|
||||||
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
|
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{})
|
stop := make(chan struct{})
|
||||||
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
||||||
defer close(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
|
need := hints.Require
|
||||||
if len(need) == 0 {
|
if len(need) == 0 {
|
||||||
need = []string{"manifest"}
|
need = []string{"manifest"}
|
||||||
}
|
}
|
||||||
|
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
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.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
|
|
||||||
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
|
|
||||||
fmt.Println(" watch:", localLog)
|
fmt.Println(" watch:", localLog)
|
||||||
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
|
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
lastErr = err
|
return res, err
|
||||||
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
|
}
|
||||||
c.ForceStop(a.Package())
|
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
|
||||||
continue
|
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||||
|
if keyMode == "" || keyMode == "auto" {
|
||||||
|
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||||
}
|
}
|
||||||
capData = cap
|
|
||||||
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
|
|
||||||
|
|
||||||
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
||||||
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
||||||
if needsKeys {
|
// Skip for clear/MPD-only apps (KeyMode none).
|
||||||
enrichWidevinePSSH(capData)
|
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"))
|
mpdURL := strings.TrimSpace(capData.Get("mpd"))
|
||||||
|
// Console: always surface the MPD we will use (BBC clear streams only need this).
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
fmt.Println("========== MPD ==========")
|
fmt.Println("========== MPD ==========")
|
||||||
if mpdURL != "" {
|
if mpdURL != "" {
|
||||||
|
|
@ -358,52 +336,27 @@ func Run(opt Options) (res Result, err error) {
|
||||||
fmt.Println(" ", label+":", trim(v, 120))
|
fmt.Println(" ", label+":", trim(v, 120))
|
||||||
}
|
}
|
||||||
|
|
||||||
if !needsKeys {
|
key := ""
|
||||||
|
if keyMode == "none" || keyMode == "clear" {
|
||||||
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
||||||
lastErr = nil
|
} else {
|
||||||
break
|
var kerr error
|
||||||
}
|
key, kerr = fetchKey(opt, root, capData, licenseURL)
|
||||||
|
|
||||||
k, kerr := fetchKey(opt, root, capData, licenseURL)
|
|
||||||
if kerr != nil {
|
if kerr != nil {
|
||||||
lastErr = kerr
|
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
|
||||||
// Missing --wvd on a manual grab-all can soft-save MPD-only; agents
|
// unless the app requires keys (e.g. c4).
|
||||||
// always pass WVD so this path is for interactive capture only.
|
|
||||||
softOK := strings.Contains(kerr.Error(), "requires --wvd")
|
softOK := strings.Contains(kerr.Error(), "requires --wvd")
|
||||||
if softOK {
|
if softOK {
|
||||||
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
|
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
|
||||||
c.ForceStop(a.Package())
|
return res, kerr
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
|
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
|
||||||
key = ""
|
} else {
|
||||||
lastErr = nil
|
return res, kerr
|
||||||
break
|
|
||||||
}
|
}
|
||||||
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
|
} else {
|
||||||
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", " | "))
|
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{
|
sess := session.Session{
|
||||||
|
|
@ -431,62 +384,6 @@ func Run(opt Options) (res Result, err error) {
|
||||||
return res, nil
|
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).
|
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
|
||||||
func ClearProxyLater(c *adb.Client) {
|
func ClearProxyLater(c *adb.Client) {
|
||||||
proxy.ClearHTTPProxy(c)
|
proxy.ClearHTTPProxy(c)
|
||||||
|
|
@ -517,18 +414,16 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
||||||
if strings.TrimSpace(opt.WVD) == "" {
|
if strings.TrimSpace(opt.WVD) == "" {
|
||||||
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
||||||
}
|
}
|
||||||
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
|
py := opt.Python
|
||||||
rt, err := wvkey.EnsureRuntime(root)
|
if py == "" {
|
||||||
if err != nil {
|
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
|
||||||
return "", err
|
if _, err := os.Stat(py); err != nil {
|
||||||
|
py = filepath.Join(root, ".venv", "bin", "python")
|
||||||
}
|
}
|
||||||
py := rt.Python
|
|
||||||
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
|
|
||||||
py = p
|
|
||||||
}
|
}
|
||||||
wopt := wvkey.Options{
|
wopt := wvkey.Options{
|
||||||
Python: py,
|
Python: py,
|
||||||
Script: rt.Script,
|
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
|
||||||
WVD: opt.WVD,
|
WVD: opt.WVD,
|
||||||
PSSH: cap.Get("pssh"),
|
PSSH: cap.Get("pssh"),
|
||||||
Auth: cap.Get("auth"),
|
Auth: cap.Get("auth"),
|
||||||
|
|
@ -570,11 +465,6 @@ 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 {
|
func first(vals ...string) string {
|
||||||
for _, v := range vals {
|
for _, v := range vals {
|
||||||
if strings.TrimSpace(v) != "" {
|
if strings.TrimSpace(v) != "" {
|
||||||
|
|
|
||||||
|
|
@ -481,14 +481,10 @@ const (
|
||||||
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
||||||
// mode otherwise only MITMs open.live.bbc.co.uk.
|
// mode otherwise only MITMs open.live.bbc.co.uk.
|
||||||
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
|
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 == "" {
|
if port == "" {
|
||||||
port = "8080"
|
port = "8080"
|
||||||
}
|
}
|
||||||
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
|
if remoteDir == "" {
|
||||||
remoteDir = RemoteCaptureRoot + "/" + pkg
|
remoteDir = RemoteCaptureRoot + "/" + pkg
|
||||||
}
|
}
|
||||||
stopProxy(c)
|
stopProxy(c)
|
||||||
|
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
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,21 +58,14 @@ func FetchWrapAll(opt Options) ([]string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func run(opt Options, mode string, all bool) ([]string, error) {
|
func run(opt Options, mode string, all bool) ([]string, error) {
|
||||||
py := resolvePython(opt.Python)
|
py := opt.Python
|
||||||
|
if py == "" {
|
||||||
|
py = findPython()
|
||||||
|
}
|
||||||
script := opt.Script
|
script := opt.Script
|
||||||
if script == "" {
|
if script == "" {
|
||||||
return nil, fmt.Errorf("wvkey script path required")
|
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) == "" {
|
if strings.TrimSpace(opt.WVD) == "" {
|
||||||
return nil, fmt.Errorf("wvkey --wvd path required")
|
return nil, fmt.Errorf("wvkey --wvd path required")
|
||||||
}
|
}
|
||||||
|
|
@ -127,30 +120,12 @@ func run(opt Options, mode string, all bool) ([]string, error) {
|
||||||
return out, nil
|
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 {
|
func findPython() string {
|
||||||
candidates := []string{
|
candidates := []string{
|
||||||
filepath.Join(".venv", "Scripts", "python.exe"),
|
filepath.Join(".venv", "Scripts", "python.exe"),
|
||||||
filepath.Join(".venv", "bin", "python"),
|
filepath.Join(".venv", "bin", "python"),
|
||||||
"python3",
|
"python3",
|
||||||
"python",
|
"python",
|
||||||
"py",
|
|
||||||
}
|
}
|
||||||
for _, c := range candidates {
|
for _, c := range candidates {
|
||||||
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
||||||
|
|
|
||||||
|
|
@ -363,10 +363,6 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
_ = h.Store.FlushHistory()
|
_ = h.Store.FlushHistory()
|
||||||
recent, _ := h.Store.RecentEvents(25)
|
recent, _ := h.Store.RecentEvents(25)
|
||||||
sessions, _ := h.Store.ListRecentSessions(50)
|
|
||||||
if sessions == nil {
|
|
||||||
sessions = []db.StreamSession{}
|
|
||||||
}
|
|
||||||
out := map[string]any{
|
out := map[string]any{
|
||||||
"totals": map[string]any{
|
"totals": map[string]any{
|
||||||
"streams": len(list),
|
"streams": len(list),
|
||||||
|
|
@ -379,7 +375,6 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
||||||
"needs_capture": needCapture,
|
"needs_capture": needCapture,
|
||||||
},
|
},
|
||||||
"recent_events": recent,
|
"recent_events": recent,
|
||||||
"recent_sessions": sessions,
|
|
||||||
}
|
}
|
||||||
if h.Scheduler != nil {
|
if h.Scheduler != nil {
|
||||||
out["upcoming"] = h.Scheduler.Upcoming(10)
|
out["upcoming"] = h.Scheduler.Upcoming(10)
|
||||||
|
|
|
||||||
|
|
@ -247,10 +247,7 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
||||||
if err := s.migrateSchedules(); err != nil {
|
if err := s.migrateSchedules(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := s.migrateEgress(); err != nil {
|
return s.migrateEgress()
|
||||||
return err
|
|
||||||
}
|
|
||||||
return s.migrateSessions()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func now() string {
|
func now() string {
|
||||||
|
|
@ -794,16 +791,7 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
|
||||||
if mpd == "" {
|
if mpd == "" {
|
||||||
return Stream{}, fmt.Errorf("mpd required")
|
return Stream{}, fmt.Errorf("mpd required")
|
||||||
}
|
}
|
||||||
st, err := s.GetStream(id)
|
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE 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)
|
mpd, key, now(), id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Stream{}, err
|
return Stream{}, err
|
||||||
|
|
|
||||||
|
|
@ -408,13 +408,6 @@ GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
||||||
_ = tx.Rollback()
|
_ = tx.Rollback()
|
||||||
return err
|
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()
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,211 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
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,23 +55,6 @@ 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 {
|
func (m *Manager) logger() *slog.Logger {
|
||||||
if m.Log != nil {
|
if m.Log != nil {
|
||||||
return m.Log
|
return m.Log
|
||||||
|
|
|
||||||
|
|
@ -77,13 +77,6 @@ func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
|
||||||
return err
|
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.
|
// Loopback inside ns.
|
||||||
_ = nsExec("ip", "link", "set", "lo", "up")
|
_ = nsExec("ip", "link", "set", "lo", "up")
|
||||||
|
|
||||||
|
|
@ -228,26 +221,6 @@ func (m *Manager) teardownWireGuard(name string, _ int64) error {
|
||||||
runQuiet("ip", "link", "del", wgDev) // if still in init ns
|
runQuiet("ip", "link", "del", wgDev) // if still in init ns
|
||||||
runQuiet("ip", "netns", "del", nsName)
|
runQuiet("ip", "netns", "del", nsName)
|
||||||
_ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
|
_ = 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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -274,29 +247,16 @@ func hostVethName(name string) string {
|
||||||
|
|
||||||
func probeEgressIP(nsName string) string {
|
func probeEgressIP(nsName string) string {
|
||||||
// Best-effort: ask a public echo over the ns default route.
|
// Best-effort: ask a public echo over the ns default route.
|
||||||
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,
|
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||||
"curl", "-4", "-fsS", "--max-time", "5", url)
|
"curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip")
|
||||||
out, err := cmd.Output()
|
out, err := cmd.Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
cmd = exec.Command("ip", "netns", "exec", nsName,
|
||||||
}
|
"wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip")
|
||||||
s := strings.TrimSpace(string(out))
|
out, err = cmd.Output()
|
||||||
if strings.Contains(url, "cdn-cgi/trace") {
|
if err != nil {
|
||||||
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 ""
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -64,34 +64,6 @@ func OpenWithBanner(path string, maxBytes int64, generations int, what string) (
|
||||||
return w, nil
|
return w, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenCmdLog prepares a rotating append log and returns the live *os.File for
|
|
||||||
// exec.Cmd Stdout/Stderr. Go only inherits a real FD for *os.File; any other
|
|
||||||
// io.Writer becomes a pipe, and N_m3u8DL-RE's Spectre progress UI crashes on
|
|
||||||
// pipe-backed consoles (ArgumentException in LiveRenderable.RemoveRange).
|
|
||||||
//
|
|
||||||
// The caller owns the file and must Close it. Mid-run size rotation is skipped
|
|
||||||
// (rotation still happens at open when the prior file is already over the cap).
|
|
||||||
func OpenCmdLog(path string, maxBytes int64, generations int, what string) (*os.File, error) {
|
|
||||||
w, err := OpenWithBanner(path, maxBytes, generations, what)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return w.DetachFile()
|
|
||||||
}
|
|
||||||
|
|
||||||
// DetachFile transfers ownership of the underlying *os.File to the caller.
|
|
||||||
// The Writer becomes inert; do not Write or Close it afterward.
|
|
||||||
func (w *Writer) DetachFile() (*os.File, error) {
|
|
||||||
w.mu.Lock()
|
|
||||||
defer w.mu.Unlock()
|
|
||||||
if w.f == nil {
|
|
||||||
return nil, os.ErrClosed
|
|
||||||
}
|
|
||||||
f := w.f
|
|
||||||
w.f = nil
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *Writer) reopen() error {
|
func (w *Writer) reopen() error {
|
||||||
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
@ -61,13 +62,11 @@ type streamProc struct {
|
||||||
nre *exec.Cmd
|
nre *exec.Cmd
|
||||||
ffmpeg *exec.Cmd
|
ffmpeg *exec.Cmd
|
||||||
started time.Time
|
started time.Time
|
||||||
sessionID int64 // stream_sessions row opened when NRE starts
|
|
||||||
workDir string
|
workDir string
|
||||||
wwwDir string
|
wwwDir string
|
||||||
tsPath string
|
tsPath string
|
||||||
hlsIndex string
|
hlsIndex string
|
||||||
nreLogFile *os.File // per-stream NRE log (banner + append)
|
nreLog *logfile.Writer
|
||||||
nrePTY io.Closer // Linux PTY master; nil on Windows / fallback
|
|
||||||
ffOutLog *logfile.Writer
|
ffOutLog *logfile.Writer
|
||||||
ffErrLog *logfile.Writer
|
ffErrLog *logfile.Writer
|
||||||
stopping bool
|
stopping bool
|
||||||
|
|
@ -258,10 +257,7 @@ func (m *Media) Start(id int64) error {
|
||||||
"--tmp-dir", nreTmp,
|
"--tmp-dir", nreTmp,
|
||||||
"--no-ansi-color",
|
"--no-ansi-color",
|
||||||
"--log-level", "ERROR",
|
"--log-level", "ERROR",
|
||||||
// Drop every subtitle track. Live pipe-mux to TS does not need them, and
|
"-ss", "0",
|
||||||
// an extra Spectre progress row makes redirected-console crashes more
|
|
||||||
// likely (NRE forces ANSI UI when stdout is a log file).
|
|
||||||
"-ds", "for=all",
|
|
||||||
}
|
}
|
||||||
if hasKeys {
|
if hasKeys {
|
||||||
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
|
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
|
||||||
|
|
@ -298,24 +294,23 @@ func (m *Media) Start(id int64) error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under
|
// A rotating log opened with a start banner, rather than truncated. The
|
||||||
// a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI
|
// previous run's output is exactly what you need when working out why
|
||||||
// with WindowWidth 0 and crash ProgressRefreshThread.
|
// this run is happening.
|
||||||
nreLogFile, err := logfile.OpenCmdLog(
|
nreLog, err := logfile.OpenWithBanner(
|
||||||
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
|
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
|
||||||
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
|
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
nreCmd := exec.Command(m.NRE, nreArgs...)
|
nreCmd := exec.Command(m.NRE, nreArgs...)
|
||||||
|
nreCmd.Stdout = nreLog
|
||||||
|
nreCmd.Stderr = nreLog
|
||||||
hideWindow(nreCmd)
|
hideWindow(nreCmd)
|
||||||
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
|
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
|
||||||
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
|
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
|
||||||
// dirs and best-effort copy beside NRE.
|
// dirs and best-effort copy beside NRE.
|
||||||
nreEnv := os.Environ()
|
nreEnv := os.Environ()
|
||||||
nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120")
|
|
||||||
nreEnv = setEnvDefault(nreEnv, "LINES", "40")
|
|
||||||
nreEnv = setEnvDefault(nreEnv, "TERM", "xterm")
|
|
||||||
pathPrepend := []string{}
|
pathPrepend := []string{}
|
||||||
if m.MP4Decrypt != "" {
|
if m.MP4Decrypt != "" {
|
||||||
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
|
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
|
||||||
|
|
@ -332,36 +327,26 @@ func (m *Media) Start(id int64) error {
|
||||||
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
|
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
|
||||||
}
|
}
|
||||||
nreCmd.Env = nreEnv
|
nreCmd.Env = nreEnv
|
||||||
nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile)
|
if err := nreCmd.Start(); err != nil {
|
||||||
if err != nil {
|
_ = nreLog.Close()
|
||||||
if keepLogFD {
|
|
||||||
_ = nreLogFile.Close()
|
|
||||||
}
|
|
||||||
if mpdProxy != nil {
|
if mpdProxy != nil {
|
||||||
mpdProxy.Close()
|
mpdProxy.Close()
|
||||||
}
|
}
|
||||||
m.fail(id, st.Name, err.Error())
|
m.fail(id, st.Name, err.Error())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ownedLog := nreLogFile
|
|
||||||
if !keepLogFD {
|
|
||||||
ownedLog = nil
|
|
||||||
}
|
|
||||||
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
|
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
|
||||||
|
|
||||||
sessionID, _ := m.Store.OpenSession(id)
|
|
||||||
sp := &streamProc{
|
sp := &streamProc{
|
||||||
id: id,
|
id: id,
|
||||||
name: st.Name,
|
name: st.Name,
|
||||||
nre: nreCmd,
|
nre: nreCmd,
|
||||||
started: time.Now(),
|
started: time.Now(),
|
||||||
sessionID: sessionID,
|
|
||||||
workDir: workDir,
|
workDir: workDir,
|
||||||
wwwDir: wwwDir,
|
wwwDir: wwwDir,
|
||||||
tsPath: tsPath,
|
tsPath: tsPath,
|
||||||
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
||||||
nreLogFile: ownedLog,
|
nreLog: nreLog,
|
||||||
nrePTY: nrePTY,
|
|
||||||
mpdProxy: mpdProxy,
|
mpdProxy: mpdProxy,
|
||||||
|
|
||||||
variantSpecs: variantSpecs,
|
variantSpecs: variantSpecs,
|
||||||
|
|
@ -447,13 +432,12 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
||||||
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
|
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
|
||||||
Health: "down",
|
Health: "down",
|
||||||
PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
PlayPath: "/hls/" + sp.name + "/index.m3u8",
|
||||||
LastError: "NRE exited before TS was ready — see data/logs/" + sp.name + "-nre.log",
|
LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
|
||||||
})
|
})
|
||||||
m.Store.AddEvent(db.StreamEvent{
|
m.Store.AddEvent(db.StreamEvent{
|
||||||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||||
Message: "downloader exited before any media arrived — see data/logs/" + sp.name + "-nre.log",
|
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
|
||||||
})
|
})
|
||||||
m.closeSession(sp, db.SessionNREExit, "down")
|
|
||||||
m.cleanupProc(sp.id)
|
m.cleanupProc(sp.id)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -605,11 +589,9 @@ func (m *Media) Stop(id int64) error {
|
||||||
if st.Name != "" {
|
if st.Name != "" {
|
||||||
name = 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"})
|
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
m.closeSession(sp, db.SessionStopped, "stopped")
|
|
||||||
m.stopAllVariants(sp)
|
m.stopAllVariants(sp)
|
||||||
nrePID, ffPID := 0, 0
|
nrePID, ffPID := 0, 0
|
||||||
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
|
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
|
||||||
|
|
@ -642,15 +624,6 @@ func (m *Media) Stop(id int64) error {
|
||||||
return nil
|
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 {
|
func (m *Media) Restart(id int64) error {
|
||||||
m.Log.Info("hard restart", "stream_id", id)
|
m.Log.Info("hard restart", "stream_id", id)
|
||||||
_ = m.Stop(id)
|
_ = m.Stop(id)
|
||||||
|
|
@ -670,15 +643,7 @@ func (m *Media) cleanupProc(id int64) {
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if sp.nrePTY != nil {
|
for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
|
||||||
_ = sp.nrePTY.Close()
|
|
||||||
sp.nrePTY = nil
|
|
||||||
}
|
|
||||||
if sp.nreLogFile != nil {
|
|
||||||
_ = sp.nreLogFile.Close()
|
|
||||||
sp.nreLogFile = nil
|
|
||||||
}
|
|
||||||
for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} {
|
|
||||||
if w != nil {
|
if w != nil {
|
||||||
_ = w.Close()
|
_ = w.Close()
|
||||||
}
|
}
|
||||||
|
|
@ -730,14 +695,13 @@ func (m *Media) refreshHealth(id int64) {
|
||||||
if nreDead {
|
if nreDead {
|
||||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
_ = m.Store.SetRuntime(id, db.RuntimePatch{
|
||||||
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
|
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
|
||||||
LastError: "NRE process exited — see data/logs/" + sp.name + "-nre.log",
|
LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
|
||||||
})
|
})
|
||||||
m.Store.AddEvent(db.StreamEvent{
|
m.Store.AddEvent(db.StreamEvent{
|
||||||
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
|
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||||
Message: fmt.Sprintf("downloader exited after %.0fs — see data/logs/%s-nre.log", uptime, sp.name),
|
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.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
|
||||||
m.closeSession(sp, db.SessionNREExit, "down")
|
|
||||||
m.report(sp, "down")
|
m.report(sp, "down")
|
||||||
m.cleanupProc(id)
|
m.cleanupProc(id)
|
||||||
return
|
return
|
||||||
|
|
@ -944,7 +908,11 @@ func killProcess(cmd *exec.Cmd) error {
|
||||||
if cmd == nil || cmd.Process == nil {
|
if cmd == nil || cmd.Process == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return killProcessTree(cmd)
|
pid := cmd.Process.Pid
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
|
||||||
|
}
|
||||||
|
return cmd.Process.Kill()
|
||||||
}
|
}
|
||||||
|
|
||||||
func prependPathEnv(env []string, prefix string) []string {
|
func prependPathEnv(env []string, prefix string) []string {
|
||||||
|
|
@ -967,20 +935,6 @@ func prependPathEnv(env []string, prefix string) []string {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// setEnvDefault sets KEY=value when KEY is missing or empty in env.
|
|
||||||
func setEnvDefault(env []string, key, value string) []string {
|
|
||||||
prefix := key + "="
|
|
||||||
for i, e := range env {
|
|
||||||
if strings.HasPrefix(e, prefix) {
|
|
||||||
if strings.TrimSpace(e[len(prefix):]) == "" {
|
|
||||||
env[i] = prefix + value
|
|
||||||
}
|
|
||||||
return env
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return append(env, prefix+value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyFile(src, dst string) error {
|
func copyFile(src, dst string) error {
|
||||||
in, err := os.Open(src)
|
in, err := os.Open(src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -3,27 +3,13 @@
|
||||||
package supervisor
|
package supervisor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
func hideWindow(cmd *exec.Cmd) {}
|
func hideWindow(cmd *exec.Cmd) {}
|
||||||
|
|
||||||
func killProcessTree(cmd *exec.Cmd) error {
|
|
||||||
if cmd == nil || cmd.Process == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
pid := cmd.Process.Pid
|
|
||||||
// Negative PID signals the process group (script PTY wrapper + NRE).
|
|
||||||
if err := syscall.Kill(-pid, syscall.SIGKILL); err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return cmd.Process.Kill()
|
|
||||||
}
|
|
||||||
|
|
||||||
func processDead(pid int) bool {
|
func processDead(pid int) bool {
|
||||||
p, err := os.FindProcess(pid)
|
p, err := os.FindProcess(pid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -32,63 +18,3 @@ func processDead(pid int) bool {
|
||||||
err = p.Signal(syscall.Signal(0))
|
err = p.Signal(syscall.Signal(0))
|
||||||
return err != nil
|
return err != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// startNRELogged starts NRE under a PTY so Spectre.Console sees a real terminal.
|
|
||||||
// Plain file/pipe redirects make N_m3u8DL-RE force ANSI UI with WindowWidth 0,
|
|
||||||
// which crashes ProgressRefreshThread (ArgumentException/RemoveRange).
|
|
||||||
//
|
|
||||||
// Uses util-linux `script` when available (PTY + typescript log). Falls back to
|
|
||||||
// attaching logFile as Stdout/Stderr. keepLogFD is false when script took over
|
|
||||||
// the log path (caller must not Close logFile again).
|
|
||||||
func startNRELogged(cmd *exec.Cmd, logFile *os.File) (pty io.Closer, keepLogFD bool, err error) {
|
|
||||||
scriptPath, err := exec.LookPath("script")
|
|
||||||
if err != nil {
|
|
||||||
cmd.Stdout = logFile
|
|
||||||
cmd.Stderr = logFile
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
return nil, true, err
|
|
||||||
}
|
|
||||||
return nopCloser{}, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
logPath := logFile.Name()
|
|
||||||
_ = logFile.Sync()
|
|
||||||
_ = logFile.Close()
|
|
||||||
|
|
||||||
inner := shellJoin(append([]string{cmd.Path}, cmd.Args[1:]...)...)
|
|
||||||
// -q quiet header, -a append (keep prior runs), -f flush so log tails live.
|
|
||||||
wrapped := exec.Command(scriptPath, "-q", "-a", "-f", "-c", inner, logPath)
|
|
||||||
wrapped.Env = cmd.Env
|
|
||||||
wrapped.Dir = cmd.Dir
|
|
||||||
if cmd.SysProcAttr != nil {
|
|
||||||
wrapped.SysProcAttr = cmd.SysProcAttr
|
|
||||||
} else {
|
|
||||||
wrapped.SysProcAttr = &syscall.SysProcAttr{}
|
|
||||||
}
|
|
||||||
// Own process group so Stop can signal the whole tree (script + NRE).
|
|
||||||
wrapped.SysProcAttr.Setpgid = true
|
|
||||||
*cmd = *wrapped
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
return nopCloser{}, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func shellJoin(argv ...string) string {
|
|
||||||
parts := make([]string, len(argv))
|
|
||||||
for i, a := range argv {
|
|
||||||
parts[i] = shellQuote(a)
|
|
||||||
}
|
|
||||||
return strings.Join(parts, " ")
|
|
||||||
}
|
|
||||||
|
|
||||||
func shellQuote(s string) string {
|
|
||||||
if s == "" {
|
|
||||||
return "''"
|
|
||||||
}
|
|
||||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
|
||||||
}
|
|
||||||
|
|
||||||
type nopCloser struct{}
|
|
||||||
|
|
||||||
func (nopCloser) Close() error { return nil }
|
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,8 @@
|
||||||
package supervisor
|
package supervisor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strconv"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -17,29 +15,6 @@ func hideWindow(cmd *exec.Cmd) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func killProcessTree(cmd *exec.Cmd) error {
|
|
||||||
if cmd == nil || cmd.Process == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
pid := cmd.Process.Pid
|
|
||||||
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
|
|
||||||
}
|
|
||||||
|
|
||||||
// startNRELogged attaches logFile as Stdout/Stderr. Windows CREATE_NO_WINDOW
|
|
||||||
// avoids the Spectre pipe-width crash that hits Linux daemons.
|
|
||||||
func startNRELogged(cmd *exec.Cmd, logFile *os.File) (io.Closer, bool, error) {
|
|
||||||
cmd.Stdout = logFile
|
|
||||||
cmd.Stderr = logFile
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
return nil, true, err
|
|
||||||
}
|
|
||||||
return nopCloser{}, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type nopCloser struct{}
|
|
||||||
|
|
||||||
func (nopCloser) Close() error { return nil }
|
|
||||||
|
|
||||||
func processDead(pid int) bool {
|
func processDead(pid int) bool {
|
||||||
p, err := os.FindProcess(pid)
|
p, err := os.FindProcess(pid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ export const state = {
|
||||||
agents: [],
|
agents: [],
|
||||||
deps: null,
|
deps: null,
|
||||||
uptimeS: 0,
|
uptimeS: 0,
|
||||||
refreshedAt: 0,
|
|
||||||
connected: false,
|
connected: false,
|
||||||
lastError: "",
|
lastError: "",
|
||||||
};
|
};
|
||||||
|
|
@ -58,7 +57,6 @@ export async function refresh(reason = "poll") {
|
||||||
state.uptimeS = health.uptime_s || 0;
|
state.uptimeS = health.uptime_s || 0;
|
||||||
if (health.deps) state.deps = health.deps;
|
if (health.deps) state.deps = health.deps;
|
||||||
}
|
}
|
||||||
state.refreshedAt = Date.now();
|
|
||||||
state.lastError = "";
|
state.lastError = "";
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
state.lastError = err.message || String(err);
|
state.lastError = err.message || String(err);
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,15 @@
|
||||||
// Dashboard: the headline numbers, what is scheduled next, and recent events.
|
// Dashboard: the headline numbers, what is scheduled next, and recent events.
|
||||||
|
|
||||||
import {
|
import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js";
|
||||||
el, pill, fmtRelative, fmtDateTime, fmtSeconds, setText, reconcile, copyText,
|
|
||||||
} from "../util.js";
|
|
||||||
import { state, subscribe, refresh } from "../store.js";
|
import { state, subscribe, refresh } from "../store.js";
|
||||||
import { timeline } from "../components.js";
|
import { timeline } from "../components.js";
|
||||||
|
|
||||||
const DONATIONS = [
|
|
||||||
{ coin: "ETH", addr: "0xa6314ce4deaa8329abba301802e3f511b3fa80a6" },
|
|
||||||
{ coin: "LTC", addr: "ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6" },
|
|
||||||
{ coin: "BTC", addr: "bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha" },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function dashboard(root) {
|
export function dashboard(root) {
|
||||||
const alarmTiles = el("div.tiles");
|
const alarmTiles = el("div.tiles");
|
||||||
const trafficTiles = el("div.tiles");
|
const trafficTiles = el("div.tiles");
|
||||||
const upcomingBody = el("tbody");
|
const upcomingBody = el("tbody");
|
||||||
const feed = el("div");
|
const feed = el("div");
|
||||||
const attention = el("div.stack");
|
const attention = el("div.stack");
|
||||||
const uptimeBody = el("tbody");
|
|
||||||
const sessionsBody = el("tbody");
|
|
||||||
const supportBody = el("div.stack");
|
|
||||||
|
|
||||||
root.append(el("div.stack",
|
root.append(el("div.stack",
|
||||||
el("div.tile-band",
|
el("div.tile-band",
|
||||||
|
|
@ -35,38 +24,6 @@ export function dashboard(root) {
|
||||||
el("div.card-head", el("h2", { text: "Needs attention" })),
|
el("div.card-head", el("h2", { text: "Needs attention" })),
|
||||||
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",
|
||||||
el("div.card-head",
|
el("div.card-head",
|
||||||
el("h2", { text: "Coming up" }),
|
el("h2", { text: "Coming up" }),
|
||||||
|
|
@ -89,36 +46,8 @@ export function dashboard(root) {
|
||||||
el("div.card-head", el("h2", { text: "Recent activity" })),
|
el("div.card-head", el("h2", { text: "Recent activity" })),
|
||||||
feed,
|
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() {
|
function paint() {
|
||||||
const t = (state.overview && state.overview.totals) || {};
|
const t = (state.overview && state.overview.totals) || {};
|
||||||
const streams = state.streams || [];
|
const streams = state.streams || [];
|
||||||
|
|
@ -197,75 +126,6 @@ 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) || [];
|
const upcoming = (state.overview && state.overview.upcoming) || [];
|
||||||
if (!upcoming.length) {
|
if (!upcoming.length) {
|
||||||
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
|
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
|
||||||
|
|
@ -300,8 +160,8 @@ export function dashboard(root) {
|
||||||
const off = subscribe(paint);
|
const off = subscribe(paint);
|
||||||
paint();
|
paint();
|
||||||
refresh("dashboard");
|
refresh("dashboard");
|
||||||
// Keep relative times and live uptimes honest without a full refetch.
|
// Keep the relative times honest without a full refetch.
|
||||||
const tick = setInterval(paint, 1000);
|
const tick = setInterval(paint, 30000);
|
||||||
return () => {
|
return () => {
|
||||||
off();
|
off();
|
||||||
clearInterval(tick);
|
clearInterval(tick);
|
||||||
|
|
|
||||||
|
|
@ -432,7 +432,6 @@ func runServe(opt ServeOptions) {
|
||||||
hub := ws.NewHub(store, lg, origins)
|
hub := ws.NewHub(store, lg, origins)
|
||||||
|
|
||||||
eg := egress.New(dataDir, store, lg, "")
|
eg := egress.New(dataDir, store, lg, "")
|
||||||
eg.WarnMissingDeps()
|
|
||||||
eg.StartEnabled()
|
eg.StartEnabled()
|
||||||
defer eg.StopAll()
|
defer eg.StopAll()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
# 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
|
|
||||||
```
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
# Streamd v0.2.3
|
|
||||||
|
|
||||||
Host patch after v0.2.2. Retargets the rolling **`stable`** channel.
|
|
||||||
|
|
||||||
## Highlights
|
|
||||||
|
|
||||||
### NRE Spectre crash under daemon (Linux)
|
|
||||||
- **Symptom:** `downloader exited before any media arrived` within ~1s; log showed
|
|
||||||
`System.ArgumentException` / `Spectre.Console.LiveRenderable.RemoveRange`
|
|
||||||
- **Cause:** N_m3u8DL-RE forces Spectre live UI when stdout is redirected. Under
|
|
||||||
`streamd serve` (no TTY) console width is 0 and the progress thread crashes
|
|
||||||
- **Fix:** On Linux, wrap NRE with util-linux `script -q -a -f` so it gets a real
|
|
||||||
PTY; drop subtitle tracks (`-ds for=all`); pin `COLUMNS`/`LINES`/`TERM`; kill
|
|
||||||
the process group on stop
|
|
||||||
- Log path in errors clarified as `data/logs/<name>-nre.log`
|
|
||||||
|
|
||||||
### Verified
|
|
||||||
- vm-2085: `rte` + `rte-jr` stayed **ok** after deploy (40s+ uptime)
|
|
||||||
|
|
||||||
## Known limits
|
|
||||||
|
|
||||||
- **BBC Live from datacenter IPs** can still get CDN **403**. Needs UK residential egress.
|
|
||||||
- Requires `script` (util-linux) on the host PATH for the PTY path; falls back to
|
|
||||||
plain file redirect if missing (may still hit Spectre on some hosts)
|
|
||||||
|
|
||||||
## 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,15 +496,6 @@ 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`)
|
`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.
|
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
|
### Dashboard
|
||||||
|
|
||||||
1. **Settings → Egress tunnels → Add profile**
|
1. **Settings → Egress tunnels → Add profile**
|
||||||
|
|
|
||||||
|
|
@ -45,14 +45,8 @@ warning.
|
||||||
- Per-stream **`egress`** names a profile from **Settings → Egress** (WireGuard
|
- Per-stream **`egress`** names a profile from **Settings → Egress** (WireGuard
|
||||||
netns + local SOCKS on Linux, or a plain SOCKS URL profile). Resolve order:
|
netns + local SOCKS on Linux, or a plain SOCKS URL profile). Resolve order:
|
||||||
explicit `proxy` → named egress SOCKS → direct. Full-tunnel WG stays inside
|
explicit `proxy` → named egress SOCKS → direct. Full-tunnel WG stays inside
|
||||||
`streamd-<name>` netns so SSH/UI keep the host route. On Linux Up, streamd
|
`streamd-<name>` netns so SSH/UI keep the host route. See
|
||||||
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.
|
[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`.
|
- **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
|
Enabling HD/SD starts live ffmpeg ladders at `/hls/<name>-hd/` and
|
||||||
`/hls/<name>-sd/`. The dashboard Copy button copies the absolute m3u8 URL
|
`/hls/<name>-sd/`. The dashboard Copy button copies the absolute m3u8 URL
|
||||||
|
|
@ -63,7 +57,6 @@ warning.
|
||||||
| Route | Purpose |
|
| Route | Purpose |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `GET /api/health` | liveness + uptime + `deps` paths |
|
| `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/apps` | modules under the panel store (`--data/modules`), channels, rewriters |
|
||||||
| `GET /api/modules` | list panel modules with yaml/package hashes + arches |
|
| `GET /api/modules` | list panel modules with yaml/package hashes + arches |
|
||||||
| `GET /api/modules/:name` | metadata; `?include=yaml` returns YAML (operator+) |
|
| `GET /api/modules/:name` | metadata; `?include=yaml` returns YAML (operator+) |
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue