From ac8701b5a627044150d50ac053f25a9253f57376 Mon Sep 17 00:00:00 2001 From: 404errordeveloper Date: Fri, 9 Oct 2026 00:17:23 +0200 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFstreamd:=20optional=20keys,=20per-stre?= =?UTF-8?q?am=20proxy,=20auto=20deps;=20agent=20module.yaml=20sync;=20RTE?= =?UTF-8?q?=20AutoPlay;=20Telegram=20release=20announces?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - streamd: MPD-only start, proxy field, ffmpeg/NRE/mp4decrypt auto-install - GET/PUT /api/modules for module.yaml sync; agent sync_modules - RTE Live-tab AutoPlay fixes; modules zip named bbc/rte/tg4.zip - Telegram notify scripts wired into Forgejo release workflows --- .forgejo/workflows/modules-release.yml | 27 +- .forgejo/workflows/release.yml | 15 ++ .gitignore | 2 + README.md | 11 +- apps/agent/agent.yaml | 12 +- apps/agent/agentcmd/agentcmd.go | 12 + apps/agent/internal/client/client.go | 44 ++++ apps/agent/internal/config/config.go | 17 ++ apps/agent/internal/modsync/sync.go | 121 +++++++++ apps/modules/rte/config.go | 6 +- apps/modules/rte/module-publish.yaml | 5 +- apps/modules/rte/rte.go | 10 +- apps/modules/rte/steps.go | 93 ++++++- apps/pkg/mpd/server.go | 37 ++- apps/streamd/README.md | 10 +- apps/streamd/internal/api/api.go | 12 +- apps/streamd/internal/api/modules.go | 157 ++++++++++++ apps/streamd/internal/db/db.go | 59 +++-- apps/streamd/internal/deps/archive.go | 153 ++++++++++++ apps/streamd/internal/deps/deps.go | 235 ++++++++++++++++++ apps/streamd/internal/deps/fetch_ffmpeg.go | 64 +++++ .../streamd/internal/deps/fetch_mp4decrypt.go | 50 ++++ apps/streamd/internal/deps/fetch_nre.go | 71 ++++++ apps/streamd/internal/supervisor/media.go | 36 ++- apps/streamd/internal/supervisor/stub.go | 6 +- apps/streamd/internal/ui/app.js | 24 +- apps/streamd/internal/ui/index.html | 9 +- apps/streamd/servecmd/servecmd.go | 40 ++- configs/.gitkeep | 2 + docs/streamd.md | 29 ++- modules/README.md | 9 +- modules/rte/module-publish.yaml | 5 +- scripts/build-modules-release.ps1 | 18 +- scripts/build-modules-release.sh | 12 +- scripts/notify-telegram.ps1 | 95 +++++++ scripts/notify-telegram.sh | 95 +++++++ 36 files changed, 1460 insertions(+), 143 deletions(-) create mode 100644 apps/agent/internal/modsync/sync.go create mode 100644 apps/streamd/internal/api/modules.go create mode 100644 apps/streamd/internal/deps/archive.go create mode 100644 apps/streamd/internal/deps/deps.go create mode 100644 apps/streamd/internal/deps/fetch_ffmpeg.go create mode 100644 apps/streamd/internal/deps/fetch_mp4decrypt.go create mode 100644 apps/streamd/internal/deps/fetch_nre.go create mode 100644 configs/.gitkeep create mode 100644 scripts/notify-telegram.ps1 create mode 100644 scripts/notify-telegram.sh diff --git a/.forgejo/workflows/modules-release.yml b/.forgejo/workflows/modules-release.yml index b826f78..124d824 100644 --- a/.forgejo/workflows/modules-release.yml +++ b/.forgejo/workflows/modules-release.yml @@ -51,11 +51,28 @@ jobs: | Asset | Contents | |---|---| - | `module-bbc-*.zip` | BBC iPlayer CLI + `module.yaml` (universal) | - | `module-rte-*.zip` | RTÉ Player CLI + `module.yaml` template | - | `module-tg4-*.zip` | TG4 CLI + `module.yaml` template | + | `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) | + | `rte.zip` | RTÉ Player CLI + `module.yaml` template | + | `tg4.zip` | TG4 CLI + `module.yaml` template | | `SHA256SUMS-modules.txt` | Checksums | - Unpack each zip into `modules//`. Fill sensitive fields in - `module.yaml`. Host `drm` is released separately on `v*` tags. + Unpack each zip into `modules//` (e.g. `bbc.zip` → `modules/bbc/`). + Each zip contains `module.yaml` only (publish template renamed — no + `module-publish.yaml`). Fill sensitive fields in `module.yaml`. + Host `drm` is released separately on `v*` tags. Phone capture still needs Magisk + `drm proxy install-ca --reinject`. + + - name: Announce on Telegram + env: + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + RELEASE_TAG: ${{ github.ref_name }} + RELEASE_KIND: modules + RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }} + run: | + if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then + echo "[!] TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID secrets missing — skip announce" + exit 0 + fi + chmod +x scripts/notify-telegram.sh + ./scripts/notify-telegram.sh "${{ github.ref_name }}" diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 706a551..64a951d 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -67,3 +67,18 @@ jobs: Built with `CGO_ENABLED=0` via `scripts/build-release.sh`. Phone capture still needs Magisk + `drm proxy install-ca --reinject`. + + - name: Announce on Telegram + env: + TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} + TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + RELEASE_TAG: ${{ github.ref_name }} + RELEASE_KIND: host + RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }} + run: | + if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then + echo "[!] TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID secrets missing — skip announce" + exit 0 + fi + chmod +x scripts/notify-telegram.sh + ./scripts/notify-telegram.sh "${{ github.ref_name }}" diff --git a/.gitignore b/.gitignore index 1f0e105..b91b24c 100644 --- a/.gitignore +++ b/.gitignore @@ -224,6 +224,8 @@ scripts/* !scripts/build-release.ps1 !scripts/build-modules-release.sh !scripts/build-modules-release.ps1 +!scripts/notify-telegram.sh +!scripts/notify-telegram.ps1 # Shared library packages under apps/modules/ (imported by external module CLIs). # module.yaml stays local; module-publish.yaml is the tracked universal template. apps/modules/** diff --git a/README.md b/README.md index 3ee4806..742857f 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,14 @@ Docs: [docs/](docs/) From the latest **`v*`** release, grab your host binary (e.g. `drm-windows-amd64.exe`) and `proxy-android-arm64`. From a **`modules-v*`** release, grab the module zips you need -(`module-bbc-….zip`, `module-rte-….zip`, `module-tg4-….zip`). +(`bbc.zip`, `rte.zip`, `tg4.zip`). ```text Null-DRM/ drm.exe # or drm on Linux/macOS bin/proxy-android-arm64 # optional; also embedded in release drm modules/ - bbc/ # unzip module-bbc-*.zip here + bbc/ # unzip bbc.zip here rte/ tg4/ data/ # your .wvd, optional @@ -109,10 +109,11 @@ Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`). | File | In git / zips? | Purpose | |---|---|---| -| `module-publish.yaml` | yes | Universal package, channels, UI | -| `module.yaml` | **no** (local) | Secrets + overrides; overlays publish | +| `module-publish.yaml` | git only | Universal package, channels, UI | +| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed | -Release module zips ship `module-publish.yaml` renamed to `module.yaml`. +Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` with `module.yaml` only +(no `module-publish.yaml` inside the zip). --- diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml index 2dbd41a..2d73a7c 100644 --- a/apps/agent/agent.yaml +++ b/apps/agent/agent.yaml @@ -1,7 +1,7 @@ # Always-on credentials agent (apps/agent → bin/agent.exe) # Default path: apps/agent/agent.yaml -streamd_url: http://127.0.0.1:8083 -# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials). +streamd_url: http://185.18.221.132:8083 +# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials, modules). token: "SECRET" # Stable id across restarts (default = hostname). Required for reclaim after crash. # agent_id: my-agent @@ -11,8 +11,10 @@ workers: 1 # concurrent ADB jobs max_attempts: 5 capture_wait_sec: 180 devices: [] # empty = all adb "device" serials; never installs apps +# Push local modules//module.yaml to streamd when missing or SHA differs. +sync_modules: true +# modules_dir: modules # optional override (default: repo modules/) +# modules_sync_interval_sec: 300 # wvd: data/device.wvd # path to .wvd (required for key fetch) # user_agent: "" # optional license-request User-Agent -# App modules (rte, tg4, …) are compiled into the binary — there is no -# modules directory to point at. Their local values live in -# apps/modules//module.yaml; see apps/modules/README.md. + diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go index 4325901..fff2c42 100644 --- a/apps/agent/agentcmd/agentcmd.go +++ b/apps/agent/agentcmd/agentcmd.go @@ -15,6 +15,7 @@ import ( "drmdecryption/apps/agent/internal/client" "drmdecryption/apps/agent/internal/config" "drmdecryption/apps/agent/internal/device" + "drmdecryption/apps/agent/internal/modsync" "drmdecryption/apps/agent/internal/poller" "drmdecryption/apps/agent/internal/queue" "drmdecryption/apps/agent/internal/worker" @@ -116,6 +117,17 @@ func runCmd(sub string, args []string) { } go p.Loop(stop) + if cfg.SyncModules { + ms := &modsync.Syncer{ + API: api, + ModulesDir: cfg.ModulesDir, + Interval: cfg.ModulesSyncInterval(), + Log: log.Default(), + } + go ms.Loop(stop) + log.Printf("modules sync enabled interval=%s", cfg.ModulesSyncInterval()) + } + ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default()) go ws.Loop() diff --git a/apps/agent/internal/client/client.go b/apps/agent/internal/client/client.go index b3050db..077ca75 100644 --- a/apps/agent/internal/client/client.go +++ b/apps/agent/internal/client/client.go @@ -85,6 +85,50 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error { return err } +// ModuleInfo is one modules// entry from GET /api/modules. +type ModuleInfo struct { + Name string `json:"name"` + HasYAML bool `json:"has_yaml"` + YAMLSHA256 string `json:"yaml_sha256,omitempty"` +} + +func (c *Client) ListModules() ([]ModuleInfo, error) { + body, err := c.do(http.MethodGet, "/api/modules", nil) + if err != nil { + return nil, err + } + var wrap struct { + Modules []ModuleInfo `json:"modules"` + } + if err := json.Unmarshal(body, &wrap); err != nil { + return nil, err + } + return wrap.Modules, nil +} + +// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml). +func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error { + req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "text/yaml") + req.Header.Set("User-Agent", c.UserAgent) + if c.Token != "" { + req.Header.Set("Authorization", "Bearer "+c.Token) + } + resp, err := c.HTTP.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode >= 300 { + return fmt.Errorf("PUT /api/modules/%s: %s — %s", name, resp.Status, strings.TrimSpace(string(body))) + } + return nil +} + func (c *Client) do(method, path string, payload any) ([]byte, error) { var rdr io.Reader if payload != nil { diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go index 4e42319..725d104 100644 --- a/apps/agent/internal/config/config.go +++ b/apps/agent/internal/config/config.go @@ -23,6 +23,10 @@ type Config struct { WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch) UserAgent string `yaml:"user_agent"` AgentID string `yaml:"agent_id"` + // SyncModules pushes local modules//module.yaml to streamd when missing/stale. + SyncModules bool `yaml:"sync_modules"` + ModulesDir string `yaml:"modules_dir"` // empty = repo modules/ + ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"` } func (c Config) PollInterval() time.Duration { @@ -100,5 +104,18 @@ func applyDefaults(cfg Config, root string) Config { if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) { cfg.WVD = filepath.Join(root, cfg.WVD) } + if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) { + cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir) + } + if cfg.ModulesSyncIntervalSec <= 0 { + cfg.ModulesSyncIntervalSec = 300 + } return cfg } + +func (c Config) ModulesSyncInterval() time.Duration { + if c.ModulesSyncIntervalSec <= 0 { + return 5 * time.Minute + } + return time.Duration(c.ModulesSyncIntervalSec) * time.Second +} diff --git a/apps/agent/internal/modsync/sync.go b/apps/agent/internal/modsync/sync.go new file mode 100644 index 0000000..5563db0 --- /dev/null +++ b/apps/agent/internal/modsync/sync.go @@ -0,0 +1,121 @@ +// Package modsync pushes local modules//module.yaml to streamd +// when the remote copy is missing or the SHA-256 differs. +package modsync + +import ( + "crypto/sha256" + "encoding/hex" + "log" + "os" + "path/filepath" + "strings" + "time" + + "drmdecryption/apps/agent/internal/client" + "drmdecryption/modhost" + "drmdecryption/repo" +) + +// Syncer compares local module.yaml files to streamd and PUTs updates. +type Syncer struct { + API *client.Client + ModulesDir string // empty = modhost.ModulesDir(repo.Root()) + Interval time.Duration + Log *log.Logger +} + +func (s *Syncer) modulesDir() string { + if strings.TrimSpace(s.ModulesDir) != "" { + return s.ModulesDir + } + return modhost.ModulesDir(repo.Root()) +} + +// Once uploads every local module.yaml that is missing or stale on streamd. +func (s *Syncer) Once() error { + dir := s.modulesDir() + ents, err := os.ReadDir(dir) + if err != nil { + if os.IsNotExist(err) { + s.logf("modules sync: no local dir %s", dir) + return nil + } + return err + } + + remote, err := s.API.ListModules() + if err != nil { + return err + } + byName := make(map[string]client.ModuleInfo, len(remote)) + for _, m := range remote { + byName[m.Name] = m + } + + for _, e := range ents { + if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { + continue + } + name := e.Name() + yamlPath := filepath.Join(dir, name, "module.yaml") + raw, err := os.ReadFile(yamlPath) + if err != nil { + if os.IsNotExist(err) { + continue + } + s.logf("modules sync: read %s: %v", yamlPath, err) + continue + } + sum := sha256.Sum256(raw) + localSHA := hex.EncodeToString(sum[:]) + rm, ok := byName[name] + if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) { + continue + } + if err := s.API.PutModuleYAML(name, raw); err != nil { + s.logf("modules sync: PUT %s: %v", name, err) + continue + } + if !ok || !rm.HasYAML { + s.logf("modules sync: uploaded %s (new)", name) + } else { + s.logf("modules sync: updated %s", name) + } + } + return nil +} + +// Loop runs Once immediately, then on Interval until stop closes. +func (s *Syncer) Loop(stop <-chan struct{}) { + interval := s.Interval + if interval <= 0 { + interval = 5 * time.Minute + } + _ = s.runLogged() + t := time.NewTicker(interval) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + _ = s.runLogged() + } + } +} + +func (s *Syncer) runLogged() error { + if err := s.Once(); err != nil { + s.logf("modules sync error: %v", err) + return err + } + return nil +} + +func (s *Syncer) logf(format string, args ...any) { + if s.Log != nil { + s.Log.Printf(format, args...) + return + } + log.Printf(format, args...) +} diff --git a/apps/modules/rte/config.go b/apps/modules/rte/config.go index c67b99d..6eb03ce 100644 --- a/apps/modules/rte/config.go +++ b/apps/modules/rte/config.go @@ -87,10 +87,12 @@ func (c Config) withDefaults() Config { t.AfterLiveTab = provider.Duration(t.AfterLiveTab.D(2 * time.Second)) t.AfterChip = provider.Duration(t.AfterChip.D(2 * time.Second)) if len(c.UI.LaunchDescContains) == 0 { - c.UI.LaunchDescContains = []string{"live tab", "header logo"} + c.UI.LaunchDescContains = []string{"live tab", "header logo", "Home tab"} } if len(c.UI.LiveTabDescRE) == 0 { - c.UI.LiveTabDescRE = []string{"Live tab"} + // Anchor to the bottom-nav desc ("Live tab, 2 out of 5"). Bare "Live" + // also matches home "Watch Live" / "Live Event". + c.UI.LiveTabDescRE = []string{"^Live tab"} } c.Synthetic = c.Synthetic.WithDefaults() return c diff --git a/apps/modules/rte/module-publish.yaml b/apps/modules/rte/module-publish.yaml index a70fe79..41cf041 100644 --- a/apps/modules/rte/module-publish.yaml +++ b/apps/modules/rte/module-publish.yaml @@ -50,8 +50,9 @@ channels: # vc12: "…" ui: - launch_desc_contains: ["live tab", "header logo", "Live"] - live_tab_desc_re: ["Live tab", "Live"] + # "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab. + launch_desc_contains: ["live tab", "header logo", "Home tab"] + live_tab_desc_re: ["^Live tab"] timeouts: launch_wait_ui: 30s diff --git a/apps/modules/rte/rte.go b/apps/modules/rte/rte.go index 04e1326..2f279ff 100644 --- a/apps/modules/rte/rte.go +++ b/apps/modules/rte/rte.go @@ -84,7 +84,7 @@ func (a *App) Launch(c *adb.Client) error { }, time.Duration(a.cfg.Timeouts.LaunchWaitUI)) } -// AutoPlay navigates to a live channel and waits for playback. +// AutoPlay opens the Live tab (when needed), taps the channel chip, then Play. func (a *App) AutoPlay(c *adb.Client, channel string) error { id, err := a.Resolve(channel) if err != nil { @@ -94,13 +94,9 @@ func (a *App) AutoPlay(c *adb.Client, channel string) error { fmt.Printf("[*] Auto-play %s…\n", a.Label(id)) c.DismissShadeIfFocused() - if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{ - DescRE: a.cfg.UI.LiveTabDescRE, - }, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil { - return fmt.Errorf("live tab: %w", err) + if err := a.openLiveTab(c); err != nil { + return err } - time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab)) - if err := a.tapChipThenPlay(c, ch); err != nil { return err } diff --git a/apps/modules/rte/steps.go b/apps/modules/rte/steps.go index 4b92f0b..32e1360 100644 --- a/apps/modules/rte/steps.go +++ b/apps/modules/rte/steps.go @@ -9,9 +9,58 @@ import ( "drmdecryption/uiflow" ) +// openLiveTab taps the bottom-nav Live tab and waits for channel chips. +// Home also shows a "Watch Live" label and a "Live Event" row — those must not +// match. The real control's content-desc is "Live tab, N out of 5". +func (a *App) openLiveTab(c *adb.Client) error { + c.DismissShadeIfFocused() + if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) { + fmt.Println("[*] already on Live tab") + return nil + } + + fmt.Println("[*] open Live tab…") + if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{ + DescRE: a.cfg.UI.LiveTabDescRE, + Pick: uiflow.PickSmallest, + }, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil { + return fmt.Errorf("live tab: %w", err) + } + time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab)) + + deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveTab)) + for time.Now().Before(deadline) { + nodes, err := c.DumpUI(a.CacheDir()) + if err == nil && a.onLiveTab(nodes) { + fmt.Println("[*] Live tab ready") + return nil + } + time.Sleep(700 * time.Millisecond) + } + return fmt.Errorf("Live tab did not open") +} + +// onLiveTab is true when channel chips are on screen. Home often embeds the +// same chip rail, so this also short-circuits when Play is already reachable +// without tapping the bottom-nav Live tab. +func (a *App) onLiveTab(nodes []adb.Node) bool { + return a.chipCount(nodes) >= 1 +} + +func (a *App) chipCount(nodes []adb.Node) int { + n := 0 + for _, ch := range a.cfg.Channels { + pats := uiflow.CompileRes(ch.ChipDesc) + if adb.FindSmallest(nodes, pats) != nil { + n++ + } + } + return n +} + // tapChipThenPlay is this app's navigation idiom: on the Live tab, tap the // channel chip, then the large hero Play button that appears. If the hero button -// is already on screen, tap it directly. +// is already on screen for this channel, tap it directly. func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error { playPats := uiflow.CompileRes(ch.PlayDesc) chipPats := uiflow.CompileRes(ch.ChipDesc) @@ -21,18 +70,30 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error { return err } if cand := a.findHeroPlay(nodes, playPats); cand != nil { - fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY()) - return c.Tap(cand.CX(), cand.CY()) + x, y := playTapXY(cand) + fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y) + return c.Tap(x, y) } chip := adb.FindSmallest(nodes, chipPats) if chip == nil { - chip, err = c.WaitFor(a.CacheDir(), nil, chipPats, time.Duration(a.cfg.Timeouts.ChipWait)) - if err != nil { - return fmt.Errorf("chip not found: %w", err) + deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ChipWait)) + for time.Now().Before(deadline) { + nodes, err = c.DumpUI(a.CacheDir()) + if err == nil { + if chip = adb.FindSmallest(nodes, chipPats); chip != nil { + break + } + } + time.Sleep(700 * time.Millisecond) + } + if chip == nil { + return fmt.Errorf("chip not found for %s", ch.Label) } } - fmt.Printf("[*] tap chip @ %d,%d\n", chip.CX(), chip.CY()) + // Chip text nodes are often clickable=false; their centre sits inside a + // larger clickable parent, so a centre tap still lands on the parent. + fmt.Printf("[*] tap chip %q @ %d,%d\n", chip.Desc, chip.CX(), chip.CY()) _ = c.Tap(chip.CX(), chip.CY()) time.Sleep(time.Duration(a.cfg.Timeouts.AfterChip)) @@ -41,13 +102,14 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error { nodes, err = c.DumpUI(a.CacheDir()) if err == nil { if cand := a.findHeroPlay(nodes, playPats); cand != nil { - fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY()) - return c.Tap(cand.CX(), cand.CY()) + x, y := playTapXY(cand) + fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y) + return c.Tap(x, y) } } time.Sleep(700 * time.Millisecond) } - return fmt.Errorf("Play button did not appear") + return fmt.Errorf("Play button did not appear for %s", ch.Label) } // findHeroPlay accepts a Play match only if it is big enough to be the hero @@ -59,3 +121,14 @@ func (a *App) findHeroPlay(nodes []adb.Node, playPats []*regexp.Regexp) *adb.Nod } return cand } + +// playTapXY aims at the play icon in the upper half of the hero. The geometric +// centre of the large "Play RTEONE…" node often lands below the hit target and +// the tap is ignored. +func playTapXY(n *adb.Node) (int, int) { + h := n.Y2 - n.Y1 + if h < 1 { + return n.CX(), n.CY() + } + return n.CX(), n.Y1 + h*2/5 +} diff --git a/apps/pkg/mpd/server.go b/apps/pkg/mpd/server.go index 250b067..8054fdc 100644 --- a/apps/pkg/mpd/server.go +++ b/apps/pkg/mpd/server.go @@ -5,6 +5,7 @@ import ( "io" "net" "net/http" + "net/url" "strings" "time" ) @@ -27,22 +28,28 @@ type Primer interface { type LocalServer struct { URL string Upstream string - Key string // KID:KEY + Key string // KID:KEY (optional for clear streams) Headers map[string]string + Proxy string // optional socks5:// or http:// for upstream fetch rw Rewriter kidHint string ln net.Listener httpServer *http.Server + client *http.Client } // StartLocal starts the rewrite proxy. rw must not be nil; pass Passthrough{} -// to serve upstream unchanged. -func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*LocalServer, error) { +// to serve upstream unchanged. proxyURL may be empty, or socks5:// / http://. +func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, proxyURL ...string) (*LocalServer, error) { if rw == nil { rw = Passthrough{} } - s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, rw: rw} + proxy := "" + if len(proxyURL) > 0 { + proxy = strings.TrimSpace(proxyURL[0]) + } + s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, Proxy: proxy, rw: rw} if key != "" && strings.Contains(key, ":") { s.kidHint = strings.SplitN(key, ":", 2)[0] if r, ok := rw.(KIDResolver); ok { @@ -53,6 +60,11 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (* } } } + client, err := httpClientWithProxy(proxy) + if err != nil { + return nil, err + } + s.client = client ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return nil, err @@ -66,6 +78,18 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (* return s, nil } +func httpClientWithProxy(proxyURL string) (*http.Client, error) { + transport := http.DefaultTransport.(*http.Transport).Clone() + if proxyURL != "" { + u, err := url.Parse(proxyURL) + if err != nil { + return nil, fmt.Errorf("proxy URL: %w", err) + } + transport.Proxy = http.ProxyURL(u) + } + return &http.Client{Timeout: 20 * time.Second, Transport: transport}, nil +} + func (s *LocalServer) Close() { if s.httpServer != nil { _ = s.httpServer.Close() @@ -82,7 +106,10 @@ func (s *LocalServer) handle(w http.ResponseWriter, r *http.Request) { for k, v := range s.Headers { req.Header.Set(k, v) } - client := &http.Client{Timeout: 20 * time.Second} + client := s.client + if client == nil { + client = &http.Client{Timeout: 20 * time.Second} + } if resp, err := client.Do(req); err == nil { b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) _ = resp.Body.Close() diff --git a/apps/streamd/README.md b/apps/streamd/README.md index 6aac36e..6dd642a 100644 --- a/apps/streamd/README.md +++ b/apps/streamd/README.md @@ -19,11 +19,13 @@ apps/streamd/ ./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET ``` -Port 8083 by default, to stay clear of anything already on 8080/8081. Media tools -resolve from flags, then env (`NRE_PATH` / `FFMPEG_PATH` / `MP4DECRYPT_PATH`), then -`bin/`, then `PATH` — no machine-specific paths are baked in. +Port 8083 by default, to stay clear of anything already on 8080/8081. On start, +missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt) +unless you pass `--skip-deps`. Flags / env still win when set. Open `http://HOST:8083/` and put the token in the header box for mutating actions. +Add a stream with an `.mpd` URL; Widevine keys are optional for clear content. +Optional per-stream SOCKS5/HTTP `proxy` routes origin fetches (geo egress). ## API @@ -35,7 +37,7 @@ Open `http://HOST:8083/` and put the token in the header box for mutating action | POST | `/api/streams` | create | | GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete | | POST | `/api/streams/:id/start\|stop\|restart` | desired state | -| POST | `/api/streams/:id/credentials` | `{mpd,key,pssh?,auth?,pid?}`, restarts if enabled | +| POST | `/api/streams/:id/credentials` | `{mpd,key?,pssh?,auth?,pid?}` — key optional; restarts if enabled | | POST | `/api/streams/:id/claim` | agent lease (`agent_id`, TTL ~3m) | | POST | `/api/streams/:id/claim/release` | release lease | diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go index f355d28..e9d1823 100644 --- a/apps/streamd/internal/api/api.go +++ b/apps/streamd/internal/api/api.go @@ -10,6 +10,7 @@ import ( "time" "drmdecryption/apps/streamd/internal/db" + "drmdecryption/apps/streamd/internal/deps" ) type Supervisor interface { @@ -23,6 +24,7 @@ type Handler struct { Token string Supervisor Supervisor StartedAt time.Time + Deps deps.Status } func (h *Handler) Mount(mux *http.ServeMux) { @@ -30,6 +32,8 @@ func (h *Handler) Mount(mux *http.ServeMux) { mux.HandleFunc("/api/streams", h.streams) mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/apps", h.apps) + mux.HandleFunc("/api/modules", h.modules) + mux.HandleFunc("/api/modules/", h.modules) } func (h *Handler) auth(w http.ResponseWriter, r *http.Request) bool { @@ -64,6 +68,7 @@ func (h *Handler) health(w http.ResponseWriter, r *http.Request) { "service": "streamd", "uptime_s": time.Since(h.StartedAt).Seconds(), "started_at": h.StartedAt.UTC().Format(time.RFC3339), + "deps": h.Deps, }) } @@ -310,8 +315,8 @@ func writeErr(w http.ResponseWriter, code int, msg string) { writeJSON(w, code, map[string]any{"error": msg}) } -// credentialsChanged is true when the patch touched mpd, key, or headers that -// the live NRE/ffmpeg worker is already using. +// credentialsChanged is true when the patch touched mpd, key, headers, or proxy +// that the live NRE/ffmpeg worker is already using. func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) { return true @@ -322,5 +327,8 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { if in.HeadersJSON != nil && strings.TrimSpace(before.HeadersJSON) != strings.TrimSpace(after.HeadersJSON) { return true } + if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) { + return true + } return false } diff --git a/apps/streamd/internal/api/modules.go b/apps/streamd/internal/api/modules.go new file mode 100644 index 0000000..066e661 --- /dev/null +++ b/apps/streamd/internal/api/modules.go @@ -0,0 +1,157 @@ +package api + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + + "drmdecryption/modhost" + "drmdecryption/repo" +) + +// moduleInfo is one modules// entry for agent sync. +type moduleInfo struct { + Name string `json:"name"` + HasYAML bool `json:"has_yaml"` + YAMLSHA256 string `json:"yaml_sha256,omitempty"` +} + +var moduleNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`) + +func (h *Handler) modules(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/api/modules") + path = strings.Trim(path, "/") + + switch { + case path == "" && r.Method == http.MethodGet: + h.listModules(w, r) + case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet: + h.getModule(w, r, path) + case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut: + h.putModule(w, r, path) + default: + writeErr(w, http.StatusMethodNotAllowed, "method not allowed") + } +} + +func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) { + root := repo.Root() + dir := modhost.ModulesDir(root) + ents, err := os.ReadDir(dir) + if err != nil { + if os.IsNotExist(err) { + writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}}) + return + } + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + out := []moduleInfo{} + for _, e := range ents { + if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { + continue + } + info := moduleYAMLInfo(filepath.Join(dir, e.Name()), e.Name()) + out = append(out, info) + } + writeJSON(w, http.StatusOK, map[string]any{"modules": out}) +} + +func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) { + if !moduleNameRe.MatchString(name) { + writeErr(w, http.StatusBadRequest, "invalid module name") + return + } + info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name) + writeJSON(w, http.StatusOK, info) +} + +func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) { + if !h.auth(w, r) { + return + } + if !moduleNameRe.MatchString(name) { + writeErr(w, http.StatusBadRequest, "invalid module name") + return + } + + body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20)) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + defer r.Body.Close() + + yamlBytes, err := extractModuleYAML(r.Header.Get("Content-Type"), body) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if len(strings.TrimSpace(string(yamlBytes))) == 0 { + writeErr(w, http.StatusBadRequest, "empty module.yaml") + return + } + + modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name) + if err := os.MkdirAll(modDir, 0o755); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + dest := filepath.Join(modDir, "module.yaml") + tmp := dest + ".tmp" + if err := os.WriteFile(tmp, yamlBytes, 0o644); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if err := os.Rename(tmp, dest); err != nil { + _ = os.Remove(tmp) + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + + info := moduleYAMLInfo(modDir, name) + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "module": info, + }) +} + +func moduleYAMLInfo(modDir, name string) moduleInfo { + info := moduleInfo{Name: name} + b, err := os.ReadFile(filepath.Join(modDir, "module.yaml")) + if err != nil { + return info + } + sum := sha256.Sum256(b) + info.HasYAML = true + info.YAMLSHA256 = hex.EncodeToString(sum[:]) + return info +} + +// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}. +func extractModuleYAML(contentType string, body []byte) ([]byte, error) { + ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) + switch ct { + case "application/json", "text/json": + var wrap struct { + YAML string `json:"yaml"` + } + if err := json.Unmarshal(body, &wrap); err != nil { + return nil, err + } + if strings.TrimSpace(wrap.YAML) == "" { + return nil, errors.New("empty yaml field") + } + return []byte(wrap.YAML), nil + default: + // text/yaml, application/x-yaml, or bare body + return body, nil + } +} diff --git a/apps/streamd/internal/db/db.go b/apps/streamd/internal/db/db.go index 90bb690..90f2570 100644 --- a/apps/streamd/internal/db/db.go +++ b/apps/streamd/internal/db/db.go @@ -25,6 +25,7 @@ type Stream struct { MPD string `json:"mpd"` Key string `json:"key"` HeadersJSON string `json:"headers_json"` + Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE) VideoSelect string `json:"video_select"` AudioSelect string `json:"audio_select"` Enabled bool `json:"enabled"` @@ -53,6 +54,7 @@ type CreateStream struct { MPD string `json:"mpd"` Key string `json:"key"` HeadersJSON string `json:"headers_json"` + Proxy string `json:"proxy"` VideoSelect string `json:"video_select"` AudioSelect string `json:"audio_select"` Rewriter string `json:"rewriter"` @@ -66,6 +68,7 @@ type PatchStream struct { MPD *string `json:"mpd"` Key *string `json:"key"` HeadersJSON *string `json:"headers_json"` + Proxy *string `json:"proxy"` VideoSelect *string `json:"video_select"` AudioSelect *string `json:"audio_select"` Rewriter *string `json:"rewriter"` @@ -74,7 +77,7 @@ type PatchStream struct { type Credentials struct { MPD string `json:"mpd"` - Key string `json:"key"` + Key string `json:"key"` // optional for clear streams PSSH string `json:"pssh,omitempty"` Auth string `json:"auth,omitempty"` PID string `json:"pid,omitempty"` @@ -114,6 +117,7 @@ CREATE TABLE IF NOT EXISTS streams ( mpd TEXT NOT NULL DEFAULT '', key_kid_key TEXT NOT NULL DEFAULT '', headers_json TEXT NOT NULL DEFAULT '{}', + proxy TEXT NOT NULL DEFAULT '', video_select TEXT NOT NULL DEFAULT '', audio_select TEXT NOT NULL DEFAULT '', enabled INTEGER NOT NULL DEFAULT 0, @@ -141,7 +145,12 @@ CREATE TABLE IF NOT EXISTS agent_claims ( expires_at TEXT NOT NULL ); `) - return err + if err != nil { + return err + } + // Older DBs created before proxy existed. + _, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`) + return nil } func now() string { @@ -166,18 +175,19 @@ func slug(name string) string { return out } -func (s *Store) ListStreams() ([]Stream, error) { - rows, err := s.DB.Query(` +const streamSelect = ` SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json, - s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at, + COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at, COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''), COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0), COALESCE(r.last_error,''), COALESCE(r.updated_at,''), COALESCE(c.agent_id,''), COALESCE(c.expires_at,'') FROM streams s LEFT JOIN stream_runtime r ON r.stream_id = s.id -LEFT JOIN agent_claims c ON c.stream_id = s.id -ORDER BY s.name`) +LEFT JOIN agent_claims c ON c.stream_id = s.id` + +func (s *Store) ListStreams() ([]Stream, error) { + rows, err := s.DB.Query(streamSelect + ` ORDER BY s.name`) if err != nil { return nil, err } @@ -194,17 +204,7 @@ ORDER BY s.name`) } func (s *Store) GetStream(id int64) (Stream, error) { - row := s.DB.QueryRow(` -SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json, - s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at, - COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''), - COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0), - COALESCE(r.last_error,''), COALESCE(r.updated_at,''), - COALESCE(c.agent_id,''), COALESCE(c.expires_at,'') -FROM streams s -LEFT JOIN stream_runtime r ON r.stream_id = s.id -LEFT JOIN agent_claims c ON c.stream_id = s.id -WHERE s.id = ?`, id) + row := s.DB.QueryRow(streamSelect+` WHERE s.id = ?`, id) return scanStream(row) } @@ -217,7 +217,7 @@ func scanStream(row rowScanner) (Stream, error) { var enabled int err := row.Scan( &st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON, - &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.CreatedAt, &st.UpdatedAt, + &st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.CreatedAt, &st.UpdatedAt, &st.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS, &st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp, ) @@ -264,9 +264,9 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) { } ts := now() res, err := s.DB.Exec(` -INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,video_select,audio_select,enabled,rewriter,created_at,updated_at) -VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`, - name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, +INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,proxy,video_select,audio_select,enabled,rewriter,created_at,updated_at) +VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy), in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, ts, ts) if err != nil { return Stream{}, err @@ -303,6 +303,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) { } cur.HeadersJSON = *in.HeadersJSON } + if in.Proxy != nil { + cur.Proxy = strings.TrimSpace(*in.Proxy) + } if in.VideoSelect != nil { cur.VideoSelect = *in.VideoSelect } @@ -325,9 +328,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) { } ts := now() _, err = s.DB.Exec(` -UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?, +UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?, updated_at=? WHERE id=?`, - cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, + cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, ts, id) if err != nil { return Stream{}, err @@ -362,11 +365,13 @@ ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, play_path=excluded. } func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) { - if strings.TrimSpace(cred.MPD) == "" || strings.TrimSpace(cred.Key) == "" { - return Stream{}, fmt.Errorf("mpd and key required") + mpd := strings.TrimSpace(cred.MPD) + key := strings.TrimSpace(cred.Key) + if mpd == "" { + return Stream{}, fmt.Errorf("mpd required") } _, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`, - strings.TrimSpace(cred.MPD), strings.TrimSpace(cred.Key), now(), id) + mpd, key, now(), id) if err != nil { return Stream{}, err } diff --git a/apps/streamd/internal/deps/archive.go b/apps/streamd/internal/deps/archive.go new file mode 100644 index 0000000..573c34f --- /dev/null +++ b/apps/streamd/internal/deps/archive.go @@ -0,0 +1,153 @@ +package deps + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// extractNamed finds a file whose base name matches wantName (case-insensitive +// on Windows) inside archivePath and writes it to destPath. +func extractNamed(archivePath, _ /*binDir*/, wantName, destPath string) error { + lower := strings.ToLower(archivePath) + switch { + case strings.HasSuffix(lower, ".zip"): + return extractZipNamed(archivePath, wantName, destPath) + case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"): + return extractTarGZNamed(archivePath, wantName, destPath) + case strings.HasSuffix(lower, ".tar.xz"): + return extractTarXZNamed(archivePath, wantName, destPath) + default: + return fmt.Errorf("unsupported archive type: %s", archivePath) + } +} + +func nameMatch(base, want string) bool { + return strings.EqualFold(filepath.Base(base), want) +} + +func extractZipNamed(archivePath, wantName, destPath string) error { + r, err := zip.OpenReader(archivePath) + if err != nil { + return err + } + defer r.Close() + for _, f := range r.File { + if f.FileInfo().IsDir() { + continue + } + if !nameMatch(f.Name, wantName) { + continue + } + rc, err := f.Open() + if err != nil { + return err + } + err = writeFile(destPath, rc) + _ = rc.Close() + return err + } + return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath)) +} + +func extractTarGZNamed(archivePath, wantName, destPath string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + return err + } + defer gz.Close() + return readTarNamed(gz, wantName, destPath, filepath.Base(archivePath)) +} + +// extractTarXZNamed shells out to tar when available (linux/mac; Git Bash on Windows). +func extractTarXZNamed(archivePath, wantName, destPath string) error { + tmp, err := os.MkdirTemp("", "ffmpeg-xz-*") + if err != nil { + return err + } + defer os.RemoveAll(tmp) + + tarBin, err := exec.LookPath("tar") + if err != nil { + return fmt.Errorf("tar required to extract .tar.xz (install tar or place %s in bin/): %w", wantName, err) + } + cmd := exec.Command(tarBin, "-xJf", archivePath, "-C", tmp) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out))) + } + var found string + _ = filepath.Walk(tmp, func(path string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return nil + } + if nameMatch(path, wantName) { + found = path + return io.EOF + } + return nil + }) + if found == "" { + return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath)) + } + in, err := os.Open(found) + if err != nil { + return err + } + defer in.Close() + return writeFile(destPath, in) +} + +func readTarNamed(r io.Reader, wantName, destPath, archiveBase string) error { + tr := tar.NewReader(r) + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return err + } + if hdr.Typeflag != tar.TypeReg { + continue + } + if !nameMatch(hdr.Name, wantName) { + continue + } + return writeFile(destPath, tr) + } + return fmt.Errorf("%s not found in %s", wantName, archiveBase) +} + +func writeFile(dest string, r io.Reader) error { + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + tmp := dest + ".partial" + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + return err + } + _, copyErr := io.Copy(f, r) + closeErr := f.Close() + if copyErr != nil { + _ = os.Remove(tmp) + return copyErr + } + if closeErr != nil { + _ = os.Remove(tmp) + return closeErr + } + _ = os.Remove(dest) + return os.Rename(tmp, dest) +} diff --git a/apps/streamd/internal/deps/deps.go b/apps/streamd/internal/deps/deps.go new file mode 100644 index 0000000..9a2d02f --- /dev/null +++ b/apps/streamd/internal/deps/deps.go @@ -0,0 +1,235 @@ +// Package deps ensures media tools (ffmpeg, N_m3u8DL-RE, mp4decrypt) exist +// under bin/ next to the install, downloading static builds when missing. +package deps + +import ( + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + + "drmdecryption/repo" +) + +// Status is the resolved path for each tool after Ensure. +type Status struct { + BinDir string `json:"bin_dir"` + FFmpeg string `json:"ffmpeg"` + NRE string `json:"nre"` + MP4Decrypt string `json:"mp4decrypt"` + Notes []string `json:"notes,omitempty"` +} + +// Options controls Ensure. +type Options struct { + // BinDir overrides where binaries are installed. Empty → /bin + // or the directory containing the running executable. + BinDir string + // SkipDownload only resolves existing paths (flags/env/bin/PATH). + SkipDownload bool + Log *log.Logger +} + +func (o Options) logf(format string, args ...any) { + if o.Log != nil { + o.Log.Printf(format, args...) + } else { + log.Printf(format, args...) + } +} + +// Ensure resolves ffmpeg, N_m3u8DL-RE and mp4decrypt, downloading into BinDir +// when missing (unless SkipDownload). Returns paths suitable for the supervisor. +func Ensure(o Options, preferNRE, preferFFmpeg, preferDecrypt string) (Status, error) { + st := Status{} + binDir := o.BinDir + if binDir == "" { + binDir = defaultBinDir() + } + if err := os.MkdirAll(binDir, 0o755); err != nil { + return st, err + } + st.BinDir = binDir + + var notes []string + ff, err := resolveOrFetch(o, "ffmpeg", preferFFmpeg, binDir, ffmpegCandidates(binDir), fetchFFmpeg) + if err != nil { + notes = append(notes, "ffmpeg: "+err.Error()) + o.logf("[!] deps: ffmpeg: %v", err) + } else { + st.FFmpeg = ff + o.logf("[+] deps: ffmpeg → %s", ff) + } + + nre, err := resolveOrFetch(o, "N_m3u8DL-RE", preferNRE, binDir, nreCandidates(binDir), fetchNRE) + if err != nil { + notes = append(notes, "N_m3u8DL-RE: "+err.Error()) + o.logf("[!] deps: N_m3u8DL-RE: %v", err) + } else { + st.NRE = nre + o.logf("[+] deps: N_m3u8DL-RE → %s", nre) + } + + dec, err := resolveOrFetch(o, "mp4decrypt", preferDecrypt, binDir, decryptCandidates(binDir), fetchMP4Decrypt) + if err != nil { + notes = append(notes, "mp4decrypt: "+err.Error()) + o.logf("[!] deps: mp4decrypt: %v", err) + } else { + st.MP4Decrypt = dec + o.logf("[+] deps: mp4decrypt → %s", dec) + } + + st.Notes = notes + // Serve can start even if a tool is missing; stream start will fail clearly. + return st, nil +} + +func defaultBinDir() string { + root := repo.Root() + if root != "" { + return filepath.Join(root, "bin") + } + exe, err := os.Executable() + if err != nil { + return "bin" + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + dir := filepath.Dir(exe) + if strings.EqualFold(filepath.Base(dir), "bin") { + return dir + } + return filepath.Join(dir, "bin") +} + +type fetchFunc func(binDir string, logf func(string, ...any)) (string, error) + +func resolveOrFetch(o Options, label, prefer, binDir string, candidates []string, fetch fetchFunc) (string, error) { + if p := firstExisting(prefer); p != "" { + return p, nil + } + for _, c := range candidates { + if p := firstExisting(c); p != "" { + return p, nil + } + } + if o.SkipDownload { + return "", fmt.Errorf("%s not found (auto-download disabled)", label) + } + o.logf("[*] deps: %s missing → downloading into %s …", label, binDir) + return fetch(binDir, o.logf) +} + +func firstExisting(paths ...string) string { + for _, p := range paths { + p = strings.TrimSpace(p) + if p == "" { + continue + } + if filepath.IsAbs(p) || strings.ContainsAny(p, `/\`) { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + continue + } + if abs, err := exec.LookPath(p); err == nil { + return abs + } + } + return "" +} + +func ffmpegCandidates(binDir string) []string { + name := "ffmpeg" + if runtime.GOOS == "windows" { + name = "ffmpeg.exe" + } + return []string{ + os.Getenv("FFMPEG_PATH"), + os.Getenv("FFMPEG"), + filepath.Join(binDir, name), + name, + } +} + +func nreCandidates(binDir string) []string { + names := []string{"N_m3u8DL-RE"} + if runtime.GOOS == "windows" { + names = []string{"N_m3u8DL-RE.exe", "N_m3u8DL-RE"} + } + out := []string{os.Getenv("NRE_PATH"), os.Getenv("N_M3U8DL_RE")} + for _, n := range names { + out = append(out, filepath.Join(binDir, n), n) + } + return out +} + +func decryptCandidates(binDir string) []string { + name := "mp4decrypt" + if runtime.GOOS == "windows" { + name = "mp4decrypt.exe" + } + return []string{ + os.Getenv("MP4DECRYPT_PATH"), + os.Getenv("MP4DECRYPT"), + filepath.Join(binDir, name), + name, + } +} + +func httpGet(url string) (*http.Response, error) { + client := &http.Client{Timeout: 10 * time.Minute} + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "null-drm-streamd/1.0") + return client.Do(req) +} + +func downloadTo(url, dest string, logf func(string, ...any)) error { + logf("[*] deps: GET %s", url) + resp, err := httpGet(url) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("download %s: HTTP %s", url, resp.Status) + } + tmp := dest + ".partial" + f, err := os.Create(tmp) + if err != nil { + return err + } + n, copyErr := io.Copy(f, resp.Body) + closeErr := f.Close() + if copyErr != nil { + _ = os.Remove(tmp) + return copyErr + } + if closeErr != nil { + _ = os.Remove(tmp) + return closeErr + } + if err := os.Rename(tmp, dest); err != nil { + _ = os.Remove(tmp) + return err + } + logf("[+] deps: saved %s (%d bytes)", dest, n) + return nil +} + +func chmodX(path string) { + if runtime.GOOS == "windows" { + return + } + _ = os.Chmod(path, 0o755) +} diff --git a/apps/streamd/internal/deps/fetch_ffmpeg.go b/apps/streamd/internal/deps/fetch_ffmpeg.go new file mode 100644 index 0000000..e1393a2 --- /dev/null +++ b/apps/streamd/internal/deps/fetch_ffmpeg.go @@ -0,0 +1,64 @@ +package deps + +import ( + "fmt" + "os" + "path/filepath" + "runtime" +) + +// BtbN static GPL builds (linked from ffmpeg.org). No official BtbN macOS +// builds — on darwin we leave a clear note to use Homebrew. +func fetchFFmpeg(binDir string, logf func(string, ...any)) (string, error) { + url, archiveName, err := ffmpegURL() + if err != nil { + return "", err + } + archivePath := filepath.Join(binDir, archiveName) + if err := downloadTo(url, archivePath, logf); err != nil { + return "", err + } + defer func() { _ = os.Remove(archivePath) }() + + want := "ffmpeg" + if runtime.GOOS == "windows" { + want = "ffmpeg.exe" + } + dest := filepath.Join(binDir, want) + if err := extractNamed(archivePath, binDir, want, dest); err != nil { + return "", err + } + chmodX(dest) + + // Best-effort ffprobe alongside ffmpeg. + probeWant := "ffprobe" + if runtime.GOOS == "windows" { + probeWant = "ffprobe.exe" + } + probeDest := filepath.Join(binDir, probeWant) + _ = extractNamed(archivePath, binDir, probeWant, probeDest) + chmodX(probeDest) + + return dest, nil +} + +func ffmpegURL() (url, archiveName string, err error) { + switch runtime.GOOS + "/" + runtime.GOARCH { + case "windows/amd64": + return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip", + "ffmpeg-win64-gpl.zip", nil + case "windows/arm64": + return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-winarm64-gpl.zip", + "ffmpeg-winarm64-gpl.zip", nil + case "linux/amd64": + return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz", + "ffmpeg-linux64-gpl.tar.xz", nil + case "linux/arm64": + return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz", + "ffmpeg-linuxarm64-gpl.tar.xz", nil + case "darwin/amd64", "darwin/arm64": + return "", "", fmt.Errorf("no static ffmpeg auto-build for macOS; install with: brew install ffmpeg") + default: + return "", "", fmt.Errorf("unsupported platform %s/%s for ffmpeg auto-download", runtime.GOOS, runtime.GOARCH) + } +} diff --git a/apps/streamd/internal/deps/fetch_mp4decrypt.go b/apps/streamd/internal/deps/fetch_mp4decrypt.go new file mode 100644 index 0000000..f662115 --- /dev/null +++ b/apps/streamd/internal/deps/fetch_mp4decrypt.go @@ -0,0 +1,50 @@ +package deps + +import ( + "fmt" + "os" + "path/filepath" + "runtime" +) + +// Official Bento4 SDK binaries from bento4.com (v1.6.0-641). +// linux/arm64 and windows/arm64 are not published there — clear error. +func fetchMP4Decrypt(binDir string, logf func(string, ...any)) (string, error) { + url, archiveName, err := bento4URL() + if err != nil { + return "", err + } + archivePath := filepath.Join(binDir, archiveName) + if err := downloadTo(url, archivePath, logf); err != nil { + return "", err + } + defer func() { _ = os.Remove(archivePath) }() + + want := "mp4decrypt" + if runtime.GOOS == "windows" { + want = "mp4decrypt.exe" + } + dest := filepath.Join(binDir, want) + if err := extractNamed(archivePath, binDir, want, dest); err != nil { + return "", err + } + chmodX(dest) + return dest, nil +} + +func bento4URL() (url, archiveName string, err error) { + const base = "https://www.bok.net/Bento4/binaries/" + switch runtime.GOOS + "/" + runtime.GOARCH { + case "windows/amd64": + name := "Bento4-SDK-1-6-0-641.x86_64-microsoft-win32.zip" + return base + name, name, nil + case "linux/amd64": + name := "Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip" + return base + name, name, nil + case "darwin/amd64", "darwin/arm64": + name := "Bento4-SDK-1-6-0-641.universal-apple-macosx.zip" + return base + name, name, nil + default: + return "", "", fmt.Errorf("no Bento4 binary for %s/%s (place mp4decrypt in bin/ manually)", runtime.GOOS, runtime.GOARCH) + } +} diff --git a/apps/streamd/internal/deps/fetch_nre.go b/apps/streamd/internal/deps/fetch_nre.go new file mode 100644 index 0000000..2c282b9 --- /dev/null +++ b/apps/streamd/internal/deps/fetch_nre.go @@ -0,0 +1,71 @@ +package deps + +import ( + "fmt" + "os" + "path/filepath" + "runtime" +) + +const nreTag = "v0.6.0-beta" +const nreBase = "https://github.com/nilaoda/N_m3u8DL-RE/releases/download/" + nreTag + "/" + +func fetchNRE(binDir string, logf func(string, ...any)) (string, error) { + url, archiveName, binName, err := nreURL() + if err != nil { + return "", err + } + archivePath := filepath.Join(binDir, archiveName) + if err := downloadTo(url, archivePath, logf); err != nil { + return "", err + } + defer func() { _ = os.Remove(archivePath) }() + + dest := filepath.Join(binDir, binName) + if err := extractNamed(archivePath, binDir, binName, dest); err != nil { + // Some archives nest the binary or use a slightly different name. + if err2 := extractNamed(archivePath, binDir, "N_m3u8DL-RE", dest); err2 != nil { + if runtime.GOOS == "windows" { + if err3 := extractNamed(archivePath, binDir, "N_m3u8DL-RE.exe", dest); err3 != nil { + return "", err + } + } else { + return "", err + } + } + } + chmodX(dest) + return dest, nil +} + +func nreURL() (url, archiveName, binName string, err error) { + binName = "N_m3u8DL-RE" + if runtime.GOOS == "windows" { + binName = "N_m3u8DL-RE.exe" + } + switch runtime.GOOS + "/" + runtime.GOARCH { + case "windows/amd64": + name := "N_m3u8DL-RE_v0.6.0-beta_win-x64_20260629.zip" + return nreBase + name, name, binName, nil + case "windows/arm64": + name := "N_m3u8DL-RE_v0.6.0-beta_win-arm64_20260629.zip" + return nreBase + name, name, binName, nil + case "windows/386": + name := "N_m3u8DL-RE_v0.6.0-beta_win-NT6.0-x86_20260629.zip" + return nreBase + name, name, binName, nil + case "linux/amd64": + name := "N_m3u8DL-RE_v0.6.0-beta_linux-x64_20260629.tar.gz" + return nreBase + name, name, binName, nil + case "linux/arm64": + name := "N_m3u8DL-RE_v0.6.0-beta_linux-arm64_20260629.tar.gz" + return nreBase + name, name, binName, nil + case "darwin/amd64": + name := "N_m3u8DL-RE_v0.6.0-beta_osx-x64_20260629.tar.gz" + return nreBase + name, name, binName, nil + case "darwin/arm64": + name := "N_m3u8DL-RE_v0.6.0-beta_osx-arm64_20260629.tar.gz" + return nreBase + name, name, binName, nil + default: + return "", "", "", fmt.Errorf("unsupported platform %s/%s for N_m3u8DL-RE auto-download", runtime.GOOS, runtime.GOARCH) + } +} diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go index b616146..74aad80 100644 --- a/apps/streamd/internal/supervisor/media.go +++ b/apps/streamd/internal/supervisor/media.go @@ -101,13 +101,13 @@ func (m *Media) Start(id int64) error { if err != nil { return err } - if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" { + if strings.TrimSpace(st.MPD) == "" { _ = m.Store.SetRuntime(id, db.RuntimePatch{ Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8", - LastError: "missing mpd/key - capture required", + LastError: "missing mpd — paste a manifest URL (keys optional for clear streams)", }) - return fmt.Errorf("missing mpd/key") + return fmt.Errorf("missing mpd") } mpdURL := strings.TrimSpace(st.MPD) if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") { @@ -151,9 +151,12 @@ func (m *Media) Start(id int64) error { } keysFile := filepath.Join(workDir, "keys.txt") - keysBody := normalizeKeysFile(st.Key) - if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil { - return err + hasKeys := strings.TrimSpace(st.Key) != "" + if hasKeys { + keysBody := normalizeKeysFile(st.Key) + if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil { + return err + } } saveName := st.Name @@ -167,7 +170,7 @@ func (m *Media) Start(id int64) error { // The rewriter is named by the stream row or its app module and looked up in // the mpd registry, so streamd needs no knowledge of any provider. if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS { - srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw) + srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy) if err != nil { _ = m.Store.SetRuntime(id, db.RuntimePatch{ Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8", @@ -189,12 +192,8 @@ func (m *Media) Start(id int64) error { liveWait := strconv.Itoa(cfg.LiveWait) nreArgs := []string{ manifestURL, - // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so - // always feed every KID:KEY via --key-text-file. - "--key-text-file", keysFile, "--live-real-time-merge", "--live-pipe-mux", - "--mp4-real-time-decryption", "--live-wait-time", liveWait, "--ffmpeg-binary-path", m.FFmpeg, "--save-name", saveName, @@ -204,6 +203,19 @@ func (m *Media) Start(id int64) error { "--log-level", "ERROR", "-ss", "0", } + if hasKeys { + // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so + // always feed every KID:KEY via --key-text-file. + nreArgs = append(nreArgs, + "--key-text-file", keysFile, + "--mp4-real-time-decryption", + ) + } + if proxy := strings.TrimSpace(st.Proxy); proxy != "" { + // NRE prefers --custom-proxy over the system proxy when both are set. + nreArgs = append(nreArgs, "--custom-proxy", proxy) + m.logf("stream %s: origin proxy %s", st.Name, proxy) + } // A synthetic manifest publishes exactly one video + audio pair, and an HLS // master's variants rarely match a resolution/language filter, so in both // cases take the best rendition instead of the configured selectors. @@ -212,7 +224,7 @@ func (m *Media) Start(id int64) error { } else { nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect) } - if m.MP4Decrypt != "" { + if hasKeys && m.MP4Decrypt != "" { nreArgs = append(nreArgs, "--decryption-engine", "MP4DECRYPT", "--decryption-binary-path", m.MP4Decrypt, diff --git a/apps/streamd/internal/supervisor/stub.go b/apps/streamd/internal/supervisor/stub.go index a847894..58eef69 100644 --- a/apps/streamd/internal/supervisor/stub.go +++ b/apps/streamd/internal/supervisor/stub.go @@ -27,13 +27,13 @@ func (s *Stub) Start(id int64) error { if err != nil { return err } - if st.MPD == "" || st.Key == "" { + if st.MPD == "" { _, err = s.Store.DB.Exec(` INSERT INTO stream_runtime(stream_id,health,play_path,last_error,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, last_error=excluded.last_error, updated_at=excluded.updated_at`, - id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd/key - capture required", time.Now().UTC().Format(time.RFC3339)) - return err + id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd", time.Now().UTC().Format(time.RFC3339)) + return fmt.Errorf("missing mpd") } pid := 10000 + int(id) s.pids[id] = pid diff --git a/apps/streamd/internal/ui/app.js b/apps/streamd/internal/ui/app.js index d42c50e..c754a02 100644 --- a/apps/streamd/internal/ui/app.js +++ b/apps/streamd/internal/ui/app.js @@ -63,7 +63,7 @@ } listMsg.textContent = streams.length + " stream(s)"; rowsEl.innerHTML = streams.map((s) => { - const need = !s.mpd || !s.key ? " needs capture" : ""; + const need = !s.mpd ? " needs MPD" : ""; return ` ${esc(s.name)}
${esc(s.title || "")}${need}
${esc(s.app)} / ${esc(s.channel)} @@ -98,6 +98,25 @@ agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", "); } + const depsEl = document.getElementById("deps-status"); + + function renderDeps(d) { + if (!depsEl || !d) return; + const bit = (label, path) => (path ? label + "✓" : label + "✗"); + depsEl.textContent = [ + bit("ffmpeg", d.ffmpeg), + bit("nre", d.nre), + bit("mp4decrypt", d.mp4decrypt), + ].join(" · "); + depsEl.title = [ + "bin: " + (d.bin_dir || ""), + "ffmpeg: " + (d.ffmpeg || "(missing)"), + "nre: " + (d.nre || "(missing)"), + "mp4decrypt: " + (d.mp4decrypt || "(missing)"), + ...(d.notes || []), + ].join("\n"); + } + async function refresh() { try { const [health, list, agents] = await Promise.all([ @@ -106,6 +125,7 @@ api("/api/agents").catch(() => ({ agents: [] })), ]); uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s"; + renderDeps(health.deps); render(list.streams || []); renderAgents(agents.agents || []); listMsg.classList.remove("err"); @@ -212,6 +232,7 @@ editForm.channel.value = st.channel || ""; editForm.mpd.value = st.mpd || ""; editForm.key.value = st.key || ""; + if (editForm.proxy) editForm.proxy.value = st.proxy || ""; editForm.headers_json.value = st.headers_json || "{}"; dlg.showModal(); return; @@ -238,6 +259,7 @@ channel: editForm.channel.value, mpd: editForm.mpd.value, key: editForm.key.value, + proxy: editForm.proxy ? editForm.proxy.value : "", headers_json: editForm.headers_json.value, }; try { diff --git a/apps/streamd/internal/ui/index.html b/apps/streamd/internal/ui/index.html index 6418772..0c0d5fd 100644 --- a/apps/streamd/internal/ui/index.html +++ b/apps/streamd/internal/ui/index.html @@ -11,6 +11,7 @@

streamd

+
@@ -26,8 +27,9 @@ - - + + +
@@ -70,7 +72,8 @@ - + +
diff --git a/apps/streamd/servecmd/servecmd.go b/apps/streamd/servecmd/servecmd.go index 51dfc61..1b2e6fb 100644 --- a/apps/streamd/servecmd/servecmd.go +++ b/apps/streamd/servecmd/servecmd.go @@ -17,6 +17,7 @@ import ( "drmdecryption/apps/streamd/internal/api" "drmdecryption/apps/streamd/internal/db" + "drmdecryption/apps/streamd/internal/deps" "drmdecryption/apps/streamd/internal/supervisor" "drmdecryption/apps/streamd/internal/ui" "drmdecryption/apps/streamd/internal/ws" @@ -54,9 +55,11 @@ serve flags: --bind listen address (default 0.0.0.0:8083) --data data dir for sqlite + www + work (default .cache/streamd) --token shared bearer token for mutating API (or STREAMD_TOKEN) - --nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH) - --ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH) - --mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH) + --nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download) + --ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download) + --mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download) + --bin-dir where to install/look for media tools (default /bin) + --skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt `) } @@ -68,6 +71,8 @@ func serveCmd(args []string) { nre := fs.String("nre", "", "N_m3u8DL-RE binary") ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary") mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary") + binDir := fs.String("bin-dir", "", "directory for media tool binaries (default /bin)") + skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools") _ = fs.Parse(args) dataDir := *data @@ -91,24 +96,14 @@ func serveCmd(args []string) { } defer store.Close() - nrePath := firstExisting(*nre, - os.Getenv("NRE_PATH"), - os.Getenv("N_M3U8DL_RE"), - filepath.Join("bin", "N_m3u8DL-RE.exe"), - "N_m3u8DL-RE", - ) - ffPath := firstExisting(*ffmpeg, - os.Getenv("FFMPEG_PATH"), - os.Getenv("FFMPEG"), - filepath.Join("bin", "ffmpeg.exe"), - "ffmpeg", - ) - decPath := firstExisting(*mp4decrypt, - os.Getenv("MP4DECRYPT_PATH"), - os.Getenv("MP4DECRYPT"), - filepath.Join("bin", "mp4decrypt.exe"), - "mp4decrypt", - ) + depStatus, _ := deps.Ensure(deps.Options{ + BinDir: *binDir, + SkipDownload: *skipDeps, + Log: log.Default(), + }, *nre, *ffmpeg, *mp4decrypt) + nrePath := depStatus.NRE + ffPath := depStatus.FFmpeg + decPath := depStatus.MP4Decrypt sup := supervisor.NewMedia(supervisor.Options{ Store: store, @@ -125,6 +120,7 @@ func serveCmd(args []string) { Token: tok, Supervisor: sup, StartedAt: time.Now(), + Deps: depStatus, } hub := ws.NewHub(store, tok, log.Default()) @@ -161,7 +157,7 @@ func serveCmd(args []string) { return } for _, st := range list { - if !st.Enabled || strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" { + if !st.Enabled || strings.TrimSpace(st.MPD) == "" { continue } mpd := strings.ToLower(strings.TrimSpace(st.MPD)) diff --git a/configs/.gitkeep b/configs/.gitkeep new file mode 100644 index 0000000..2aa133a --- /dev/null +++ b/configs/.gitkeep @@ -0,0 +1,2 @@ +# Optional local configs + diff --git a/docs/streamd.md b/docs/streamd.md index ab69bcc..a1958ac 100644 --- a/docs/streamd.md +++ b/docs/streamd.md @@ -14,19 +14,36 @@ run` keeps credentials fresh using real phones. | `--bind` | `0.0.0.0:8083` | listen address | | `--data` | `.cache/streamd` | SQLite, work dirs, HLS output, logs | | `--token` | `$STREAMD_TOKEN` | bearer token for mutating routes | -| `--nre` | `$NRE_PATH`, `bin/`, `PATH` | downloader binary | -| `--ffmpeg` | `$FFMPEG_PATH`, `bin/`, `PATH` | ffmpeg | -| `--mp4decrypt` | `$MP4DECRYPT_PATH`, `bin/`, `PATH` | decrypter | +| `--nre` | `$NRE_PATH`, `bin/`, `PATH`, auto-download | N_m3u8DL-RE | +| `--ffmpeg` | `$FFMPEG_PATH`, `bin/`, `PATH`, auto-download | ffmpeg | +| `--mp4decrypt` | `$MP4DECRYPT_PATH`, `bin/`, `PATH`, auto-download | Bento4 mp4decrypt | +| `--bin-dir` | `/bin` | where auto-downloaded tools are installed | +| `--skip-deps` | off | do not download missing tools | + +On start, `serve` resolves media tools and **downloads** ffmpeg (BtbN static), +N_m3u8DL-RE (v0.6.0-beta), and mp4decrypt (Bento4) into `bin/` when missing. +macOS ffmpeg is not auto-fetched — install with `brew install ffmpeg`. Open . GET routes are unauthenticated; anything mutating -needs `Authorization: Bearer `. +needs `Authorization: Bearer `. The header shows ffmpeg / NRE / mp4decrypt +status from `/api/health` → `deps`. + +### Keys and proxy + +- **MPD** is required to start. **Keys are optional** (clear streams such as BBC). +- Per-stream **`proxy`** (`socks5://127.0.0.1:1080` or `http://…`) is passed to + N_m3u8DL-RE as `--custom-proxy` so origin fetches can egress via a UK SOCKS + sidecar while the host itself stays elsewhere. The local MPD rewrite fetch + uses the same proxy. Outbound HLS you serve is unaffected. ### API | Route | Purpose | |---|---| -| `GET /api/health` | liveness + uptime | -| `GET /api/apps` | compiled-in modules, their channels, registered rewriters | +| `GET /api/health` | liveness + uptime + `deps` paths | +| `GET /api/apps` | modules under `modules/`, their channels, registered rewriters | +| `GET /api/modules` | list `modules//` with `has_yaml` + `yaml_sha256` | +| `PUT /api/modules/:name` | write `modules//module.yaml` (bearer; raw YAML or `{"yaml":…}`) | | `GET /api/streams` | all streams with runtime state | | `POST /api/streams` | create | | `PATCH /api/streams/:id` | update | diff --git a/modules/README.md b/modules/README.md index c54b0b6..fc2c5e8 100644 --- a/modules/README.md +++ b/modules/README.md @@ -17,10 +17,11 @@ modules/ | File | Published? | Purpose | |---|---|---| -| `module-publish.yaml` | yes (in git + release zips) | Universal package/channels/UI | -| `module.yaml` | **no** | Operator secrets; overlays publish at runtime | +| `module-publish.yaml` | yes (in git only) | Universal package/channels/UI | +| `module.yaml` | **no** (gitignored locally) | Operator secrets; overlays publish at runtime | -Release zips rename `module-publish.yaml` → `module.yaml` so end users edit one file. +Release zips ship **`module.yaml` only** (publish template renamed). They do **not** +include `module-publish.yaml`. ## Commands @@ -33,7 +34,7 @@ DRM_MODULES_DIR=D:\mods drm capture --app rte --channel rteone ## Releases -Push a `modules-v*` tag to publish per-module zips (`module-bbc-….zip`, …) via +Push a `modules-v*` tag to publish per-module zips (`bbc.zip`, `rte.zip`, `tg4.zip`) via Forgejo Actions. Host `drm` stays on separate `v*` tags. Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt. diff --git a/modules/rte/module-publish.yaml b/modules/rte/module-publish.yaml index a70fe79..41cf041 100644 --- a/modules/rte/module-publish.yaml +++ b/modules/rte/module-publish.yaml @@ -50,8 +50,9 @@ channels: # vc12: "…" ui: - launch_desc_contains: ["live tab", "header logo", "Live"] - live_tab_desc_re: ["Live tab", "Live"] + # "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab. + launch_desc_contains: ["live tab", "header logo", "Home tab"] + live_tab_desc_re: ["^Live tab"] timeouts: launch_wait_ui: 30s diff --git a/scripts/build-modules-release.ps1 b/scripts/build-modules-release.ps1 index 7a080ae..a09c18d 100644 --- a/scripts/build-modules-release.ps1 +++ b/scripts/build-modules-release.ps1 @@ -74,16 +74,14 @@ foreach ($name in $Modules) { Remove-Item Env:GOOS, Env:GOARCH, Env:CGO_ENABLED -ErrorAction SilentlyContinue } - # Release zip gets module.yaml (= publish template, secrets empty/placeholders). + # Release zip ships module.yaml only (= publish template renamed; no secrets). Copy-Item $publish (Join-Path $stage "module.yaml") -Force - # Also keep the publish name for clarity. - Copy-Item $publish (Join-Path $stage "module-publish.yaml") -Force $readme = @" -# module-$name ($Version) +# $name ($Version) -Drop this folder into your Null DRM ``modules/$name/`` directory (or point -``drm --modules-dir`` at a folder that contains ``$name/``). +Unpack this zip into your Null DRM ``modules/$name/`` directory (or point +``drm --modules-dir`` at a parent that contains ``$name/``). 1. Edit ``module.yaml`` — fill in any sensitive fields marked in comments. 2. Copy the matching ``.bin/-/$name[.exe]`` up to ``.bin/$name[.exe]`` @@ -91,12 +89,12 @@ Drop this folder into your Null DRM ``modules/$name/`` directory (or point if Go is installed. 3. Run: ``drm modules`` then ``drm capture --app $name --channel …`` -Local ``module.yaml`` with secrets must never be committed. This zip's -``module.yaml`` is a rename of ``module-publish.yaml`` (universal values only). +This zip's ``module.yaml`` is the published universal template (secrets empty). +Do not commit a local ``module.yaml`` that contains secrets. "@ Set-Content -Path (Join-Path $stage "README.md") -Value $readme -Encoding utf8 - $zipName = "module-$name-$Version.zip" + $zipName = "$name.zip" $zipPath = Join-Path $Out $zipName if (Test-Path $zipPath) { Remove-Item -Force $zipPath } Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force @@ -113,4 +111,4 @@ foreach ($z in $builtZips) { } [System.IO.File]::WriteAllLines($sumsPath, $lines) Write-Host "DONE modules release $Version → $Out" -Get-ChildItem $Out -Filter "module-*" | Format-Table Name, Length +Get-ChildItem $Out -Filter "*.zip" | Where-Object { $_.Name -match '^(bbc|rte|tg4)\.zip$' } | Format-Table Name, Length diff --git a/scripts/build-modules-release.sh b/scripts/build-modules-release.sh index 14e20ba..190b444 100644 --- a/scripts/build-modules-release.sh +++ b/scripts/build-modules-release.sh @@ -41,18 +41,18 @@ for name in "${MODULES[@]}"; do go build -trimpath -ldflags='-s -w' -o "$bin" . ) done <<< "$(printf '%s\n' "${TARGETS[@]}")" + # Ship module.yaml only (= publish template renamed; no secrets, no module-publish.yaml). cp "$publish" "$stage/module.yaml" - cp "$publish" "$stage/module-publish.yaml" cat > "$stage/README.md" <-/$name\` to \`.bin/$name\` for your OS, or rebuild with Go. -\`module.yaml\` in this zip is \`module-publish.yaml\` renamed (universal values). +This zip's \`module.yaml\` is the published universal template (secrets empty). EOF - zip_path="$OUT/module-${name}-${VERSION}.zip" + zip_path="$OUT/${name}.zip" rm -f "$zip_path" ( cd "$stage" && zip -qr "$zip_path" . ) built+=("$zip_path") @@ -65,4 +65,4 @@ for z in "${built[@]}"; do ( cd "$(dirname "$z")" && sha256sum "$(basename "$z")" ) >> "$sums" done echo "DONE modules release $VERSION → $OUT" -ls -la "$OUT"/module-* 2>/dev/null || true +ls -la "$OUT"/bbc.zip "$OUT"/rte.zip "$OUT"/tg4.zip 2>/dev/null || true diff --git a/scripts/notify-telegram.ps1 b/scripts/notify-telegram.ps1 new file mode 100644 index 0000000..7fd9e0b --- /dev/null +++ b/scripts/notify-telegram.ps1 @@ -0,0 +1,95 @@ +# Post a release announce to Telegram. +# +# Required env: +# TELEGRAM_BOT_TOKEN BotFather token (never commit) +# TELEGRAM_CHAT_ID e.g. -1003721978702 +# +# Usage: +# $env:TELEGRAM_BOT_TOKEN="…"; $env:TELEGRAM_CHAT_ID="-1003721978702" +# .\scripts\notify-telegram.ps1 -Tag v0.1.2 +# .\scripts\notify-telegram.ps1 -Tag modules-v0.1.2 -DryRun +param( + [string]$Tag = "", + [string]$Kind = "auto", # auto | host | modules + [string]$Title = "", + [string]$Body = "", + [string]$ReleaseUrl = "", + [string]$RepoUrl = "https://git.nulldrm.com/nulldrm/Null-DRM-Official", + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +$Root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) + +if (-not $Tag) { $Tag = $env:RELEASE_TAG } +if (-not $Tag) { + try { $Tag = (git -C $Root describe --tags --exact-match 2>$null) } catch { } +} +if (-not $Tag) { + try { $Tag = (git -C $Root describe --tags --always 2>$null) } catch { } +} +if (-not $Tag) { throw "usage: notify-telegram.ps1 -Tag v0.1.2" } + +$Token = $env:TELEGRAM_BOT_TOKEN +$Chat = $env:TELEGRAM_CHAT_ID +if (-not $Token -or -not $Chat) { + throw "TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are required" +} + +if ($Kind -eq "auto") { + if ($Tag -like "modules-v*") { $Kind = "modules" } else { $Kind = "host" } +} + +if (-not $ReleaseUrl) { + if ($env:RELEASE_URL) { $ReleaseUrl = $env:RELEASE_URL } + else { $ReleaseUrl = "$RepoUrl/releases/tag/$Tag" } +} + +if (-not $Title) { + if ($env:RELEASE_TITLE) { $Title = $env:RELEASE_TITLE } + elseif ($Kind -eq "modules") { $Title = "Null DRM $Tag" } + else { $Title = "Null DRM $Tag" } +} + +if (-not $Body) { + if ($env:RELEASE_BODY) { + $Body = $env:RELEASE_BODY + } elseif ($Kind -eq "modules") { + $Body = @" +$Title +Provider module zips: bbc.zip, rte.zip, tg4.zip + +Unpack each into modules/<name>/ and edit module.yaml for secrets. + +Download $Tag +"@ + } else { + $Body = @" +$Title +Host CLI (drm) + on-device MITM (proxy-android-arm64). + +Download $Tag +"@ + } +} + +if ($DryRun) { + Write-Host "DRY_RUN chat=$Chat tag=$Tag kind=$Kind" + Write-Host "----" + Write-Host $Body + return +} + +Write-Host "[*] Telegram notify → chat $Chat ($Tag)" +$uri = "https://api.telegram.org/bot$Token/sendMessage" +$form = @{ + chat_id = $Chat + text = $Body + parse_mode = "HTML" + disable_web_page_preview = "false" +} +$resp = Invoke-RestMethod -Method Post -Uri $uri -Body $form +if (-not $resp.ok) { + throw "Telegram API error: $($resp | ConvertTo-Json -Compress)" +} +Write-Host "[+] Telegram announce sent for $Tag (message_id=$($resp.result.message_id))" diff --git a/scripts/notify-telegram.sh b/scripts/notify-telegram.sh new file mode 100644 index 0000000..03a7228 --- /dev/null +++ b/scripts/notify-telegram.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Post a release announce to Telegram. +# +# Required env: +# TELEGRAM_BOT_TOKEN BotFather token (Forgejo secret / local env — never commit) +# TELEGRAM_CHAT_ID Channel chat id, e.g. -1003721978702 +# +# Optional: +# RELEASE_TAG / first arg tag name +# RELEASE_URL release page URL +# RELEASE_TITLE headline override +# RELEASE_BODY full HTML body override +# RELEASE_KIND host | modules | auto +# RELEASE_REPO_URL default https://git.nulldrm.com/nulldrm/Null-DRM-Official +# DRY_RUN=1 print, do not send +# +# Usage: +# TELEGRAM_BOT_TOKEN=… TELEGRAM_CHAT_ID=… ./scripts/notify-telegram.sh v0.1.2 +# TELEGRAM_BOT_TOKEN=… TELEGRAM_CHAT_ID=… ./scripts/notify-telegram.sh modules-v0.1.2 +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +TAG="${1:-${RELEASE_TAG:-}}" +if [[ -z "$TAG" ]]; then + TAG="$(git -C "$ROOT" describe --tags --exact-match 2>/dev/null || git -C "$ROOT" describe --tags --always 2>/dev/null || true)" +fi +if [[ -z "$TAG" ]]; then + echo "usage: $0 " >&2 + exit 2 +fi + +TOKEN="${TELEGRAM_BOT_TOKEN:-}" +CHAT="${TELEGRAM_CHAT_ID:-}" +if [[ -z "$TOKEN" || -z "$CHAT" ]]; then + echo "TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are required" >&2 + exit 1 +fi + +KIND="${RELEASE_KIND:-auto}" +if [[ "$KIND" == "auto" ]]; then + case "$TAG" in + modules-v*) KIND="modules" ;; + *) KIND="host" ;; + esac +fi + +REPO_URL="${RELEASE_REPO_URL:-https://git.nulldrm.com/nulldrm/Null-DRM-Official}" +URL="${RELEASE_URL:-${REPO_URL}/releases/tag/${TAG}}" + +if [[ -n "${RELEASE_TITLE:-}" ]]; then + TITLE="$RELEASE_TITLE" +else + TITLE="Null DRM ${TAG}" +fi + +if [[ -n "${RELEASE_BODY:-}" ]]; then + BODY="$RELEASE_BODY" +elif [[ "$KIND" == "modules" ]]; then + BODY="${TITLE} +Provider module zips: bbc.zip, rte.zip, tg4.zip + +Unpack each into modules/<name>/ and edit module.yaml for secrets. + +Download ${TAG}" +else + BODY="${TITLE} +Host CLI (drm) + on-device MITM (proxy-android-arm64). + +Download ${TAG}" +fi + +if [[ "${DRY_RUN:-}" == "1" ]]; then + echo "DRY_RUN chat=$CHAT tag=$TAG kind=$KIND" + echo "----" + echo "$BODY" + exit 0 +fi + +echo "[*] Telegram notify → chat $CHAT ($TAG)" +RESP=$(curl -sS -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${CHAT}" \ + --data-urlencode "text=${BODY}" \ + --data-urlencode "parse_mode=HTML" \ + --data-urlencode "disable_web_page_preview=false") + +case "$RESP" in + *"\"ok\":true"*|*"\"ok\": true"*) + echo "[+] Telegram announce sent for $TAG" + ;; + *) + echo "Telegram API error:" >&2 + echo "$RESP" >&2 + exit 1 + ;; +esac