streamd: optional keys, per-stream proxy, auto deps; agent module.yaml sync; RTE AutoPlay; Telegram release announces
All checks were successful
release / build-and-upload (push) Successful in 6m20s
modules-release / build-and-upload (push) Successful in 4m51s

- 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
This commit is contained in:
404errordeveloper 2026-10-09 00:17:23 +02:00
parent f9c28be3f1
commit ac8701b5a6
36 changed files with 1460 additions and 143 deletions

View file

@ -51,11 +51,28 @@ jobs:
| Asset | Contents | | Asset | Contents |
|---|---| |---|---|
| `module-bbc-*.zip` | BBC iPlayer CLI + `module.yaml` (universal) | | `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) |
| `module-rte-*.zip` | RTÉ Player CLI + `module.yaml` template | | `rte.zip` | RTÉ Player CLI + `module.yaml` template |
| `module-tg4-*.zip` | TG4 CLI + `module.yaml` template | | `tg4.zip` | TG4 CLI + `module.yaml` template |
| `SHA256SUMS-modules.txt` | Checksums | | `SHA256SUMS-modules.txt` | Checksums |
Unpack each zip into `modules/<name>/`. Fill sensitive fields in Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`).
`module.yaml`. Host `drm` is released separately on `v*` tags. 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`. 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 }}"

View file

@ -67,3 +67,18 @@ jobs:
Built with `CGO_ENABLED=0` via `scripts/build-release.sh`. Built with `CGO_ENABLED=0` via `scripts/build-release.sh`.
Phone capture still needs Magisk + `drm proxy install-ca --reinject`. 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 }}"

2
.gitignore vendored
View file

@ -224,6 +224,8 @@ scripts/*
!scripts/build-release.ps1 !scripts/build-release.ps1
!scripts/build-modules-release.sh !scripts/build-modules-release.sh
!scripts/build-modules-release.ps1 !scripts/build-modules-release.ps1
!scripts/notify-telegram.sh
!scripts/notify-telegram.ps1
# Shared library packages under apps/modules/ (imported by external module CLIs). # Shared library packages under apps/modules/ (imported by external module CLIs).
# module.yaml stays local; module-publish.yaml is the tracked universal template. # module.yaml stays local; module-publish.yaml is the tracked universal template.
apps/modules/** apps/modules/**

View file

@ -15,14 +15,14 @@ Docs: [docs/](docs/)
From the latest **`v*`** release, grab your host binary (e.g. `drm-windows-amd64.exe`) 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 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 ```text
Null-DRM/ Null-DRM/
drm.exe # or drm on Linux/macOS drm.exe # or drm on Linux/macOS
bin/proxy-android-arm64 # optional; also embedded in release drm bin/proxy-android-arm64 # optional; also embedded in release drm
modules/ modules/
bbc/ # unzip module-bbc-*.zip here bbc/ # unzip bbc.zip here
rte/ rte/
tg4/ tg4/
data/ # your .wvd, optional data/ # your .wvd, optional
@ -109,10 +109,11 @@ Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
| File | In git / zips? | Purpose | | File | In git / zips? | Purpose |
|---|---|---| |---|---|---|
| `module-publish.yaml` | yes | Universal package, channels, UI | | `module-publish.yaml` | git only | Universal package, channels, UI |
| `module.yaml` | **no** (local) | Secrets + overrides; overlays publish | | `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).
--- ---

View file

@ -1,7 +1,7 @@
# Always-on credentials agent (apps/agent → bin/agent.exe) # Always-on credentials agent (apps/agent → bin/agent.exe)
# Default path: apps/agent/agent.yaml # Default path: apps/agent/agent.yaml
streamd_url: http://127.0.0.1:8083 streamd_url: http://185.18.221.132:8083
# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials). # Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials, modules).
token: "SECRET" token: "SECRET"
# Stable id across restarts (default = hostname). Required for reclaim after crash. # Stable id across restarts (default = hostname). Required for reclaim after crash.
# agent_id: my-agent # agent_id: my-agent
@ -11,8 +11,10 @@ workers: 1 # concurrent ADB jobs
max_attempts: 5 max_attempts: 5
capture_wait_sec: 180 capture_wait_sec: 180
devices: [] # empty = all adb "device" serials; never installs apps devices: [] # empty = all adb "device" serials; never installs apps
# Push local modules/<name>/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) # wvd: data/device.wvd # path to .wvd (required for key fetch)
# user_agent: "" # optional license-request User-Agent # 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/<name>/module.yaml; see apps/modules/README.md.

View file

@ -15,6 +15,7 @@ import (
"drmdecryption/apps/agent/internal/client" "drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/config" "drmdecryption/apps/agent/internal/config"
"drmdecryption/apps/agent/internal/device" "drmdecryption/apps/agent/internal/device"
"drmdecryption/apps/agent/internal/modsync"
"drmdecryption/apps/agent/internal/poller" "drmdecryption/apps/agent/internal/poller"
"drmdecryption/apps/agent/internal/queue" "drmdecryption/apps/agent/internal/queue"
"drmdecryption/apps/agent/internal/worker" "drmdecryption/apps/agent/internal/worker"
@ -116,6 +117,17 @@ func runCmd(sub string, args []string) {
} }
go p.Loop(stop) 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()) ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
go ws.Loop() go ws.Loop()

View file

@ -85,6 +85,50 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
return err return err
} }
// ModuleInfo is one modules/<name>/ 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) { func (c *Client) do(method, path string, payload any) ([]byte, error) {
var rdr io.Reader var rdr io.Reader
if payload != nil { if payload != nil {

View file

@ -23,6 +23,10 @@ type Config struct {
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch) WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
UserAgent string `yaml:"user_agent"` UserAgent string `yaml:"user_agent"`
AgentID string `yaml:"agent_id"` AgentID string `yaml:"agent_id"`
// SyncModules pushes local modules/<name>/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 { func (c Config) PollInterval() time.Duration {
@ -100,5 +104,18 @@ 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.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
}
if cfg.ModulesSyncIntervalSec <= 0 {
cfg.ModulesSyncIntervalSec = 300
}
return cfg return cfg
} }
func (c Config) ModulesSyncInterval() time.Duration {
if c.ModulesSyncIntervalSec <= 0 {
return 5 * time.Minute
}
return time.Duration(c.ModulesSyncIntervalSec) * time.Second
}

View file

@ -0,0 +1,121 @@
// Package modsync pushes local modules/<name>/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...)
}

View file

@ -87,10 +87,12 @@ func (c Config) withDefaults() Config {
t.AfterLiveTab = provider.Duration(t.AfterLiveTab.D(2 * time.Second)) t.AfterLiveTab = provider.Duration(t.AfterLiveTab.D(2 * time.Second))
t.AfterChip = provider.Duration(t.AfterChip.D(2 * time.Second)) t.AfterChip = provider.Duration(t.AfterChip.D(2 * time.Second))
if len(c.UI.LaunchDescContains) == 0 { 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 { 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() c.Synthetic = c.Synthetic.WithDefaults()
return c return c

View file

@ -50,8 +50,9 @@ channels:
# vc12: "…" # vc12: "…"
ui: ui:
launch_desc_contains: ["live tab", "header logo", "Live"] # "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab.
live_tab_desc_re: ["Live tab", "Live"] launch_desc_contains: ["live tab", "header logo", "Home tab"]
live_tab_desc_re: ["^Live tab"]
timeouts: timeouts:
launch_wait_ui: 30s launch_wait_ui: 30s

View file

@ -84,7 +84,7 @@ func (a *App) Launch(c *adb.Client) error {
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)) }, 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 { func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel) id, err := a.Resolve(channel)
if err != nil { 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)) fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
c.DismissShadeIfFocused() c.DismissShadeIfFocused()
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{ if err := a.openLiveTab(c); err != nil {
DescRE: a.cfg.UI.LiveTabDescRE, return err
}, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil {
return fmt.Errorf("live tab: %w", err)
} }
time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab))
if err := a.tapChipThenPlay(c, ch); err != nil { if err := a.tapChipThenPlay(c, ch); err != nil {
return err return err
} }

View file

@ -9,9 +9,58 @@ import (
"drmdecryption/uiflow" "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 // 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 // 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 { func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
playPats := uiflow.CompileRes(ch.PlayDesc) playPats := uiflow.CompileRes(ch.PlayDesc)
chipPats := uiflow.CompileRes(ch.ChipDesc) chipPats := uiflow.CompileRes(ch.ChipDesc)
@ -21,18 +70,30 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
return err return err
} }
if cand := a.findHeroPlay(nodes, playPats); cand != nil { if cand := a.findHeroPlay(nodes, playPats); cand != nil {
fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY()) x, y := playTapXY(cand)
return c.Tap(cand.CX(), cand.CY()) fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
return c.Tap(x, y)
} }
chip := adb.FindSmallest(nodes, chipPats) chip := adb.FindSmallest(nodes, chipPats)
if chip == nil { if chip == nil {
chip, err = c.WaitFor(a.CacheDir(), nil, chipPats, time.Duration(a.cfg.Timeouts.ChipWait)) deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ChipWait))
if err != nil { for time.Now().Before(deadline) {
return fmt.Errorf("chip not found: %w", err) 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()) _ = c.Tap(chip.CX(), chip.CY())
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChip)) 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()) nodes, err = c.DumpUI(a.CacheDir())
if err == nil { if err == nil {
if cand := a.findHeroPlay(nodes, playPats); cand != nil { if cand := a.findHeroPlay(nodes, playPats); cand != nil {
fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY()) x, y := playTapXY(cand)
return c.Tap(cand.CX(), cand.CY()) fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
return c.Tap(x, y)
} }
} }
time.Sleep(700 * time.Millisecond) 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 // 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 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
}

View file

@ -5,6 +5,7 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"net/url"
"strings" "strings"
"time" "time"
) )
@ -27,22 +28,28 @@ type Primer interface {
type LocalServer struct { type LocalServer struct {
URL string URL string
Upstream string Upstream string
Key string // KID:KEY Key string // KID:KEY (optional for clear streams)
Headers map[string]string Headers map[string]string
Proxy string // optional socks5:// or http:// for upstream fetch
rw Rewriter rw Rewriter
kidHint string kidHint string
ln net.Listener ln net.Listener
httpServer *http.Server httpServer *http.Server
client *http.Client
} }
// StartLocal starts the rewrite proxy. rw must not be nil; pass Passthrough{} // StartLocal starts the rewrite proxy. rw must not be nil; pass Passthrough{}
// to serve upstream unchanged. // to serve upstream unchanged. proxyURL may be empty, or socks5:// / http://.
func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*LocalServer, error) { func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, proxyURL ...string) (*LocalServer, error) {
if rw == nil { if rw == nil {
rw = Passthrough{} 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, ":") { if key != "" && strings.Contains(key, ":") {
s.kidHint = strings.SplitN(key, ":", 2)[0] s.kidHint = strings.SplitN(key, ":", 2)[0]
if r, ok := rw.(KIDResolver); ok { 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") ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
return nil, err return nil, err
@ -66,6 +78,18 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*
return s, nil 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() { func (s *LocalServer) Close() {
if s.httpServer != nil { if s.httpServer != nil {
_ = s.httpServer.Close() _ = s.httpServer.Close()
@ -82,7 +106,10 @@ func (s *LocalServer) handle(w http.ResponseWriter, r *http.Request) {
for k, v := range s.Headers { for k, v := range s.Headers {
req.Header.Set(k, v) 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 { if resp, err := client.Do(req); err == nil {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
_ = resp.Body.Close() _ = resp.Body.Close()

View file

@ -19,11 +19,13 @@ apps/streamd/
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET ./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 Port 8083 by default, to stay clear of anything already on 8080/8081. On start,
resolve from flags, then env (`NRE_PATH` / `FFMPEG_PATH` / `MP4DECRYPT_PATH`), then missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt)
`bin/`, then `PATH` — no machine-specific paths are baked in. 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. 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 ## API
@ -35,7 +37,7 @@ Open `http://HOST:8083/` and put the token in the header box for mutating action
| POST | `/api/streams` | create | | POST | `/api/streams` | create |
| GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete | | GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete |
| POST | `/api/streams/:id/start\|stop\|restart` | desired state | | 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` | agent lease (`agent_id`, TTL ~3m) |
| POST | `/api/streams/:id/claim/release` | release lease | | POST | `/api/streams/:id/claim/release` | release lease |

View file

@ -10,6 +10,7 @@ import (
"time" "time"
"drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps"
) )
type Supervisor interface { type Supervisor interface {
@ -23,6 +24,7 @@ type Handler struct {
Token string Token string
Supervisor Supervisor Supervisor Supervisor
StartedAt time.Time StartedAt time.Time
Deps deps.Status
} }
func (h *Handler) Mount(mux *http.ServeMux) { 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.streams)
mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/streams/", h.streamAction)
mux.HandleFunc("/api/apps", h.apps) 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 { 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", "service": "streamd",
"uptime_s": time.Since(h.StartedAt).Seconds(), "uptime_s": time.Since(h.StartedAt).Seconds(),
"started_at": h.StartedAt.UTC().Format(time.RFC3339), "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}) writeJSON(w, code, map[string]any{"error": msg})
} }
// credentialsChanged is true when the patch touched mpd, key, or headers that // credentialsChanged is true when the patch touched mpd, key, headers, or proxy
// the live NRE/ffmpeg worker is already using. // that the live NRE/ffmpeg worker is already using.
func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) { if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) {
return true 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) { if in.HeadersJSON != nil && strings.TrimSpace(before.HeadersJSON) != strings.TrimSpace(after.HeadersJSON) {
return true return true
} }
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
return true
}
return false return false
} }

View file

@ -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/<name>/ 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
}
}

View file

@ -25,6 +25,7 @@ type Stream struct {
MPD string `json:"mpd"` MPD string `json:"mpd"`
Key string `json:"key"` Key string `json:"key"`
HeadersJSON string `json:"headers_json"` HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
VideoSelect string `json:"video_select"` VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"` AudioSelect string `json:"audio_select"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
@ -53,6 +54,7 @@ type CreateStream struct {
MPD string `json:"mpd"` MPD string `json:"mpd"`
Key string `json:"key"` Key string `json:"key"`
HeadersJSON string `json:"headers_json"` HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"`
VideoSelect string `json:"video_select"` VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"` AudioSelect string `json:"audio_select"`
Rewriter string `json:"rewriter"` Rewriter string `json:"rewriter"`
@ -66,6 +68,7 @@ type PatchStream struct {
MPD *string `json:"mpd"` MPD *string `json:"mpd"`
Key *string `json:"key"` Key *string `json:"key"`
HeadersJSON *string `json:"headers_json"` HeadersJSON *string `json:"headers_json"`
Proxy *string `json:"proxy"`
VideoSelect *string `json:"video_select"` VideoSelect *string `json:"video_select"`
AudioSelect *string `json:"audio_select"` AudioSelect *string `json:"audio_select"`
Rewriter *string `json:"rewriter"` Rewriter *string `json:"rewriter"`
@ -74,7 +77,7 @@ type PatchStream struct {
type Credentials struct { type Credentials struct {
MPD string `json:"mpd"` MPD string `json:"mpd"`
Key string `json:"key"` Key string `json:"key"` // optional for clear streams
PSSH string `json:"pssh,omitempty"` PSSH string `json:"pssh,omitempty"`
Auth string `json:"auth,omitempty"` Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"` PID string `json:"pid,omitempty"`
@ -114,6 +117,7 @@ CREATE TABLE IF NOT EXISTS streams (
mpd TEXT NOT NULL DEFAULT '', mpd TEXT NOT NULL DEFAULT '',
key_kid_key TEXT NOT NULL DEFAULT '', key_kid_key TEXT NOT NULL DEFAULT '',
headers_json TEXT NOT NULL DEFAULT '{}', headers_json TEXT NOT NULL DEFAULT '{}',
proxy TEXT NOT NULL DEFAULT '',
video_select TEXT NOT NULL DEFAULT '', video_select TEXT NOT NULL DEFAULT '',
audio_select TEXT NOT NULL DEFAULT '', audio_select TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 0, enabled INTEGER NOT NULL DEFAULT 0,
@ -141,7 +145,12 @@ CREATE TABLE IF NOT EXISTS agent_claims (
expires_at TEXT NOT NULL 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 { func now() string {
@ -166,18 +175,19 @@ func slug(name string) string {
return out return out
} }
func (s *Store) ListStreams() ([]Stream, error) { const streamSelect = `
rows, err := s.DB.Query(`
SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json, 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.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.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
COALESCE(r.last_error,''), COALESCE(r.updated_at,''), COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
COALESCE(c.agent_id,''), COALESCE(c.expires_at,'') COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
FROM streams s FROM streams s
LEFT JOIN stream_runtime r ON r.stream_id = s.id LEFT JOIN stream_runtime r ON r.stream_id = s.id
LEFT JOIN agent_claims c ON c.stream_id = s.id LEFT JOIN agent_claims c ON c.stream_id = s.id`
ORDER BY s.name`)
func (s *Store) ListStreams() ([]Stream, error) {
rows, err := s.DB.Query(streamSelect + ` ORDER BY s.name`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -194,17 +204,7 @@ ORDER BY s.name`)
} }
func (s *Store) GetStream(id int64) (Stream, error) { func (s *Store) GetStream(id int64) (Stream, error) {
row := s.DB.QueryRow(` row := s.DB.QueryRow(streamSelect+` WHERE s.id = ?`, id)
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)
return scanStream(row) return scanStream(row)
} }
@ -217,7 +217,7 @@ func scanStream(row rowScanner) (Stream, error) {
var enabled int var enabled int
err := row.Scan( err := row.Scan(
&st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON, &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.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS,
&st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp, &st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp,
) )
@ -264,9 +264,9 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
} }
ts := now() ts := now()
res, err := s.DB.Exec(` 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) 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(?,?,?,?,?,?,?,?,?,?,?,?,?)`, VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, 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) in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, ts, ts)
if err != nil { if err != nil {
return Stream{}, err return Stream{}, err
@ -303,6 +303,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
} }
cur.HeadersJSON = *in.HeadersJSON cur.HeadersJSON = *in.HeadersJSON
} }
if in.Proxy != nil {
cur.Proxy = strings.TrimSpace(*in.Proxy)
}
if in.VideoSelect != nil { if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect cur.VideoSelect = *in.VideoSelect
} }
@ -325,9 +328,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
} }
ts := now() ts := now()
_, err = s.DB.Exec(` _, 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=?`, 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) cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, ts, id)
if err != nil { if err != nil {
return Stream{}, err 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) { func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
if strings.TrimSpace(cred.MPD) == "" || strings.TrimSpace(cred.Key) == "" { mpd := strings.TrimSpace(cred.MPD)
return Stream{}, fmt.Errorf("mpd and key required") 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=?`, _, 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 { if err != nil {
return Stream{}, err return Stream{}, err
} }

View file

@ -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)
}

View file

@ -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 → <repo.Root()>/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)
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -101,13 +101,13 @@ func (m *Media) Start(id int64) error {
if err != nil { if err != nil {
return err return err
} }
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" { if strings.TrimSpace(st.MPD) == "" {
_ = m.Store.SetRuntime(id, db.RuntimePatch{ _ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", Health: "down",
PlayPath: "/hls/" + st.Name + "/index.m3u8", 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) mpdURL := strings.TrimSpace(st.MPD)
if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") { 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") keysFile := filepath.Join(workDir, "keys.txt")
keysBody := normalizeKeysFile(st.Key) hasKeys := strings.TrimSpace(st.Key) != ""
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil { if hasKeys {
return err keysBody := normalizeKeysFile(st.Key)
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
return err
}
} }
saveName := st.Name 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 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. // 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 { 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 { if err != nil {
_ = m.Store.SetRuntime(id, db.RuntimePatch{ _ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8", Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8",
@ -189,12 +192,8 @@ func (m *Media) Start(id int64) error {
liveWait := strconv.Itoa(cfg.LiveWait) liveWait := strconv.Itoa(cfg.LiveWait)
nreArgs := []string{ nreArgs := []string{
manifestURL, 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-real-time-merge",
"--live-pipe-mux", "--live-pipe-mux",
"--mp4-real-time-decryption",
"--live-wait-time", liveWait, "--live-wait-time", liveWait,
"--ffmpeg-binary-path", m.FFmpeg, "--ffmpeg-binary-path", m.FFmpeg,
"--save-name", saveName, "--save-name", saveName,
@ -204,6 +203,19 @@ func (m *Media) Start(id int64) error {
"--log-level", "ERROR", "--log-level", "ERROR",
"-ss", "0", "-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 // A synthetic manifest publishes exactly one video + audio pair, and an HLS
// master's variants rarely match a resolution/language filter, so in both // master's variants rarely match a resolution/language filter, so in both
// cases take the best rendition instead of the configured selectors. // cases take the best rendition instead of the configured selectors.
@ -212,7 +224,7 @@ func (m *Media) Start(id int64) error {
} else { } else {
nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect) nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect)
} }
if m.MP4Decrypt != "" { if hasKeys && m.MP4Decrypt != "" {
nreArgs = append(nreArgs, nreArgs = append(nreArgs,
"--decryption-engine", "MP4DECRYPT", "--decryption-engine", "MP4DECRYPT",
"--decryption-binary-path", m.MP4Decrypt, "--decryption-binary-path", m.MP4Decrypt,

View file

@ -27,13 +27,13 @@ func (s *Stub) Start(id int64) error {
if err != nil { if err != nil {
return err return err
} }
if st.MPD == "" || st.Key == "" { if st.MPD == "" {
_, err = s.Store.DB.Exec(` _, err = s.Store.DB.Exec(`
INSERT INTO stream_runtime(stream_id,health,play_path,last_error,updated_at) INSERT INTO stream_runtime(stream_id,health,play_path,last_error,updated_at)
VALUES(?,?,?,?,?) VALUES(?,?,?,?,?)
ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, last_error=excluded.last_error, updated_at=excluded.updated_at`, 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)) id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd", time.Now().UTC().Format(time.RFC3339))
return err return fmt.Errorf("missing mpd")
} }
pid := 10000 + int(id) pid := 10000 + int(id)
s.pids[id] = pid s.pids[id] = pid

View file

@ -63,7 +63,7 @@
} }
listMsg.textContent = streams.length + " stream(s)"; listMsg.textContent = streams.length + " stream(s)";
rowsEl.innerHTML = streams.map((s) => { rowsEl.innerHTML = streams.map((s) => {
const need = !s.mpd || !s.key ? " needs capture" : ""; const need = !s.mpd ? " needs MPD" : "";
return `<tr> return `<tr>
<td><strong>${esc(s.name)}</strong><div class="muted">${esc(s.title || "")}${need}</div></td> <td><strong>${esc(s.name)}</strong><div class="muted">${esc(s.title || "")}${need}</div></td>
<td>${esc(s.app)} / ${esc(s.channel)}</td> <td>${esc(s.app)} / ${esc(s.channel)}</td>
@ -98,6 +98,25 @@
agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", "); 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() { async function refresh() {
try { try {
const [health, list, agents] = await Promise.all([ const [health, list, agents] = await Promise.all([
@ -106,6 +125,7 @@
api("/api/agents").catch(() => ({ agents: [] })), api("/api/agents").catch(() => ({ agents: [] })),
]); ]);
uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s"; uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s";
renderDeps(health.deps);
render(list.streams || []); render(list.streams || []);
renderAgents(agents.agents || []); renderAgents(agents.agents || []);
listMsg.classList.remove("err"); listMsg.classList.remove("err");
@ -212,6 +232,7 @@
editForm.channel.value = st.channel || ""; editForm.channel.value = st.channel || "";
editForm.mpd.value = st.mpd || ""; editForm.mpd.value = st.mpd || "";
editForm.key.value = st.key || ""; editForm.key.value = st.key || "";
if (editForm.proxy) editForm.proxy.value = st.proxy || "";
editForm.headers_json.value = st.headers_json || "{}"; editForm.headers_json.value = st.headers_json || "{}";
dlg.showModal(); dlg.showModal();
return; return;
@ -238,6 +259,7 @@
channel: editForm.channel.value, channel: editForm.channel.value,
mpd: editForm.mpd.value, mpd: editForm.mpd.value,
key: editForm.key.value, key: editForm.key.value,
proxy: editForm.proxy ? editForm.proxy.value : "",
headers_json: editForm.headers_json.value, headers_json: editForm.headers_json.value,
}; };
try { try {

View file

@ -11,6 +11,7 @@
<h1>streamd</h1> <h1>streamd</h1>
<div class="header-right"> <div class="header-right">
<span id="uptime" class="muted"></span> <span id="uptime" class="muted"></span>
<span id="deps-status" class="muted" title="Media tool paths"></span>
<label class="token-box">token <input id="token" type="password" placeholder="STREAMD_TOKEN" autocomplete="off" /></label> <label class="token-box">token <input id="token" type="password" placeholder="STREAMD_TOKEN" autocomplete="off" /></label>
</div> </div>
</header> </header>
@ -26,8 +27,9 @@
<label>channel <label>channel
<select name="channel" id="channel-select"></select> <select name="channel" id="channel-select"></select>
</label> </label>
<label class="span2">mpd <input name="mpd" placeholder="https://…/manifest.mpd (optional until capture)" /></label> <label class="span2">mpd <input name="mpd" placeholder="https://…/manifest.mpd (required to start)" /></label>
<label class="span2">key <textarea name="key" rows="4" placeholder="KID:KEY (one per line; multi-key streams need every key)" spellcheck="false"></textarea></label> <label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY lines (clear streams like BBC need no keys)" spellcheck="false"></textarea></label>
<label class="span2">proxy <input name="proxy" placeholder="optional — socks5://127.0.0.1:1080 or http://127.0.0.1:8080 (origin fetch)" /></label>
<label class="span2">headers JSON <input name="headers_json" value="{}" /></label> <label class="span2">headers JSON <input name="headers_json" value="{}" /></label>
<div class="span2 actions"> <div class="span2 actions">
<button type="submit">Create</button> <button type="submit">Create</button>
@ -70,7 +72,8 @@
<label>title <input name="title" /></label> <label>title <input name="title" /></label>
<label>channel <input name="channel" /></label> <label>channel <input name="channel" /></label>
<label class="span2">mpd <input name="mpd" /></label> <label class="span2">mpd <input name="mpd" /></label>
<label class="span2">key <textarea name="key" rows="4" placeholder="KID:KEY (one per line)" spellcheck="false"></textarea></label> <label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY (one per line)" spellcheck="false"></textarea></label>
<label class="span2">proxy <input name="proxy" placeholder="socks5://127.0.0.1:1080" /></label>
<label class="span2">headers JSON <input name="headers_json" /></label> <label class="span2">headers JSON <input name="headers_json" /></label>
<div class="span2 actions"> <div class="span2 actions">
<button type="submit" value="save">Save</button> <button type="submit" value="save">Save</button>

View file

@ -17,6 +17,7 @@ import (
"drmdecryption/apps/streamd/internal/api" "drmdecryption/apps/streamd/internal/api"
"drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps"
"drmdecryption/apps/streamd/internal/supervisor" "drmdecryption/apps/streamd/internal/supervisor"
"drmdecryption/apps/streamd/internal/ui" "drmdecryption/apps/streamd/internal/ui"
"drmdecryption/apps/streamd/internal/ws" "drmdecryption/apps/streamd/internal/ws"
@ -54,9 +55,11 @@ serve flags:
--bind listen address (default 0.0.0.0:8083) --bind listen address (default 0.0.0.0:8083)
--data data dir for sqlite + www + work (default .cache/streamd) --data data dir for sqlite + www + work (default .cache/streamd)
--token shared bearer token for mutating API (or STREAMD_TOKEN) --token shared bearer token for mutating API (or STREAMD_TOKEN)
--nre path to N_m3u8DL-RE (else NRE_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) --ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH) --mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
--bin-dir where to install/look for media tools (default <repo>/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") nre := fs.String("nre", "", "N_m3u8DL-RE binary")
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary") ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary") mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
_ = fs.Parse(args) _ = fs.Parse(args)
dataDir := *data dataDir := *data
@ -91,24 +96,14 @@ func serveCmd(args []string) {
} }
defer store.Close() defer store.Close()
nrePath := firstExisting(*nre, depStatus, _ := deps.Ensure(deps.Options{
os.Getenv("NRE_PATH"), BinDir: *binDir,
os.Getenv("N_M3U8DL_RE"), SkipDownload: *skipDeps,
filepath.Join("bin", "N_m3u8DL-RE.exe"), Log: log.Default(),
"N_m3u8DL-RE", }, *nre, *ffmpeg, *mp4decrypt)
) nrePath := depStatus.NRE
ffPath := firstExisting(*ffmpeg, ffPath := depStatus.FFmpeg
os.Getenv("FFMPEG_PATH"), decPath := depStatus.MP4Decrypt
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",
)
sup := supervisor.NewMedia(supervisor.Options{ sup := supervisor.NewMedia(supervisor.Options{
Store: store, Store: store,
@ -125,6 +120,7 @@ func serveCmd(args []string) {
Token: tok, Token: tok,
Supervisor: sup, Supervisor: sup,
StartedAt: time.Now(), StartedAt: time.Now(),
Deps: depStatus,
} }
hub := ws.NewHub(store, tok, log.Default()) hub := ws.NewHub(store, tok, log.Default())
@ -161,7 +157,7 @@ func serveCmd(args []string) {
return return
} }
for _, st := range list { for _, st := range list {
if !st.Enabled || strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" { if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
continue continue
} }
mpd := strings.ToLower(strings.TrimSpace(st.MPD)) mpd := strings.ToLower(strings.TrimSpace(st.MPD))

2
configs/.gitkeep Normal file
View file

@ -0,0 +1,2 @@
# Optional local configs

View file

@ -14,19 +14,36 @@ run` keeps credentials fresh using real phones.
| `--bind` | `0.0.0.0:8083` | listen address | | `--bind` | `0.0.0.0:8083` | listen address |
| `--data` | `.cache/streamd` | SQLite, work dirs, HLS output, logs | | `--data` | `.cache/streamd` | SQLite, work dirs, HLS output, logs |
| `--token` | `$STREAMD_TOKEN` | bearer token for mutating routes | | `--token` | `$STREAMD_TOKEN` | bearer token for mutating routes |
| `--nre` | `$NRE_PATH`, `bin/`, `PATH` | downloader binary | | `--nre` | `$NRE_PATH`, `bin/`, `PATH`, auto-download | N_m3u8DL-RE |
| `--ffmpeg` | `$FFMPEG_PATH`, `bin/`, `PATH` | ffmpeg | | `--ffmpeg` | `$FFMPEG_PATH`, `bin/`, `PATH`, auto-download | ffmpeg |
| `--mp4decrypt` | `$MP4DECRYPT_PATH`, `bin/`, `PATH` | decrypter | | `--mp4decrypt` | `$MP4DECRYPT_PATH`, `bin/`, `PATH`, auto-download | Bento4 mp4decrypt |
| `--bin-dir` | `<repo>/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 <http://127.0.0.1:8083>. GET routes are unauthenticated; anything mutating Open <http://127.0.0.1:8083>. GET routes are unauthenticated; anything mutating
needs `Authorization: Bearer <token>`. needs `Authorization: Bearer <token>`. 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 ### API
| Route | Purpose | | Route | Purpose |
|---|---| |---|---|
| `GET /api/health` | liveness + uptime | | `GET /api/health` | liveness + uptime + `deps` paths |
| `GET /api/apps` | compiled-in modules, their channels, registered rewriters | | `GET /api/apps` | modules under `modules/`, their channels, registered rewriters |
| `GET /api/modules` | list `modules/<name>/` with `has_yaml` + `yaml_sha256` |
| `PUT /api/modules/:name` | write `modules/<name>/module.yaml` (bearer; raw YAML or `{"yaml":…}`) |
| `GET /api/streams` | all streams with runtime state | | `GET /api/streams` | all streams with runtime state |
| `POST /api/streams` | create | | `POST /api/streams` | create |
| `PATCH /api/streams/:id` | update | | `PATCH /api/streams/:id` | update |

View file

@ -17,10 +17,11 @@ modules/
| File | Published? | Purpose | | File | Published? | Purpose |
|---|---|---| |---|---|---|
| `module-publish.yaml` | yes (in git + release zips) | Universal package/channels/UI | | `module-publish.yaml` | yes (in git only) | Universal package/channels/UI |
| `module.yaml` | **no** | Operator secrets; overlays publish at runtime | | `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 ## Commands
@ -33,7 +34,7 @@ DRM_MODULES_DIR=D:\mods drm capture --app rte --channel rteone
## Releases ## 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. Forgejo Actions. Host `drm` stays on separate `v*` tags.
Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt. Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt.

View file

@ -50,8 +50,9 @@ channels:
# vc12: "…" # vc12: "…"
ui: ui:
launch_desc_contains: ["live tab", "header logo", "Live"] # "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab.
live_tab_desc_re: ["Live tab", "Live"] launch_desc_contains: ["live tab", "header logo", "Home tab"]
live_tab_desc_re: ["^Live tab"]
timeouts: timeouts:
launch_wait_ui: 30s launch_wait_ui: 30s

View file

@ -74,16 +74,14 @@ foreach ($name in $Modules) {
Remove-Item Env:GOOS, Env:GOARCH, Env:CGO_ENABLED -ErrorAction SilentlyContinue 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 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 = @" $readme = @"
# module-$name ($Version) # $name ($Version)
Drop this folder into your Null DRM ``modules/$name/`` directory (or point Unpack this zip into your Null DRM ``modules/$name/`` directory (or point
``drm --modules-dir`` at a folder that contains ``$name/``). ``drm --modules-dir`` at a parent that contains ``$name/``).
1. Edit ``module.yaml`` — fill in any sensitive fields marked in comments. 1. Edit ``module.yaml`` — fill in any sensitive fields marked in comments.
2. Copy the matching ``.bin/<goos>-<goarch>/$name[.exe]`` up to ``.bin/$name[.exe]`` 2. Copy the matching ``.bin/<goos>-<goarch>/$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. if Go is installed.
3. Run: ``drm modules`` then ``drm capture --app $name --channel …`` 3. Run: ``drm modules`` then ``drm capture --app $name --channel …``
Local ``module.yaml`` with secrets must never be committed. This zip's This zip's ``module.yaml`` is the published universal template (secrets empty).
``module.yaml`` is a rename of ``module-publish.yaml`` (universal values only). Do not commit a local ``module.yaml`` that contains secrets.
"@ "@
Set-Content -Path (Join-Path $stage "README.md") -Value $readme -Encoding utf8 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 $zipPath = Join-Path $Out $zipName
if (Test-Path $zipPath) { Remove-Item -Force $zipPath } if (Test-Path $zipPath) { Remove-Item -Force $zipPath }
Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force
@ -113,4 +111,4 @@ foreach ($z in $builtZips) {
} }
[System.IO.File]::WriteAllLines($sumsPath, $lines) [System.IO.File]::WriteAllLines($sumsPath, $lines)
Write-Host "DONE modules release $Version → $Out" 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

View file

@ -41,18 +41,18 @@ for name in "${MODULES[@]}"; do
go build -trimpath -ldflags='-s -w' -o "$bin" . ) go build -trimpath -ldflags='-s -w' -o "$bin" . )
done <<< "$(printf '%s\n' "${TARGETS[@]}")" 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.yaml"
cp "$publish" "$stage/module-publish.yaml"
cat > "$stage/README.md" <<EOF cat > "$stage/README.md" <<EOF
# module-$name ($VERSION) # $name ($VERSION)
Drop into \`modules/$name/\`. Edit \`module.yaml\` for secrets. Copy Unpack into \`modules/$name/\`. Edit \`module.yaml\` for secrets. Copy
\`.bin/<goos>-<goarch>/$name\` to \`.bin/$name\` for your OS, or rebuild with Go. \`.bin/<goos>-<goarch>/$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 EOF
zip_path="$OUT/module-${name}-${VERSION}.zip" zip_path="$OUT/${name}.zip"
rm -f "$zip_path" rm -f "$zip_path"
( cd "$stage" && zip -qr "$zip_path" . ) ( cd "$stage" && zip -qr "$zip_path" . )
built+=("$zip_path") built+=("$zip_path")
@ -65,4 +65,4 @@ for z in "${built[@]}"; do
( cd "$(dirname "$z")" && sha256sum "$(basename "$z")" ) >> "$sums" ( cd "$(dirname "$z")" && sha256sum "$(basename "$z")" ) >> "$sums"
done done
echo "DONE modules release $VERSION → $OUT" 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

View file

@ -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 = @"
<b>$Title</b>
Provider module zips: <code>bbc.zip</code>, <code>rte.zip</code>, <code>tg4.zip</code>
Unpack each into <code>modules/&lt;name&gt;/</code> and edit <code>module.yaml</code> for secrets.
<a href="$ReleaseUrl">Download $Tag</a>
"@
} else {
$Body = @"
<b>$Title</b>
Host CLI (<code>drm</code>) + on-device MITM (<code>proxy-android-arm64</code>).
<a href="$ReleaseUrl">Download $Tag</a>
"@
}
}
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))"

View file

@ -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 <tag>" >&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="<b>${TITLE}</b>
Provider module zips: <code>bbc.zip</code>, <code>rte.zip</code>, <code>tg4.zip</code>
Unpack each into <code>modules/&lt;name&gt;/</code> and edit <code>module.yaml</code> for secrets.
<a href=\"${URL}\">Download ${TAG}</a>"
else
BODY="<b>${TITLE}</b>
Host CLI (<code>drm</code>) + on-device MITM (<code>proxy-android-arm64</code>).
<a href=\"${URL}\">Download ${TAG}</a>"
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