Compare commits
No commits in common. "main" and "v0.1.4" have entirely different histories.
233 changed files with 2385 additions and 28201 deletions
|
|
@ -55,8 +55,6 @@ jobs:
|
||||||
| `rte.zip` | RTÉ Player CLI + `module.yaml` template |
|
| `rte.zip` | RTÉ Player CLI + `module.yaml` template |
|
||||||
| `tg4.zip` | TG4 CLI + `module.yaml` template |
|
| `tg4.zip` | TG4 CLI + `module.yaml` template |
|
||||||
| `itv.zip` | ITVX CLI stub + `module.yaml` template |
|
| `itv.zip` | ITVX CLI stub + `module.yaml` template |
|
||||||
| `c4.zip` | Channel 4 CLI + `module.yaml` template |
|
|
||||||
| `my5.zip` | Channel 5 (My5) CLI + `module.yaml` template |
|
|
||||||
| `SHA256SUMS-modules.txt` | Checksums |
|
| `SHA256SUMS-modules.txt` | Checksums |
|
||||||
|
|
||||||
Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`).
|
Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`).
|
||||||
|
|
@ -78,8 +76,8 @@ jobs:
|
||||||
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
|
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
|
# Release announces go to the maintainer DM (not the public group topic).
|
||||||
export TELEGRAM_CHAT_ID="-1003721978702"
|
export TELEGRAM_CHAT_ID="7314901602"
|
||||||
export TELEGRAM_MESSAGE_THREAD_ID="16"
|
unset TELEGRAM_MESSAGE_THREAD_ID || true
|
||||||
chmod +x scripts/notify-telegram.sh
|
chmod +x scripts/notify-telegram.sh
|
||||||
./scripts/notify-telegram.sh "${{ github.ref_name }}"
|
./scripts/notify-telegram.sh "${{ github.ref_name }}"
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,7 @@
|
||||||
# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release.
|
# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release.
|
||||||
#
|
#
|
||||||
# Triggers:
|
# Trigger: push a version tag
|
||||||
# Stable: git tag v1.2.3 && git push origin v1.2.3
|
# git tag v1.2.3 && git push origin v1.2.3
|
||||||
# Beta: git tag v1.2.3-beta.1 && git push origin v1.2.3-beta.1
|
|
||||||
#
|
|
||||||
# Each version tag gets its own release. CI also retargets a rolling channel tag:
|
|
||||||
# vX.Y.Z → release + update `stable` (always-latest download URL)
|
|
||||||
# vX.Y.Z-<pre> → prerelease + update `beta` (always-latest beta URL)
|
|
||||||
#
|
|
||||||
# Download without pinning a version:
|
|
||||||
# .../releases/download/stable/streamd-linux-amd64
|
|
||||||
# .../releases/download/beta/streamd-linux-amd64
|
|
||||||
#
|
#
|
||||||
# Requires a Forgejo Actions runner registered against this instance
|
# Requires a Forgejo Actions runner registered against this instance
|
||||||
# (label must match runs-on below — default act_runner often uses "docker").
|
# (label must match runs-on below — default act_runner often uses "docker").
|
||||||
|
|
@ -32,35 +23,6 @@ jobs:
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Classify tag (stable vs beta)
|
|
||||||
id: meta
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
TAG="${{ github.ref_name }}"
|
|
||||||
# Strict SemVer: v1.2.3 = stable; v1.2.3-beta.1 / -rc.1 / -alpha.1 = beta channel
|
|
||||||
if echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
|
|
||||||
CHANNEL=stable
|
|
||||||
PRERELEASE=false
|
|
||||||
TITLE="$TAG"
|
|
||||||
NOTES_KIND=stable
|
|
||||||
elif echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+-(beta|rc|alpha)(\.[0-9]+)?$'; then
|
|
||||||
CHANNEL=beta
|
|
||||||
PRERELEASE=true
|
|
||||||
TITLE="$TAG (beta)"
|
|
||||||
NOTES_KIND=beta
|
|
||||||
else
|
|
||||||
echo "Unsupported host tag '$TAG'." >&2
|
|
||||||
echo "Use vX.Y.Z for stable or vX.Y.Z-beta.N / -rc.N / -alpha.N for beta." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
{
|
|
||||||
echo "channel=$CHANNEL"
|
|
||||||
echo "prerelease=$PRERELEASE"
|
|
||||||
echo "title=$TITLE"
|
|
||||||
echo "notes_kind=$NOTES_KIND"
|
|
||||||
} >> "$GITHUB_OUTPUT"
|
|
||||||
echo "tag=$TAG channel=$CHANNEL prerelease=$PRERELEASE"
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
|
|
@ -75,104 +37,52 @@ jobs:
|
||||||
./scripts/build-release.sh "${{ github.ref_name }}"
|
./scripts/build-release.sh "${{ github.ref_name }}"
|
||||||
ls -la dist/release
|
ls -la dist/release
|
||||||
|
|
||||||
- name: Prepare release notes
|
- name: Upload to Forgejo release
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
TAG="${{ github.ref_name }}"
|
|
||||||
CHANNEL="${{ steps.meta.outputs.channel }}"
|
|
||||||
NOTES="docs/releases/${TAG}.md"
|
|
||||||
if [ -f "$NOTES" ]; then
|
|
||||||
cp "$NOTES" /tmp/release-notes.md
|
|
||||||
echo "Using $NOTES"
|
|
||||||
else
|
|
||||||
cat > /tmp/release-notes.md <<EOF
|
|
||||||
Multi-platform **Streamd** host CLI + on-device MITM (\`proxy-android-arm64\`).
|
|
||||||
|
|
||||||
Channel: **${CHANNEL}** (rolling download tag \`${CHANNEL}\` also updated).
|
|
||||||
|
|
||||||
| Asset | Platform |
|
|
||||||
|---|---|
|
|
||||||
| \`streamd-windows-amd64.exe\` | Windows x86_64 |
|
|
||||||
| \`streamd-windows-arm64.exe\` | Windows ARM64 |
|
|
||||||
| \`streamd-linux-amd64\` | Linux x86_64 |
|
|
||||||
| \`streamd-linux-arm64\` | Linux ARM64 |
|
|
||||||
| \`streamd-darwin-amd64\` | macOS Intel |
|
|
||||||
| \`streamd-darwin-arm64\` | macOS Apple Silicon |
|
|
||||||
| \`proxy-android-arm64\` | On-device MITM (push with \`streamd proxy\`) |
|
|
||||||
| \`SHA256SUMS.txt\` | Checksums |
|
|
||||||
|
|
||||||
Always-latest URLs (no version pin):
|
|
||||||
- Stable: \`…/releases/download/stable/<asset>\`
|
|
||||||
- Beta: \`…/releases/download/beta/<asset>\`
|
|
||||||
|
|
||||||
Built with \`CGO_ENABLED=0\` via \`scripts/build-release.sh\`.
|
|
||||||
Phone capture still needs Magisk + \`streamd proxy install-ca --reinject\`.
|
|
||||||
EOF
|
|
||||||
echo "No $NOTES — using generic notes"
|
|
||||||
fi
|
|
||||||
cat > /tmp/channel-notes.md <<EOF
|
|
||||||
Rolling **${CHANNEL}** channel for Streamd.
|
|
||||||
|
|
||||||
Currently points at **${TAG}**.
|
|
||||||
Prefer versioned tags for pinned installs; use this channel for always-latest downloads.
|
|
||||||
|
|
||||||
\`\`\`text
|
|
||||||
…/releases/download/${CHANNEL}/streamd-linux-amd64
|
|
||||||
…/releases/download/${CHANNEL}/streamd-windows-amd64.exe
|
|
||||||
…/releases/download/${CHANNEL}/proxy-android-arm64
|
|
||||||
\`\`\`
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload versioned Forgejo release
|
|
||||||
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
|
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
|
||||||
with:
|
with:
|
||||||
direction: upload
|
direction: upload
|
||||||
|
# Defaults to this runner's Forgejo URL when omitted.
|
||||||
url: https://git.nulldrm.com
|
url: https://git.nulldrm.com
|
||||||
repo: ${{ github.repository }}
|
repo: ${{ github.repository }}
|
||||||
|
# Built-in job token (write:repository). Override with a PAT secret if needed.
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
tag: ${{ github.ref_name }}
|
tag: ${{ github.ref_name }}
|
||||||
sha: ${{ github.sha }}
|
sha: ${{ github.sha }}
|
||||||
release-dir: dist/release
|
release-dir: dist/release
|
||||||
title: ${{ steps.meta.outputs.title }}
|
title: ${{ github.ref_name }}
|
||||||
prerelease: ${{ steps.meta.outputs.prerelease }}
|
|
||||||
override: true
|
override: true
|
||||||
release-notes-file: /tmp/release-notes.md
|
release-notes: |
|
||||||
|
Multi-platform `drm` host CLI + on-device MITM (`proxy-android-arm64`).
|
||||||
|
|
||||||
- name: Upload rolling channel release (stable / beta)
|
| Asset | Platform |
|
||||||
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
|
|---|---|
|
||||||
with:
|
| `drm-windows-amd64.exe` | Windows x86_64 |
|
||||||
direction: upload
|
| `drm-windows-arm64.exe` | Windows ARM64 |
|
||||||
url: https://git.nulldrm.com
|
| `drm-linux-amd64` | Linux x86_64 |
|
||||||
repo: ${{ github.repository }}
|
| `drm-linux-arm64` | Linux ARM64 |
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
| `drm-darwin-amd64` | macOS Intel |
|
||||||
tag: ${{ steps.meta.outputs.channel }}
|
| `drm-darwin-arm64` | macOS Apple Silicon |
|
||||||
sha: ${{ github.sha }}
|
| `proxy-android-arm64` | On-device MITM (push with `drm proxy`) |
|
||||||
release-dir: dist/release
|
| `SHA256SUMS.txt` | Checksums |
|
||||||
title: ${{ steps.meta.outputs.channel }} ← ${{ github.ref_name }}
|
|
||||||
prerelease: ${{ steps.meta.outputs.prerelease }}
|
Built with `CGO_ENABLED=0` via `scripts/build-release.sh`.
|
||||||
override: true
|
Phone capture still needs Magisk + `drm proxy install-ca --reinject`.
|
||||||
release-notes-file: /tmp/channel-notes.md
|
|
||||||
|
|
||||||
- name: Announce on Telegram
|
- name: Announce on Telegram
|
||||||
env:
|
env:
|
||||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||||
|
# Private DM chat (@error404developer). Override via secret if needed.
|
||||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||||
RELEASE_TAG: ${{ github.ref_name }}
|
RELEASE_TAG: ${{ github.ref_name }}
|
||||||
RELEASE_KIND: host
|
RELEASE_KIND: host
|
||||||
RELEASE_CHANNEL: ${{ steps.meta.outputs.channel }}
|
|
||||||
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
|
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
|
||||||
run: |
|
run: |
|
||||||
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
|
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
|
||||||
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
|
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
|
# Release announces go to the maintainer DM (not the public group topic).
|
||||||
export TELEGRAM_CHAT_ID="-1003721978702"
|
export TELEGRAM_CHAT_ID="7314901602"
|
||||||
export TELEGRAM_MESSAGE_THREAD_ID="16"
|
unset TELEGRAM_MESSAGE_THREAD_ID || true
|
||||||
if [ "${{ steps.meta.outputs.channel }}" = "beta" ]; then
|
|
||||||
export RELEASE_TITLE="Streamd ${{ github.ref_name }} (beta)"
|
|
||||||
else
|
|
||||||
export RELEASE_TITLE="Streamd ${{ github.ref_name }}"
|
|
||||||
fi
|
|
||||||
chmod +x scripts/notify-telegram.sh
|
chmod +x scripts/notify-telegram.sh
|
||||||
./scripts/notify-telegram.sh "${{ github.ref_name }}"
|
./scripts/notify-telegram.sh "${{ github.ref_name }}"
|
||||||
|
|
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64
|
||||||
apps/proxy/rteproxy-android-arm64
|
apps/proxy/rteproxy-android-arm64
|
||||||
# local / VPS deploy + operator scripts (test stuff; keep out of git)
|
# local / VPS deploy + operator scripts (test stuff; keep out of git)
|
||||||
deploy/
|
deploy/
|
||||||
# Ignore local scripts, but keep release builders + server helpers tracked.
|
# Ignore local scripts, but keep the release builders tracked for Forgejo Actions.
|
||||||
scripts/*
|
scripts/*
|
||||||
!scripts/build-release.sh
|
!scripts/build-release.sh
|
||||||
!scripts/build-release.ps1
|
!scripts/build-release.ps1
|
||||||
|
|
@ -226,8 +226,6 @@ scripts/*
|
||||||
!scripts/build-modules-release.ps1
|
!scripts/build-modules-release.ps1
|
||||||
!scripts/notify-telegram.sh
|
!scripts/notify-telegram.sh
|
||||||
!scripts/notify-telegram.ps1
|
!scripts/notify-telegram.ps1
|
||||||
!scripts/streamd-bg.sh
|
|
||||||
!scripts/streamd-update.sh
|
|
||||||
# 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/**
|
||||||
|
|
|
||||||
146
README.md
146
README.md
|
|
@ -1,9 +1,9 @@
|
||||||
# 📺 Streamd
|
# 🔓 Null DRM
|
||||||
|
|
||||||
**Next-generation open-source DRM decryption for Android streaming apps.**
|
**Next-generation open-source DRM decryption for Android streaming apps.**
|
||||||
|
|
||||||
Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests
|
Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, …), pull manifests
|
||||||
and licenses through a transparent MITM, and restream. One host binary — **`streamd`** —
|
and licenses through a transparent MITM, and restream. One host binary — **`drm`** —
|
||||||
plus drop-in providers under **`modules/`**.
|
plus drop-in providers under **`modules/`**.
|
||||||
|
|
||||||
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
|
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
|
||||||
|
|
@ -24,39 +24,6 @@ traffic.
|
||||||
| 🇮🇪 `rte` | RTÉ Player | Irish egress; ModularDRM keys |
|
| 🇮🇪 `rte` | RTÉ Player | Irish egress; ModularDRM keys |
|
||||||
| 🟢 `tg4` | TG4 | Catalog + phone capture |
|
| 🟢 `tg4` | TG4 | Catalog + phone capture |
|
||||||
| 🟣 `itv` | ITVX | Transparent MITM; UK VPN; Live list autoplay |
|
| 🟣 `itv` | ITVX | Transparent MITM; UK VPN; Live list autoplay |
|
||||||
| 🟧 `c4` | Channel 4 | Transparent MITM; UK VPN; Live TV grab-all |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🖥️ streamd dashboard
|
|
||||||
|
|
||||||
Run `streamd serve`, open the panel in a browser, manage streams and API keys:
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="docs/images/streamd/dashboard.jpg" alt="streamd Dashboard — overview, live Channel 4, HLS link" width="720" />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center"><em>Dashboard — health, live streams, and play links</em></p>
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="docs/images/streamd/streams.jpg" alt="streamd Streams list" width="720" />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center"><em>Streams — list, filters, start / stop / restart</em></p>
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="docs/images/streamd/stream-detail.jpg" alt="streamd stream detail with in-browser player" width="720" />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center"><em>Stream detail — credentials, variants, and preview player</em></p>
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="docs/images/streamd/people-keys.jpg" alt="streamd People and API keys" width="720" />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center"><em>People & keys — accounts and agent API keys</em></p>
|
|
||||||
|
|
||||||
Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md) · full reference: [docs/streamd.md](docs/streamd.md)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -64,55 +31,15 @@ Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md)
|
||||||
|
|
||||||
### 1️⃣ Download
|
### 1️⃣ Download
|
||||||
|
|
||||||
Host binaries ship on two rolling channels (always the newest build — no version pin):
|
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 zips you need
|
||||||
| Channel | Tag | When to use |
|
(`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`).
|
||||||
|---------|-----|-------------|
|
|
||||||
| **Stable** | [`stable`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/stable) | Everyday installs |
|
|
||||||
| **Beta** | [`beta`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/beta) | Try pre-releases (`vX.Y.Z-beta.N`) |
|
|
||||||
|
|
||||||
Provider zips still come from **`modules-v*`** releases (`bbc.zip`, `rte.zip`, …).
|
|
||||||
Pick **one** host binary block for your machine, then run `chmod +x streamd` on Linux/macOS.
|
|
||||||
|
|
||||||
**Linux Intel / AMD 64-bit (stable)**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -fL -o streamd \
|
|
||||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
|
|
||||||
chmod +x streamd
|
|
||||||
```
|
|
||||||
|
|
||||||
**Linux ARM 64-bit (stable)** — Raspberry Pi 4+, many cloud ARM VMs
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -fL -o streamd \
|
|
||||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-arm64"
|
|
||||||
chmod +x streamd
|
|
||||||
```
|
|
||||||
|
|
||||||
**Beta channel (Linux Intel / AMD 64-bit pre-release)**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -fL -o streamd \
|
|
||||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/beta/streamd-linux-amd64"
|
|
||||||
chmod +x streamd
|
|
||||||
```
|
|
||||||
|
|
||||||
**Windows Intel / AMD 64-bit (stable, PowerShell)**
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
Invoke-WebRequest -Uri "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-windows-amd64.exe" -OutFile streamd.exe
|
|
||||||
```
|
|
||||||
|
|
||||||
Other stable assets: `streamd-windows-arm64.exe`, `streamd-darwin-amd64`, `streamd-darwin-arm64`,
|
|
||||||
`proxy-android-arm64`. For beta, swap `/download/stable/` → `/download/beta/` in any URL.
|
|
||||||
Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v0.2.0-beta.1`.
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
Streamd/
|
Null-DRM/
|
||||||
streamd.exe # or ./streamd on Linux/macOS
|
drm.exe # or ./drm on Linux/macOS
|
||||||
bin/proxy-android-arm64 # optional; also embedded in the release binary
|
bin/proxy-android-arm64 # optional; also embedded in release drm
|
||||||
modules/ # or upload zips in the streamd Modules page
|
modules/
|
||||||
bbc/ # unzip bbc.zip here
|
bbc/ # unzip bbc.zip here
|
||||||
rte/
|
rte/
|
||||||
tg4/
|
tg4/
|
||||||
|
|
@ -121,7 +48,7 @@ Streamd/
|
||||||
outputs/ # created on first run
|
outputs/ # created on first run
|
||||||
```
|
```
|
||||||
|
|
||||||
On first run, `streamd` creates the install scaffold next to the exe.
|
On first run, `drm` creates the install scaffold next to the exe.
|
||||||
|
|
||||||
### 2️⃣ Prerequisites
|
### 2️⃣ Prerequisites
|
||||||
|
|
||||||
|
|
@ -139,14 +66,14 @@ Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields o
|
||||||
almost nothing extra.
|
almost nothing extra.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
streamd modules
|
drm modules
|
||||||
# or: streamd --modules-dir D:\mods modules
|
# or: drm --modules-dir D:\mods modules
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4️⃣ Phone CA (once per device / CA)
|
### 4️⃣ Phone CA (once per device / CA)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
streamd proxy install-ca --reinject
|
drm proxy install-ca --reinject
|
||||||
adb shell am force-stop bbc.iplayer.android # or the app you will capture
|
adb shell am force-stop bbc.iplayer.android # or the app you will capture
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -154,25 +81,18 @@ adb shell am force-stop bbc.iplayer.android # or the app you will capture
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
|
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
|
||||||
streamd capture --app bbc --channel bbcone --wait 120
|
drm capture --app bbc --channel bbcone --wait 120
|
||||||
streamd capture --app bbc --channel s4c --wait 120
|
drm capture --app bbc --channel s4c --wait 120
|
||||||
|
|
||||||
# ITVX (UK VPN; Live tab autoplay)
|
# ITVX (UK VPN; Live tab autoplay)
|
||||||
streamd capture --app itv --channel itv1 --wait 90
|
drm capture --app itv --channel itv1 --wait 90
|
||||||
|
|
||||||
# Channel 4 — one channel, or every Live channel
|
|
||||||
streamd capture --app c4 --channel channel4 --wait 90
|
|
||||||
streamd capture --app c4 --all --wait 90
|
|
||||||
|
|
||||||
# Grab every channel for any module
|
|
||||||
streamd capture --app itv --all --wait 90
|
|
||||||
|
|
||||||
# RTE / TG4 (keys via --wvd when needed)
|
# RTE / TG4 (keys via --wvd when needed)
|
||||||
streamd capture --app rte --channel rteone --wvd data/device.wvd
|
drm capture --app rte --channel rteone --wvd data/device.wvd
|
||||||
streamd capture --app tg4 --channel ioi --wvd data/device.wvd
|
drm capture --app tg4 --channel ioi --wvd data/device.wvd
|
||||||
|
|
||||||
# Catalog only (no phone) — TG4
|
# Catalog only (no phone) — TG4
|
||||||
streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
||||||
```
|
```
|
||||||
|
|
||||||
📁 Results land in `outputs/<app>/<stamp>/` (and `latest/`).
|
📁 Results land in `outputs/<app>/<stamp>/` (and `latest/`).
|
||||||
|
|
@ -180,7 +100,7 @@ streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
||||||
### 6️⃣ Clean the phone after a run
|
### 6️⃣ Clean the phone after a run
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
streamd proxy reset
|
drm proxy reset
|
||||||
```
|
```
|
||||||
|
|
||||||
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
|
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
|
||||||
|
|
@ -190,19 +110,19 @@ Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fr
|
||||||
## 🧾 Command cheat sheet
|
## 🧾 Command cheat sheet
|
||||||
|
|
||||||
```text
|
```text
|
||||||
streamd [--modules-dir DIR] <command> …
|
drm [--modules-dir DIR] <command> …
|
||||||
|
|
||||||
streamd modules
|
drm modules
|
||||||
streamd capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
|
drm capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
|
||||||
streamd catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
|
drm catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
|
||||||
streamd proxy install-ca [--reinject] | reset [--keep-captures]
|
drm proxy install-ca [--reinject] | reset [--keep-captures]
|
||||||
| transparent --package PKG [--mitm-host HOST]
|
| transparent --package PKG [--mitm-host HOST]
|
||||||
| start | stop | push | discover | pull
|
| start | stop | push | discover | pull
|
||||||
streamd serve [--bind …] [--data …] [--token …]
|
drm serve [--bind …] [--data …] [--token …]
|
||||||
streamd agent run|status|devices|enqueue|cancel [--config …]
|
drm agent run|status|devices|enqueue|cancel [--config …]
|
||||||
```
|
```
|
||||||
|
|
||||||
🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
|
🌍 Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
|
||||||
|
|
||||||
🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
|
🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
|
||||||
|
|
||||||
|
|
@ -215,8 +135,8 @@ streamd agent run|status|devices|enqueue|cancel [--config …]
|
||||||
| `module-publish.yaml` | git only | Universal package, channels, UI |
|
| `module-publish.yaml` | git only | Universal package, channels, UI |
|
||||||
| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed |
|
| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed |
|
||||||
|
|
||||||
Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` / `c4.zip` / `my5.zip`
|
Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` with
|
||||||
with `module.yaml` only (no `module-publish.yaml` inside the zip).
|
`module.yaml` only (no `module-publish.yaml` inside the zip).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -225,7 +145,7 @@ with `module.yaml` only (no `module-publish.yaml` inside the zip).
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
|
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
|
||||||
cd Null-DRM-Official
|
cd Null-DRM-Official
|
||||||
go -C apps/cli build -o ../../bin/streamd.exe . # Windows
|
go -C apps/cli build -o ../../bin/drm.exe . # Windows
|
||||||
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
|
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
|
||||||
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
|
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
|
||||||
```
|
```
|
||||||
|
|
@ -236,7 +156,7 @@ More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](
|
||||||
|
|
||||||
## 💚 Support the project
|
## 💚 Support the project
|
||||||
|
|
||||||
If Streamd saves you time, donations keep development going:
|
If Null DRM saves you time, donations keep development going:
|
||||||
|
|
||||||
| Coin | Address |
|
| Coin | Address |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# agent
|
# agent
|
||||||
|
|
||||||
Always-on credentials refresher, hosted by the single binary as `streamd agent`.
|
Always-on credentials refresher, hosted by the single binary as `drm agent`.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
apps/agent/
|
apps/agent/
|
||||||
|
|
@ -26,54 +26,38 @@ expire by themselves if the agent dies.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# terminal 1 — control plane
|
# terminal 1 — control plane
|
||||||
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
|
||||||
|
|
||||||
# terminal 2 — agent in the background (Linux / macOS / Windows)
|
# terminal 2 — agent
|
||||||
export STREAMD_API_KEY=ndk_…
|
export STREAMD_TOKEN=SECRET
|
||||||
./bin/streamd agent start --config apps/agent/agent.yaml
|
./bin/drm agent run --config apps/agent/agent.yaml
|
||||||
./bin/streamd agent status --config apps/agent/agent.yaml
|
|
||||||
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
|
|
||||||
# stop / restart: ./bin/streamd agent stop|restart --config …
|
|
||||||
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./bin/streamd agent devices
|
./bin/drm agent status
|
||||||
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
./bin/drm agent devices
|
||||||
./bin/streamd agent cancel --job 3
|
./bin/drm agent enqueue --stream tg4-ioi --reason manual
|
||||||
|
./bin/drm agent cancel --job 3
|
||||||
```
|
```
|
||||||
|
|
||||||
With `sync_modules: true` (default in the sample config), the agent **pulls**
|
App modules are compiled into the binary, so there is no `modules_dir` to set. The
|
||||||
provider modules from the streamd Modules page into `<data_dir>/modules/`. You do
|
agent drives whichever module a stream names and contains no provider logic.
|
||||||
not need a hand-maintained `modules/` tree on each agent host. The agent drives
|
|
||||||
whichever module a stream names and contains no provider logic.
|
|
||||||
|
|
||||||
## Config
|
## Config
|
||||||
|
|
||||||
`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
|
`agent.yaml` — `streamd_url`, `token` (or `STREAMD_TOKEN`), `poll_interval_sec`,
|
||||||
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
|
`workers`, `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised
|
||||||
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
|
device), `wvd`, `user_agent`, `agent_id`, `data_dir`.
|
||||||
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
|
|
||||||
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`,
|
|
||||||
`job_backoff` (default false — exponential delays only when several agents
|
|
||||||
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
|
|
||||||
`keep_old` for `agent start|stop|update`.
|
|
||||||
|
|
||||||
Create the key in the streamd dashboard (role **operator**). The legacy shared
|
`wvd` must be set or key fetches fail.
|
||||||
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
|
||||||
|
|
||||||
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
|
|
||||||
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
|
|
||||||
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
|
|
||||||
a hand-made venv.
|
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go -C apps/cli build -o ../../bin/streamd .
|
go -C apps/cli build -o ../../bin/drm .
|
||||||
|
|
||||||
# cross-compile
|
# cross-compile
|
||||||
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
|
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
|
||||||
```
|
```
|
||||||
|
|
||||||
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,8 @@
|
||||||
# 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://localhost:8083
|
streamd_url: http://185.18.221.132:8083
|
||||||
# Paste an operator API key from streamd → People & keys → New API key.
|
# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials, modules).
|
||||||
# The dashboard shows the secret once — copy it into api_key (not the name).
|
token: "SECRET"
|
||||||
# api_key: "<paste-secret-here>"
|
|
||||||
# token: is a legacy alias for the same field (or set STREAMD_API_KEY / STREAMD_TOKEN).
|
|
||||||
token: "REPLACE_WITH_API_KEY_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
|
||||||
poll_interval_sec: 30
|
poll_interval_sec: 30
|
||||||
|
|
@ -14,23 +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
|
||||||
# Pull modules from the streamd panel into the local cache (package.zip + yaml).
|
# Push local modules/<name>/module.yaml to streamd when missing or SHA differs.
|
||||||
sync_modules: true
|
sync_modules: true
|
||||||
# modules_dir: # optional; default <data_dir>/modules
|
# modules_dir: modules # optional override (default: repo modules/)
|
||||||
# modules_sync_interval_sec: 300
|
# modules_sync_interval_sec: 300
|
||||||
# modules_prune: false # delete local modules absent from the panel
|
# wvd: data/device.wvd # path to .wvd (required for key fetch)
|
||||||
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
|
|
||||||
# Set true only when several agents share the same streams.
|
|
||||||
# job_backoff: false
|
|
||||||
# Background daemon (streamd agent start|stop|update):
|
|
||||||
# log_file: agent.log
|
|
||||||
# pid_file: agent.pid
|
|
||||||
# channel: stable # or beta — used by agent update
|
|
||||||
# asset: # optional streamd-* override
|
|
||||||
# keep_old: 10
|
|
||||||
# Required for key fetch. Relative paths resolve from the install/repo root.
|
|
||||||
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
|
|
||||||
# python: # optional override; default = <root>/.venv/…
|
|
||||||
wvd: data/device.wvd
|
|
||||||
# user_agent: "" # optional license-request User-Agent
|
# user_agent: "" # optional license-request User-Agent
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,21 +9,17 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
"drmdecryption/apps/agent/internal/client"
|
||||||
"streamd/apps/agent/internal/config"
|
"drmdecryption/apps/agent/internal/config"
|
||||||
"streamd/apps/agent/internal/device"
|
"drmdecryption/apps/agent/internal/device"
|
||||||
"streamd/apps/agent/internal/modsync"
|
"drmdecryption/apps/agent/internal/modsync"
|
||||||
"streamd/apps/agent/internal/poller"
|
"drmdecryption/apps/agent/internal/poller"
|
||||||
"streamd/apps/agent/internal/queue"
|
"drmdecryption/apps/agent/internal/queue"
|
||||||
"streamd/apps/agent/internal/worker"
|
"drmdecryption/apps/agent/internal/worker"
|
||||||
"streamd/apps/agent/internal/wsclient"
|
"drmdecryption/apps/agent/internal/wsclient"
|
||||||
"streamd/modhost"
|
|
||||||
"streamd/repo"
|
|
||||||
"streamd/wvkey"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
||||||
|
|
@ -39,14 +35,6 @@ func Run(args []string) error {
|
||||||
switch sub {
|
switch sub {
|
||||||
case "run":
|
case "run":
|
||||||
runCmd(sub, rest)
|
runCmd(sub, rest)
|
||||||
case "start":
|
|
||||||
return startDaemonCmd(rest)
|
|
||||||
case "stop":
|
|
||||||
return stopDaemonCmd(rest)
|
|
||||||
case "restart":
|
|
||||||
return restartDaemonCmd(rest)
|
|
||||||
case "update":
|
|
||||||
return updateDaemonCmd(rest)
|
|
||||||
case "status":
|
case "status":
|
||||||
statusCmd(sub, rest)
|
statusCmd(sub, rest)
|
||||||
case "devices":
|
case "devices":
|
||||||
|
|
@ -69,13 +57,8 @@ func Usage() {
|
||||||
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
agent start [--config agent.yaml] # background (pid + log)
|
agent run [--config apps/agent/agent.yaml]
|
||||||
agent stop [--config ...]
|
agent status [--config ...]
|
||||||
agent restart [--config ...]
|
|
||||||
agent status [--config ...] # process + recent jobs
|
|
||||||
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
|
|
||||||
agent run [--config ...] # foreground (debug)
|
|
||||||
|
|
||||||
agent devices [--config ...]
|
agent devices [--config ...]
|
||||||
agent enqueue --stream NAME [--reason manual] [--config ...]
|
agent enqueue --stream NAME [--reason manual] [--config ...]
|
||||||
agent cancel --job ID [--config ...]
|
agent cancel --job ID [--config ...]
|
||||||
|
|
@ -84,9 +67,6 @@ Polls streamd for enabled streams that are down / missing credentials,
|
||||||
enqueues jobs, claims a free phone that already has the app, captures
|
enqueues jobs, claims a free phone that already has the app, captures
|
||||||
via MITM, POSTs credentials, then force-stops the app.
|
via MITM, POSTs credentials, then force-stops the app.
|
||||||
|
|
||||||
Job retries default to immediate (job_backoff: false). Set job_backoff: true
|
|
||||||
in agent.yaml for exponential delays when several agents share work.
|
|
||||||
|
|
||||||
Does not install apps. Does not run NRE/ffmpeg.
|
Does not install apps. Does not run NRE/ffmpeg.
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|
@ -102,14 +82,6 @@ func loadCfg(sub string, args []string) (config.Config, *flag.FlagSet) {
|
||||||
return cfg, fs
|
return cfg, fs
|
||||||
}
|
}
|
||||||
|
|
||||||
// newAPI builds the streamd client with this agent's identity attached, so
|
|
||||||
// audit rows in streamd name the agent and not just its API key.
|
|
||||||
func newAPI(cfg config.Config) *client.Client {
|
|
||||||
c := client.New(cfg.StreamdURL, cfg.Token)
|
|
||||||
c.AgentID = cfg.AgentID
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func openQueue(cfg config.Config) *queue.Store {
|
func openQueue(cfg config.Config) *queue.Store {
|
||||||
q, err := queue.Open(cfg.DataDir)
|
q, err := queue.Open(cfg.DataDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -120,34 +92,10 @@ func openQueue(cfg config.Config) *queue.Store {
|
||||||
|
|
||||||
func runCmd(sub string, args []string) {
|
func runCmd(sub string, args []string) {
|
||||||
cfg, _ := loadCfg(sub, args)
|
cfg, _ := loadCfg(sub, args)
|
||||||
api := newAPI(cfg)
|
api := client.New(cfg.StreamdURL, cfg.Token)
|
||||||
if err := api.Health(); err != nil {
|
if err := api.Health(); err != nil {
|
||||||
log.Fatalf("streamd unreachable at %s: %v", cfg.StreamdURL, err)
|
log.Fatalf("streamd unreachable at %s: %v", cfg.StreamdURL, err)
|
||||||
}
|
}
|
||||||
// Health says the server is up; /api/me says our credential actually
|
|
||||||
// works. Without this a missing or revoked key failed silently on every
|
|
||||||
// poll instead of once, loudly, at startup.
|
|
||||||
me, err := api.Me()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("streamd rejected this agent at %s: %v", cfg.StreamdURL, err)
|
|
||||||
}
|
|
||||||
if me.Role != "operator" && me.Role != "admin" {
|
|
||||||
log.Fatalf("this agent's credential has role %q, but capturing needs at least `operator` — "+
|
|
||||||
"create an operator API key in the streamd dashboard", me.Role)
|
|
||||||
}
|
|
||||||
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
|
|
||||||
|
|
||||||
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
|
|
||||||
// once per install root so Windows / Linux / macOS agents all work.
|
|
||||||
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
|
|
||||||
log.Fatalf("widevine helper: %v", err)
|
|
||||||
} else {
|
|
||||||
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
|
|
||||||
if strings.TrimSpace(cfg.Python) == "" {
|
|
||||||
cfg.Python = rt.Python
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
q := openQueue(cfg)
|
q := openQueue(cfg)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
|
|
||||||
|
|
@ -156,16 +104,6 @@ func runCmd(sub string, args []string) {
|
||||||
} else if n > 0 {
|
} else if n > 0 {
|
||||||
log.Printf("re-queued %d stuck running job(s) from previous run", n)
|
log.Printf("re-queued %d stuck running job(s) from previous run", n)
|
||||||
}
|
}
|
||||||
if n, err := q.ClearAllBackoffs(); err != nil {
|
|
||||||
log.Printf("clear backoffs: %v", err)
|
|
||||||
} else if n > 0 {
|
|
||||||
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
|
|
||||||
}
|
|
||||||
if cfg.JobBackoffEnabled() {
|
|
||||||
log.Printf("job_backoff=true (exponential delays after failures)")
|
|
||||||
} else {
|
|
||||||
log.Printf("job_backoff=false (retry failed captures immediately)")
|
|
||||||
}
|
|
||||||
|
|
||||||
pool := device.New("", cfg.Devices)
|
pool := device.New("", cfg.Devices)
|
||||||
stop := make(chan struct{})
|
stop := make(chan struct{})
|
||||||
|
|
@ -179,60 +117,18 @@ func runCmd(sub string, args []string) {
|
||||||
}
|
}
|
||||||
go p.Loop(stop)
|
go p.Loop(stop)
|
||||||
|
|
||||||
// Prefer the panel-synced modules cache for capture jobs.
|
|
||||||
if cfg.ModulesDir != "" {
|
|
||||||
if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
|
|
||||||
log.Fatalf("modules dir: %v", err)
|
|
||||||
}
|
|
||||||
log.Printf("modules dir %s", cfg.ModulesDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
var ms *modsync.Syncer
|
|
||||||
if cfg.SyncModules {
|
if cfg.SyncModules {
|
||||||
ms = &modsync.Syncer{
|
ms := &modsync.Syncer{
|
||||||
API: api,
|
API: api,
|
||||||
ModulesDir: cfg.ModulesDir,
|
ModulesDir: cfg.ModulesDir,
|
||||||
Interval: cfg.ModulesSyncInterval(),
|
Interval: cfg.ModulesSyncInterval(),
|
||||||
Prune: cfg.ModulesPrune,
|
|
||||||
Log: log.Default(),
|
Log: log.Default(),
|
||||||
}
|
}
|
||||||
go ms.Loop(stop)
|
go ms.Loop(stop)
|
||||||
log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
|
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())
|
||||||
// streamd pushes a capture request when a viewer wakes an on-demand
|
|
||||||
// stream or a scheduled event is about to start. Reacting here is what
|
|
||||||
// makes those responsive instead of up to one poll interval late.
|
|
||||||
ws.OnCapture = func(streamID int64, name, app, channel, reason string) {
|
|
||||||
if cfg.PushedCapturesArePriority() {
|
|
||||||
p.EnqueueNow(streamID, name, app, channel, reason)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if j, added, err := q.EnqueueIfIdle(streamID, name, app, channel, reason, cfg.MaxAttempts); err != nil {
|
|
||||||
log.Printf("pushed capture for %s failed: %v", name, err)
|
|
||||||
} else if added {
|
|
||||||
log.Printf("enqueued job=%d stream=%s reason=%s (pushed by streamd)", j.ID, name, reason)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A stream was edited: re-poll now rather than waiting out the interval.
|
|
||||||
ws.OnStreamChanged = func(name, reason string) {
|
|
||||||
go func() {
|
|
||||||
if err := p.Once(); err != nil {
|
|
||||||
log.Printf("re-poll after change to %s: %v", name, err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
ws.OnModulesChanged = func(name, reason string) {
|
|
||||||
if ms == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
if err := ms.Once(); err != nil {
|
|
||||||
log.Printf("modules sync after change to %s: %v", name, err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
go ws.Loop()
|
go ws.Loop()
|
||||||
|
|
||||||
for i := 0; i < cfg.Workers; i++ {
|
for i := 0; i < cfg.Workers; i++ {
|
||||||
|
|
@ -246,7 +142,6 @@ func runCmd(sub string, args []string) {
|
||||||
Python: cfg.Python,
|
Python: cfg.Python,
|
||||||
WVD: cfg.WVD,
|
WVD: cfg.WVD,
|
||||||
UserAgent: cfg.UserAgent,
|
UserAgent: cfg.UserAgent,
|
||||||
JobBackoff: cfg.JobBackoffEnabled(),
|
|
||||||
Log: log.Default(),
|
Log: log.Default(),
|
||||||
}
|
}
|
||||||
go w.Loop(stop)
|
go w.Loop(stop)
|
||||||
|
|
@ -267,7 +162,6 @@ func runCmd(sub string, args []string) {
|
||||||
|
|
||||||
func statusCmd(sub string, args []string) {
|
func statusCmd(sub string, args []string) {
|
||||||
cfg, _ := loadCfg(sub, args)
|
cfg, _ := loadCfg(sub, args)
|
||||||
printDaemonStatus(cfg)
|
|
||||||
q := openQueue(cfg)
|
q := openQueue(cfg)
|
||||||
defer q.Close()
|
defer q.Close()
|
||||||
jobs, err := q.ListRecent(40)
|
jobs, err := q.ListRecent(40)
|
||||||
|
|
@ -317,7 +211,7 @@ func enqueueCmd(args []string) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
api := newAPI(cfg)
|
api := client.New(cfg.StreamdURL, cfg.Token)
|
||||||
streams, err := api.ListStreams()
|
streams, err := api.ListStreams()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
|
|
||||||
|
|
@ -1,177 +0,0 @@
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/apps/agent/internal/config"
|
|
||||||
"streamd/repo"
|
|
||||||
)
|
|
||||||
|
|
||||||
func readPID(pidFile string) (int, error) {
|
|
||||||
b, err := os.ReadFile(pidFile)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return strconv.Atoi(strings.TrimSpace(string(b)))
|
|
||||||
}
|
|
||||||
|
|
||||||
func writePID(pidFile string, pid int) error {
|
|
||||||
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
|
|
||||||
}
|
|
||||||
|
|
||||||
func removePID(pidFile string) { _ = os.Remove(pidFile) }
|
|
||||||
|
|
||||||
func runningPID(cfg config.Config) (int, bool) {
|
|
||||||
pid, err := readPID(cfg.PIDFile)
|
|
||||||
if err != nil || pid <= 0 {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
if !signalAlive(pid) {
|
|
||||||
removePID(cfg.PIDFile)
|
|
||||||
return pid, false
|
|
||||||
}
|
|
||||||
return pid, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func printDaemonStatus(cfg config.Config) {
|
|
||||||
fmt.Printf("config: %s\n", cfgPathHint(cfg))
|
|
||||||
fmt.Printf("pid: %s\n", cfg.PIDFile)
|
|
||||||
fmt.Printf("log: %s\n", cfg.LogFile)
|
|
||||||
if pid, ok := runningPID(cfg); ok {
|
|
||||||
fmt.Printf("agent: running pid=%d\n", pid)
|
|
||||||
} else {
|
|
||||||
fmt.Println("agent: stopped")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func cfgPathHint(cfg config.Config) string {
|
|
||||||
// Best-effort: show data dir; exact yaml path was already resolved by Load.
|
|
||||||
return cfg.DataDir
|
|
||||||
}
|
|
||||||
|
|
||||||
func startDaemonCmd(args []string) error {
|
|
||||||
cfg, cfgFile := loadCfgWithPath("start", args)
|
|
||||||
if pid, ok := runningPID(cfg); ok {
|
|
||||||
fmt.Printf("agent already running (pid %d)\n", pid)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
exe, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
|
||||||
exe = resolved
|
|
||||||
}
|
|
||||||
runArgs := []string{"agent", "run"}
|
|
||||||
if cfgFile != "" {
|
|
||||||
runArgs = append(runArgs, "--config", cfgFile)
|
|
||||||
}
|
|
||||||
cmd := exec.Command(exe, runArgs...)
|
|
||||||
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
cmd.Stdout = logF
|
|
||||||
cmd.Stderr = logF
|
|
||||||
cmd.Stdin = nil
|
|
||||||
detachProcess(cmd)
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
_ = logF.Close()
|
|
||||||
return fmt.Errorf("start agent: %w", err)
|
|
||||||
}
|
|
||||||
pid := cmd.Process.Pid
|
|
||||||
_ = cmd.Process.Release()
|
|
||||||
_ = logF.Close()
|
|
||||||
if err := writePID(cfg.PIDFile, pid); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
if !signalAlive(pid) {
|
|
||||||
removePID(cfg.PIDFile)
|
|
||||||
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
|
|
||||||
}
|
|
||||||
fmt.Printf("agent started pid=%d\n", pid)
|
|
||||||
fmt.Printf("logs: %s\n", cfg.LogFile)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopDaemonCmd(args []string) error {
|
|
||||||
cfg, _ := loadCfgWithPath("stop", args)
|
|
||||||
pid, err := readPID(cfg.PIDFile)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
fmt.Println("agent is not running")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !signalAlive(pid) {
|
|
||||||
removePID(cfg.PIDFile)
|
|
||||||
fmt.Println("agent is not running (stale pid file removed)")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if err := signalTerminate(pid); err != nil {
|
|
||||||
return fmt.Errorf("stop pid %d: %w", pid, err)
|
|
||||||
}
|
|
||||||
deadline := time.Now().Add(8 * time.Second)
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
if !signalAlive(pid) {
|
|
||||||
removePID(cfg.PIDFile)
|
|
||||||
fmt.Printf("agent stopped (was pid %d)\n", pid)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
time.Sleep(200 * time.Millisecond)
|
|
||||||
}
|
|
||||||
_ = signalKill(pid)
|
|
||||||
time.Sleep(200 * time.Millisecond)
|
|
||||||
removePID(cfg.PIDFile)
|
|
||||||
fmt.Printf("agent killed (pid %d)\n", pid)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func restartDaemonCmd(args []string) error {
|
|
||||||
_ = stopDaemonCmd(args)
|
|
||||||
return startDaemonCmd(args)
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadCfgWithPath returns config and the resolved --config path (may be empty).
|
|
||||||
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
|
|
||||||
fs := flag.NewFlagSet(sub, flag.ExitOnError)
|
|
||||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
|
||||||
_ = fs.Parse(args)
|
|
||||||
path := strings.TrimSpace(*cfgPath)
|
|
||||||
cfg, err := config.Load(path)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintln(os.Stderr, "[!]", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if path == "" {
|
|
||||||
// Mirror config.Load default discovery for daemon child argv.
|
|
||||||
path = defaultConfigPath()
|
|
||||||
} else if !filepath.IsAbs(path) {
|
|
||||||
abs, err := filepath.Abs(path)
|
|
||||||
if err == nil {
|
|
||||||
path = abs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cfg, path
|
|
||||||
}
|
|
||||||
|
|
||||||
// defaultConfigPath matches config.Load("") discovery so the background child
|
|
||||||
// reopens the same yaml the parent resolved.
|
|
||||||
func defaultConfigPath() string {
|
|
||||||
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
|
|
||||||
}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
//go:build unix
|
|
||||||
|
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
func detachProcess(cmd *exec.Cmd) {
|
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalAlive(pid int) bool {
|
|
||||||
p, err := os.FindProcess(pid)
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return p.Signal(syscall.Signal(0)) == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalTerminate(pid int) error {
|
|
||||||
p, err := os.FindProcess(pid)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return p.Signal(syscall.SIGTERM)
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalKill(pid int) error {
|
|
||||||
p, err := os.FindProcess(pid)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return p.Signal(syscall.SIGKILL)
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
//go:build windows
|
|
||||||
|
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
|
||||||
|
|
||||||
func detachProcess(cmd *exec.Cmd) {
|
|
||||||
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
|
|
||||||
// stdout/stderr still reach the log file opened by the parent.
|
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
|
||||||
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalAlive(pid int) bool {
|
|
||||||
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
|
|
||||||
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
defer windows.CloseHandle(h)
|
|
||||||
var code uint32
|
|
||||||
if err := windows.GetExitCodeProcess(h, &code); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
const stillActive = 259 // STILL_ACTIVE
|
|
||||||
return code == stillActive
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalTerminate(pid int) error {
|
|
||||||
p, err := os.FindProcess(pid)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return p.Kill()
|
|
||||||
}
|
|
||||||
|
|
||||||
func signalKill(pid int) error {
|
|
||||||
return signalTerminate(pid)
|
|
||||||
}
|
|
||||||
|
|
@ -1,282 +0,0 @@
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/apps/agent/internal/config"
|
|
||||||
"streamd/repo"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
|
|
||||||
defaultChannel = "stable"
|
|
||||||
)
|
|
||||||
|
|
||||||
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
|
|
||||||
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
|
|
||||||
|
|
||||||
func defaultAssetName() string {
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "linux":
|
|
||||||
switch runtime.GOARCH {
|
|
||||||
case "amd64":
|
|
||||||
return "streamd-linux-amd64"
|
|
||||||
case "arm64":
|
|
||||||
return "streamd-linux-arm64"
|
|
||||||
}
|
|
||||||
case "darwin":
|
|
||||||
switch runtime.GOARCH {
|
|
||||||
case "amd64":
|
|
||||||
return "streamd-darwin-amd64"
|
|
||||||
case "arm64":
|
|
||||||
return "streamd-darwin-arm64"
|
|
||||||
}
|
|
||||||
case "windows":
|
|
||||||
switch runtime.GOARCH {
|
|
||||||
case "amd64":
|
|
||||||
return "streamd-windows-amd64.exe"
|
|
||||||
case "arm64":
|
|
||||||
return "streamd-windows-arm64.exe"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateURL(base, ref, asset string) string {
|
|
||||||
base = strings.TrimRight(base, "/")
|
|
||||||
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateDaemonCmd(args []string) error {
|
|
||||||
fs := flag.NewFlagSet("update", flag.ExitOnError)
|
|
||||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
|
||||||
beta := fs.Bool("beta", false, "use beta channel")
|
|
||||||
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
|
|
||||||
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
|
|
||||||
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
|
|
||||||
_ = fs.Parse(args)
|
|
||||||
|
|
||||||
path := strings.TrimSpace(*cfgPath)
|
|
||||||
cfg, err := config.Load(path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if path == "" {
|
|
||||||
path = defaultConfigPath()
|
|
||||||
} else if !filepath.IsAbs(path) {
|
|
||||||
if abs, err := filepath.Abs(path); err == nil {
|
|
||||||
path = abs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
channel := cfg.Channel
|
|
||||||
if channel == "" {
|
|
||||||
channel = defaultChannel
|
|
||||||
}
|
|
||||||
if *beta {
|
|
||||||
channel = "beta"
|
|
||||||
}
|
|
||||||
ref := channel
|
|
||||||
if strings.TrimSpace(*tag) != "" {
|
|
||||||
ref = strings.TrimSpace(*tag)
|
|
||||||
}
|
|
||||||
asset := cfg.Asset
|
|
||||||
if asset == "" {
|
|
||||||
asset = defaultAssetName()
|
|
||||||
}
|
|
||||||
if asset == "" {
|
|
||||||
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
|
|
||||||
}
|
|
||||||
keepN := 10
|
|
||||||
if cfg.KeepOld != nil {
|
|
||||||
keepN = *cfg.KeepOld
|
|
||||||
}
|
|
||||||
if *keep >= 0 {
|
|
||||||
keepN = *keep
|
|
||||||
}
|
|
||||||
|
|
||||||
installRoot := repo.Root()
|
|
||||||
url := updateURL(releaseBaseURL, ref, asset)
|
|
||||||
fmt.Printf("agent update: downloading %s\n", url)
|
|
||||||
|
|
||||||
tmp, err := downloadToTemp(installRoot, url)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer os.Remove(tmp)
|
|
||||||
|
|
||||||
if err := smokeTestBinary(tmp); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
exe, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
|
||||||
exe = resolved
|
|
||||||
}
|
|
||||||
target := exe
|
|
||||||
wantName := "streamd"
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
wantName = "streamd.exe"
|
|
||||||
}
|
|
||||||
// Prefer well-known names in the install / Downloads tree.
|
|
||||||
for _, candidate := range []string{
|
|
||||||
filepath.Join(installRoot, wantName),
|
|
||||||
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
|
|
||||||
filepath.Join(installRoot, "streamd-linux-amd64"),
|
|
||||||
filepath.Join(installRoot, "bin", wantName),
|
|
||||||
} {
|
|
||||||
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
|
|
||||||
target = candidate
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If the running exe is already a streamd binary in this tree, prefer it.
|
|
||||||
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
|
|
||||||
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
|
|
||||||
target = exe
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := runningPID(cfg); ok {
|
|
||||||
fmt.Println("agent update: stopping running agent…")
|
|
||||||
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
oldDir := filepath.Join(filepath.Dir(target), "old")
|
|
||||||
if err := os.MkdirAll(oldDir, 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
stamp := time.Now().UTC().Format("20060102T150405Z")
|
|
||||||
archive := filepath.Join(oldDir, "streamd."+stamp)
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
archive += ".exe"
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(archive); err == nil {
|
|
||||||
archive += "." + fmt.Sprint(os.Getpid())
|
|
||||||
}
|
|
||||||
|
|
||||||
if *noRestart {
|
|
||||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
|
|
||||||
} else {
|
|
||||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
|
|
||||||
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
|
|
||||||
}
|
|
||||||
if err := replaceBinary(target, tmp, archive); err != nil {
|
|
||||||
if err == errUpdateDeferred {
|
|
||||||
return nil // helper finishes after exit; treat as success for CLI
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
fmt.Printf("agent update: archived previous → %s\n", archive)
|
|
||||||
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
|
|
||||||
pruneOldBinaries(oldDir, keepN)
|
|
||||||
|
|
||||||
if *noRestart {
|
|
||||||
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
fmt.Println("agent update: starting…")
|
|
||||||
return startDaemonCmd([]string{"--config", path})
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadToTemp(dir, url string) (string, error) {
|
|
||||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
f, err := os.CreateTemp(dir, ".streamd-download-*")
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
path := f.Name()
|
|
||||||
resp, err := http.Get(url)
|
|
||||||
if err != nil {
|
|
||||||
_ = f.Close()
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
_ = f.Close()
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
|
|
||||||
}
|
|
||||||
n, err := io.Copy(f, resp.Body)
|
|
||||||
closeErr := f.Close()
|
|
||||||
if err != nil {
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if closeErr != nil {
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", closeErr
|
|
||||||
}
|
|
||||||
if n < 1024 {
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
|
|
||||||
}
|
|
||||||
head, _ := os.ReadFile(path)
|
|
||||||
if len(head) > 32 {
|
|
||||||
h := strings.ToLower(string(head[:32]))
|
|
||||||
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
|
|
||||||
_ = os.Remove(path)
|
|
||||||
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = os.Chmod(path, 0o755)
|
|
||||||
return path, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func smokeTestBinary(path string) error {
|
|
||||||
cmd := exec.Command(path, "help")
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
text := string(out)
|
|
||||||
if err != nil {
|
|
||||||
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
|
|
||||||
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func pruneOldBinaries(oldDir string, keep int) {
|
|
||||||
if keep <= 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ents, err := os.ReadDir(oldDir)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var names []string
|
|
||||||
for _, e := range ents {
|
|
||||||
if e.IsDir() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
n := e.Name()
|
|
||||||
if strings.HasPrefix(n, "streamd.") {
|
|
||||||
names = append(names, n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Strings(names)
|
|
||||||
if len(names) <= keep {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, n := range names[:len(names)-keep] {
|
|
||||||
_ = os.Remove(filepath.Join(oldDir, n))
|
|
||||||
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
//go:build unix
|
|
||||||
|
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
// replaceBinary moves the live binary to archive, then moves next into place.
|
|
||||||
func replaceBinary(target, next, archive string) error {
|
|
||||||
if err := os.Rename(target, archive); err != nil {
|
|
||||||
return fmt.Errorf("archive current binary: %w", err)
|
|
||||||
}
|
|
||||||
if err := os.Rename(next, target); err != nil {
|
|
||||||
_ = os.Rename(archive, target)
|
|
||||||
return fmt.Errorf("install new binary: %w", err)
|
|
||||||
}
|
|
||||||
_ = os.Chmod(target, 0o755)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
//go:build windows
|
|
||||||
|
|
||||||
package agentcmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
|
|
||||||
// 1. Move target → archive when target is not our own running image.
|
|
||||||
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
|
|
||||||
// waits for this PID to exit, then swaps and optionally starts the agent.
|
|
||||||
func replaceBinary(target, next, archive string) error {
|
|
||||||
self, _ := os.Executable()
|
|
||||||
if resolved, err := filepath.EvalSymlinks(self); err == nil {
|
|
||||||
self = resolved
|
|
||||||
}
|
|
||||||
same, _ := sameFile(self, target)
|
|
||||||
|
|
||||||
if !same {
|
|
||||||
if err := os.Rename(target, archive); err != nil {
|
|
||||||
if err2 := copyFile(target, archive); err2 != nil {
|
|
||||||
return fmt.Errorf("archive current binary: %v / %w", err, err2)
|
|
||||||
}
|
|
||||||
_ = os.Remove(target)
|
|
||||||
}
|
|
||||||
if err := os.Rename(next, target); err != nil {
|
|
||||||
if err2 := copyFile(next, target); err2 != nil {
|
|
||||||
_ = os.Rename(archive, target)
|
|
||||||
return fmt.Errorf("install new binary: %v / %w", err, err2)
|
|
||||||
}
|
|
||||||
_ = os.Remove(next)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
newPath := target + ".new"
|
|
||||||
_ = os.Remove(newPath)
|
|
||||||
if err := os.Rename(next, newPath); err != nil {
|
|
||||||
if err2 := copyFile(next, newPath); err2 != nil {
|
|
||||||
return fmt.Errorf("stage new binary: %v / %w", err, err2)
|
|
||||||
}
|
|
||||||
_ = os.Remove(next)
|
|
||||||
}
|
|
||||||
|
|
||||||
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
|
|
||||||
pid := os.Getpid()
|
|
||||||
startLine := ""
|
|
||||||
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
|
|
||||||
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
|
|
||||||
if cfg != "" {
|
|
||||||
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
|
|
||||||
} else {
|
|
||||||
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
script := fmt.Sprintf(""+
|
|
||||||
"@echo off\r\n"+
|
|
||||||
":wait\r\n"+
|
|
||||||
"timeout /t 1 /nobreak >nul\r\n"+
|
|
||||||
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
|
|
||||||
"if not errorlevel 1 goto wait\r\n"+
|
|
||||||
"move /Y \"%s\" \"%s\"\r\n"+
|
|
||||||
"move /Y \"%s\" \"%s\"\r\n"+
|
|
||||||
"%s"+
|
|
||||||
"del \"%%~f0\"\r\n",
|
|
||||||
pid, pid,
|
|
||||||
escapeCmd(target), escapeCmd(archive),
|
|
||||||
escapeCmd(newPath), escapeCmd(target),
|
|
||||||
startLine,
|
|
||||||
)
|
|
||||||
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
cmd := exec.Command("cmd.exe", "/C", helper)
|
|
||||||
cmd.Stdout = nil
|
|
||||||
cmd.Stderr = nil
|
|
||||||
detachProcess(cmd)
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
return fmt.Errorf("start update helper: %w", err)
|
|
||||||
}
|
|
||||||
_ = cmd.Process.Release()
|
|
||||||
fmt.Println("agent update: scheduled file swap after this process exits")
|
|
||||||
fmt.Println("agent update: agent will restart automatically in 1–2s")
|
|
||||||
time.Sleep(300 * time.Millisecond)
|
|
||||||
return errUpdateDeferred
|
|
||||||
}
|
|
||||||
|
|
||||||
func escapeCmd(p string) string {
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func sameFile(a, b string) (bool, error) {
|
|
||||||
absA, err := filepath.Abs(a)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
absB, err := filepath.Abs(b)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return filepath.Clean(absA) == filepath.Clean(absB), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyFile(src, dst string) error {
|
|
||||||
in, err := os.Open(src)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer in.Close()
|
|
||||||
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, copyErr := out.ReadFrom(in)
|
|
||||||
closeErr := out.Close()
|
|
||||||
if copyErr != nil {
|
|
||||||
return copyErr
|
|
||||||
}
|
|
||||||
return closeErr
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
module streamd/apps/agent
|
module drmdecryption/apps/agent
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
drmdecryption v0.0.0
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.34.5
|
modernc.org/sqlite v1.34.5
|
||||||
streamd v0.0.0
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|
@ -15,10 +15,11 @@ require (
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
|
||||||
golang.org/x/sys v0.42.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
modernc.org/libc v1.55.3 // indirect
|
modernc.org/libc v1.55.3 // indirect
|
||||||
modernc.org/mathutil v1.6.0 // indirect
|
modernc.org/mathutil v1.6.0 // indirect
|
||||||
modernc.org/memory v1.8.0 // indirect
|
modernc.org/memory v1.8.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
replace streamd => ../pkg
|
replace drmdecryption => ../pkg
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
|
@ -12,6 +14,8 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
|
||||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
|
||||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
|
@ -19,6 +23,8 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||||
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|
|
||||||
|
|
@ -3,93 +3,42 @@ package client
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Version is reported in the User-Agent so streamd's audit log can tell
|
|
||||||
// agent builds apart.
|
|
||||||
const Version = "2.0"
|
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
BaseURL string
|
BaseURL string
|
||||||
Token string
|
Token string
|
||||||
HTTP *http.Client
|
HTTP *http.Client
|
||||||
UserAgent string
|
UserAgent string
|
||||||
// AgentID is sent as X-Agent-ID so streamd can attribute audit rows to
|
|
||||||
// this agent rather than just to the API key it shares.
|
|
||||||
AgentID string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrUnauthorized is returned when streamd rejects this agent's credential.
|
|
||||||
// It is checked by the worker so a bad key does not burn job attempts.
|
|
||||||
var ErrUnauthorized = errors.New("unauthorized")
|
|
||||||
|
|
||||||
func New(baseURL, token string) *Client {
|
func New(baseURL, token string) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||||
Token: token,
|
Token: token,
|
||||||
HTTP: &http.Client{Timeout: 30 * time.Second},
|
HTTP: &http.Client{Timeout: 30 * time.Second},
|
||||||
UserAgent: "drm-agent/" + Version,
|
UserAgent: "drm-agent/1.0",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stream is one row of GET /api/streams.
|
|
||||||
//
|
|
||||||
// Note there is no Key field. streamd redacts credentials from this response,
|
|
||||||
// and the agent only ever writes keys, never reads them. Decisions that used
|
|
||||||
// to be made here by inspecting the key are now made server-side and arrive
|
|
||||||
// as NeedsCapture / KeyValid / DRMRequired.
|
|
||||||
type Stream struct {
|
type Stream struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
App string `json:"app"`
|
App string `json:"app"`
|
||||||
Channel string `json:"channel"`
|
Channel string `json:"channel"`
|
||||||
Tags string `json:"tags"`
|
|
||||||
MPD string `json:"mpd"`
|
MPD string `json:"mpd"`
|
||||||
|
Key string `json:"key"`
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
Health string `json:"health"`
|
Health string `json:"health"`
|
||||||
LastError string `json:"last_error"`
|
LastError string `json:"last_error"`
|
||||||
PlaylistAgeS float64 `json:"playlist_age_s"`
|
PlaylistAgeS float64 `json:"playlist_age_s"`
|
||||||
ClaimedBy string `json:"claimed_by"`
|
ClaimedBy string `json:"claimed_by"`
|
||||||
|
|
||||||
// Credential state, without the credentials.
|
|
||||||
HasKey bool `json:"has_key"`
|
|
||||||
KeyValid bool `json:"key_valid"`
|
|
||||||
DRMRequired bool `json:"drm_required"`
|
|
||||||
// NeedsCapture is streamd's verdict on whether to refresh credentials.
|
|
||||||
// This is the field the poller acts on.
|
|
||||||
NeedsCapture bool `json:"needs_capture"`
|
|
||||||
|
|
||||||
OnDemand bool `json:"on_demand"`
|
|
||||||
Public bool `json:"public"`
|
|
||||||
|
|
||||||
Outputs []Output `json:"outputs"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Output is one configured publish format, shown by `agent status`.
|
|
||||||
type Output struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
Format string `json:"format"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnabledOutputs is a short label list for display, e.g. "HLS, DASH".
|
|
||||||
func (s Stream) EnabledOutputs() string {
|
|
||||||
var on []string
|
|
||||||
for _, o := range s.Outputs {
|
|
||||||
if o.Enabled {
|
|
||||||
on = append(on, o.Label)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return strings.Join(on, ",")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Credentials struct {
|
type Credentials struct {
|
||||||
|
|
@ -100,34 +49,11 @@ type Credentials struct {
|
||||||
PID string `json:"pid,omitempty"`
|
PID string `json:"pid,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Identity is the answer from GET /api/me.
|
|
||||||
type Identity struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
ActorKind string `json:"actor_kind"`
|
|
||||||
AgentID string `json:"agent_id,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) Health() error {
|
func (c *Client) Health() error {
|
||||||
_, err := c.do(http.MethodGet, "/api/health", nil)
|
_, err := c.do(http.MethodGet, "/api/health", nil)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Me verifies this agent's credential and reports the role it was granted.
|
|
||||||
// Called at startup so a missing, wrong or revoked key fails loudly instead
|
|
||||||
// of silently failing every poll.
|
|
||||||
func (c *Client) Me() (Identity, error) {
|
|
||||||
body, err := c.do(http.MethodGet, "/api/me", nil)
|
|
||||||
if err != nil {
|
|
||||||
return Identity{}, err
|
|
||||||
}
|
|
||||||
var id Identity
|
|
||||||
if err := json.Unmarshal(body, &id); err != nil {
|
|
||||||
return Identity{}, err
|
|
||||||
}
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) ListStreams() ([]Stream, error) {
|
func (c *Client) ListStreams() ([]Stream, error) {
|
||||||
body, err := c.do(http.MethodGet, "/api/streams", nil)
|
body, err := c.do(http.MethodGet, "/api/streams", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -159,35 +85,11 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Capture event kinds reported back to streamd, so a failing phone capture
|
|
||||||
// shows up on the stream's timeline in the dashboard instead of only in this
|
|
||||||
// agent's console.
|
|
||||||
const (
|
|
||||||
EventCaptureStarted = "capture_started"
|
|
||||||
EventCaptureOK = "capture_ok"
|
|
||||||
EventCaptureFailed = "capture_failed"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PostEvent records an agent-authored event against a stream. Failures are
|
|
||||||
// the caller's to ignore: losing a timeline entry must never fail a capture.
|
|
||||||
func (c *Client) PostEvent(streamID int64, kind, message string, detail map[string]any) error {
|
|
||||||
payload := map[string]any{"kind": kind, "message": message}
|
|
||||||
if len(detail) > 0 {
|
|
||||||
payload["detail"] = detail
|
|
||||||
}
|
|
||||||
_, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/events", streamID), payload)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ModuleInfo is one modules/<name>/ entry from GET /api/modules.
|
// ModuleInfo is one modules/<name>/ entry from GET /api/modules.
|
||||||
type ModuleInfo struct {
|
type ModuleInfo struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
HasYAML bool `json:"has_yaml"`
|
HasYAML bool `json:"has_yaml"`
|
||||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||||
HasPackage bool `json:"has_package"`
|
|
||||||
PackageSHA256 string `json:"package_sha256,omitempty"`
|
|
||||||
Arches []string `json:"arches,omitempty"`
|
|
||||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) ListModules() ([]ModuleInfo, error) {
|
func (c *Client) ListModules() ([]ModuleInfo, error) {
|
||||||
|
|
@ -204,72 +106,27 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
|
||||||
return wrap.Modules, nil
|
return wrap.Modules, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetModuleYAML downloads raw module.yaml bytes for name.
|
// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml).
|
||||||
func (c *Client) GetModuleYAML(name string) ([]byte, error) {
|
func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error {
|
||||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
|
req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes))
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
c.setHeaders(req)
|
|
||||||
resp, err := c.HTTP.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
|
||||||
if resp.StatusCode >= 300 {
|
|
||||||
return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
|
|
||||||
}
|
|
||||||
return body, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadModulePackage writes the module zip to destPath.
|
|
||||||
func (c *Client) DownloadModulePackage(name, destPath string) error {
|
|
||||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
c.setHeaders(req)
|
req.Header.Set("Content-Type", "text/yaml")
|
||||||
resp, err := c.HTTP.Do(req)
|
req.Header.Set("User-Agent", c.UserAgent)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode >= 300 {
|
|
||||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
||||||
return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
|
|
||||||
}
|
|
||||||
tmp := destPath + ".partial"
|
|
||||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
|
|
||||||
closeErr := f.Close()
|
|
||||||
if copyErr != nil {
|
|
||||||
_ = os.Remove(tmp)
|
|
||||||
return copyErr
|
|
||||||
}
|
|
||||||
if closeErr != nil {
|
|
||||||
_ = os.Remove(tmp)
|
|
||||||
return closeErr
|
|
||||||
}
|
|
||||||
_ = os.Remove(destPath)
|
|
||||||
return os.Rename(tmp, destPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) setHeaders(req *http.Request) {
|
|
||||||
ua := c.UserAgent
|
|
||||||
if ua == "" {
|
|
||||||
ua = "streamd-agent/" + Version
|
|
||||||
}
|
|
||||||
req.Header.Set("User-Agent", ua)
|
|
||||||
if c.Token != "" {
|
if c.Token != "" {
|
||||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||||
}
|
}
|
||||||
if c.AgentID != "" {
|
resp, err := c.HTTP.Do(req)
|
||||||
req.Header.Set("X-Agent-ID", c.AgentID)
|
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) {
|
||||||
|
|
@ -288,53 +145,18 @@ func (c *Client) do(method, path string, payload any) ([]byte, error) {
|
||||||
if payload != nil {
|
if payload != nil {
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
c.setHeaders(req)
|
req.Header.Set("User-Agent", c.UserAgent)
|
||||||
|
if c.Token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||||
|
}
|
||||||
resp, err := c.HTTP.Do(req)
|
resp, err := c.HTTP.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
body, _ := io.ReadAll(resp.Body)
|
||||||
if resp.StatusCode >= 300 {
|
if resp.StatusCode >= 300 {
|
||||||
return nil, c.statusError(method, path, resp, body)
|
return nil, fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, strings.TrimSpace(string(body)))
|
||||||
}
|
}
|
||||||
return body, nil
|
return body, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// statusError turns an HTTP failure into something actionable. A 401 or 403
|
|
||||||
// used to surface as a bare status line, which left an operator guessing why
|
|
||||||
// a working agent had gone quiet.
|
|
||||||
func (c *Client) statusError(method, path string, resp *http.Response, body []byte) error {
|
|
||||||
msg := strings.TrimSpace(string(body))
|
|
||||||
if parsed := errorField(body); parsed != "" {
|
|
||||||
msg = parsed
|
|
||||||
}
|
|
||||||
switch resp.StatusCode {
|
|
||||||
case http.StatusUnauthorized:
|
|
||||||
hint := "streamd rejected this agent's credential"
|
|
||||||
if c.Token == "" {
|
|
||||||
hint = "streamd requires a credential and none is configured"
|
|
||||||
}
|
|
||||||
return fmt.Errorf("%w: %s %s — %s. Set `token:` (or `api_key:`) in apps/agent/agent.yaml, "+
|
|
||||||
"or STREAMD_TOKEN, to an API key created in the streamd dashboard under "+
|
|
||||||
"Settings -> API keys (role: operator). Server said: %s",
|
|
||||||
ErrUnauthorized, method, path, hint, msg)
|
|
||||||
case http.StatusForbidden:
|
|
||||||
return fmt.Errorf("%w: %s %s — this agent's API key lacks the needed role; "+
|
|
||||||
"it must be at least `operator`. Server said: %s", ErrUnauthorized, method, path, msg)
|
|
||||||
case http.StatusTooManyRequests:
|
|
||||||
return fmt.Errorf("%s %s: rate limited by streamd (retry-after %s) — %s",
|
|
||||||
method, path, resp.Header.Get("Retry-After"), msg)
|
|
||||||
}
|
|
||||||
return fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func errorField(body []byte) string {
|
|
||||||
var wrap struct {
|
|
||||||
Error string `json:"error"`
|
|
||||||
}
|
|
||||||
if json.Unmarshal(body, &wrap) == nil {
|
|
||||||
return strings.TrimSpace(wrap.Error)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -7,16 +7,12 @@ import (
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
StreamdURL string `yaml:"streamd_url"`
|
StreamdURL string `yaml:"streamd_url"`
|
||||||
// Token is this agent's streamd credential. It is now an API key created
|
|
||||||
// in the dashboard (Settings -> API keys, role operator) rather than the
|
|
||||||
// one shared secret; `api_key` is a clearer alias for the same field.
|
|
||||||
Token string `yaml:"token"`
|
Token string `yaml:"token"`
|
||||||
APIKey string `yaml:"api_key"`
|
|
||||||
PollIntervalSec int `yaml:"poll_interval_sec"`
|
PollIntervalSec int `yaml:"poll_interval_sec"`
|
||||||
DataDir string `yaml:"data_dir"`
|
DataDir string `yaml:"data_dir"`
|
||||||
Workers int `yaml:"workers"`
|
Workers int `yaml:"workers"`
|
||||||
|
|
@ -27,37 +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 pulls modules from streamd into the local cache when missing/stale.
|
// SyncModules pushes local modules/<name>/module.yaml to streamd when missing/stale.
|
||||||
SyncModules bool `yaml:"sync_modules"`
|
SyncModules bool `yaml:"sync_modules"`
|
||||||
ModulesDir string `yaml:"modules_dir"` // empty = <data_dir>/modules
|
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
|
||||||
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
||||||
ModulesPrune bool `yaml:"modules_prune"` // remove local modules absent from panel
|
|
||||||
// OnDemandPriority lets a capture that streamd pushed — a viewer waking
|
|
||||||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
|
||||||
// of routine refreshes in the queue.
|
|
||||||
OnDemandPriority *bool `yaml:"ondemand_priority"`
|
|
||||||
// JobBackoff enables exponential retry delays after a failed capture
|
|
||||||
// (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
|
|
||||||
// Set job_backoff: true when several agents share the same streams.
|
|
||||||
JobBackoff *bool `yaml:"job_backoff"`
|
|
||||||
// Daemon / update (streamd agent start|stop|update)
|
|
||||||
LogFile string `yaml:"log_file"` // default agent.log next to config / install root
|
|
||||||
PIDFile string `yaml:"pid_file"` // default agent.pid
|
|
||||||
Channel string `yaml:"channel"` // stable|beta for agent update
|
|
||||||
Asset string `yaml:"asset"` // optional streamd-* asset override
|
|
||||||
KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushedCapturesArePriority reports whether pushed captures jump the queue.
|
|
||||||
// Defaults to true: somebody is waiting on them.
|
|
||||||
func (c Config) PushedCapturesArePriority() bool {
|
|
||||||
return c.OnDemandPriority == nil || *c.OnDemandPriority
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobBackoffEnabled is the exponential multi-agent retry delay.
|
|
||||||
// Defaults to false so a lone agent retries immediately after a failure.
|
|
||||||
func (c Config) JobBackoffEnabled() bool {
|
|
||||||
return c.JobBackoff != nil && *c.JobBackoff
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c Config) PollInterval() time.Duration {
|
func (c Config) PollInterval() time.Duration {
|
||||||
|
|
@ -103,15 +72,9 @@ func applyDefaults(cfg Config, root string) Config {
|
||||||
if cfg.StreamdURL == "" {
|
if cfg.StreamdURL == "" {
|
||||||
cfg.StreamdURL = "http://127.0.0.1:8083"
|
cfg.StreamdURL = "http://127.0.0.1:8083"
|
||||||
}
|
}
|
||||||
if cfg.Token == "" {
|
|
||||||
cfg.Token = cfg.APIKey
|
|
||||||
}
|
|
||||||
if cfg.Token == "" {
|
if cfg.Token == "" {
|
||||||
cfg.Token = os.Getenv("STREAMD_TOKEN")
|
cfg.Token = os.Getenv("STREAMD_TOKEN")
|
||||||
}
|
}
|
||||||
if cfg.Token == "" {
|
|
||||||
cfg.Token = os.Getenv("STREAMD_API_KEY")
|
|
||||||
}
|
|
||||||
if cfg.PollIntervalSec <= 0 {
|
if cfg.PollIntervalSec <= 0 {
|
||||||
cfg.PollIntervalSec = 30
|
cfg.PollIntervalSec = 30
|
||||||
}
|
}
|
||||||
|
|
@ -141,36 +104,12 @@ func applyDefaults(cfg Config, root string) Config {
|
||||||
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
||||||
cfg.WVD = filepath.Join(root, cfg.WVD)
|
cfg.WVD = filepath.Join(root, cfg.WVD)
|
||||||
}
|
}
|
||||||
if cfg.Python != "" && !filepath.IsAbs(cfg.Python) {
|
if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
|
||||||
cfg.Python = filepath.Join(root, cfg.Python)
|
|
||||||
}
|
|
||||||
if cfg.ModulesDir == "" {
|
|
||||||
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
|
||||||
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
|
||||||
cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
|
cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
|
||||||
}
|
}
|
||||||
if cfg.ModulesSyncIntervalSec <= 0 {
|
if cfg.ModulesSyncIntervalSec <= 0 {
|
||||||
cfg.ModulesSyncIntervalSec = 300
|
cfg.ModulesSyncIntervalSec = 300
|
||||||
}
|
}
|
||||||
if cfg.LogFile == "" {
|
|
||||||
cfg.LogFile = "agent.log"
|
|
||||||
}
|
|
||||||
if !filepath.IsAbs(cfg.LogFile) {
|
|
||||||
cfg.LogFile = filepath.Join(root, cfg.LogFile)
|
|
||||||
}
|
|
||||||
if cfg.PIDFile == "" {
|
|
||||||
cfg.PIDFile = "agent.pid"
|
|
||||||
}
|
|
||||||
if !filepath.IsAbs(cfg.PIDFile) {
|
|
||||||
cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
|
|
||||||
}
|
|
||||||
if cfg.Channel == "" {
|
|
||||||
cfg.Channel = "stable"
|
|
||||||
}
|
|
||||||
if cfg.KeepOld == nil {
|
|
||||||
k := 10
|
|
||||||
cfg.KeepOld = &k
|
|
||||||
}
|
|
||||||
return cfg
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,15 +4,15 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pool tracks free/busy ADB devices. Never installs apps.
|
// Pool tracks free/busy ADB devices. Never installs apps.
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
adbBin string
|
adbBin string
|
||||||
allow map[string]bool // empty allow = all serials
|
allow map[string]bool // empty allow = all serials
|
||||||
busy map[string]string // serial → job label
|
busy map[string]string // serial → job label
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(adbBin string, allowlist []string) *Pool {
|
func New(adbBin string, allowlist []string) *Pool {
|
||||||
|
|
|
||||||
|
|
@ -1,32 +1,26 @@
|
||||||
// Package modsync pulls provider modules from streamd into a local cache.
|
// Package modsync pushes local modules/<name>/module.yaml to streamd
|
||||||
// The panel is the source of truth: agents download package.zip when the
|
// when the remote copy is missing or the SHA-256 differs.
|
||||||
// package hash changes, and module.yaml alone when only YAML changed.
|
|
||||||
package modsync
|
package modsync
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
"drmdecryption/apps/agent/internal/client"
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Syncer keeps the local modules cache aligned with streamd.
|
// Syncer compares local module.yaml files to streamd and PUTs updates.
|
||||||
type Syncer struct {
|
type Syncer struct {
|
||||||
API *client.Client
|
API *client.Client
|
||||||
ModulesDir string // empty = <data_dir>/modules resolved by caller, or modhost default
|
ModulesDir string // empty = modhost.ModulesDir(repo.Root())
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
Prune bool // remove local modules absent from the panel
|
|
||||||
Log *log.Logger
|
Log *log.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -37,10 +31,15 @@ func (s *Syncer) modulesDir() string {
|
||||||
return modhost.ModulesDir(repo.Root())
|
return modhost.ModulesDir(repo.Root())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Once pulls every remote module that is missing or stale locally.
|
// Once uploads every local module.yaml that is missing or stale on streamd.
|
||||||
func (s *Syncer) Once() error {
|
func (s *Syncer) Once() error {
|
||||||
dir := s.modulesDir()
|
dir := s.modulesDir()
|
||||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
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
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -48,139 +47,42 @@ func (s *Syncer) Once() error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
seen := map[string]struct{}{}
|
byName := make(map[string]client.ModuleInfo, len(remote))
|
||||||
for _, m := range remote {
|
for _, m := range remote {
|
||||||
seen[m.Name] = struct{}{}
|
byName[m.Name] = m
|
||||||
if err := s.syncOne(dir, m); err != nil {
|
|
||||||
s.logf("modules sync: %s: %v", m.Name, err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if s.Prune {
|
|
||||||
s.pruneLocal(dir, seen)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
|
|
||||||
modDir := filepath.Join(dir, m.Name)
|
|
||||||
localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
|
|
||||||
localYAML := ""
|
|
||||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
|
||||||
sum := sha256.Sum256(raw)
|
|
||||||
localYAML = hex.EncodeToString(sum[:])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
|
|
||||||
needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
|
|
||||||
|
|
||||||
if !needPackage && !needYAML {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if needPackage {
|
|
||||||
if !m.HasPackage {
|
|
||||||
return fmt.Errorf("panel has no package.zip")
|
|
||||||
}
|
|
||||||
if err := s.pullPackage(modDir, m); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
s.logf("modules sync: pulled package %s", m.Name)
|
|
||||||
// Package extract includes yaml; refresh localYAML check.
|
|
||||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
|
||||||
sum := sha256.Sum256(raw)
|
|
||||||
localYAML = hex.EncodeToString(sum[:])
|
|
||||||
needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
|
|
||||||
} else {
|
|
||||||
needYAML = m.HasYAML
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if needYAML {
|
|
||||||
raw, err := s.API.GetModuleYAML(m.Name)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
s.logf("modules sync: updated yaml %s", m.Name)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
|
|
||||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
zipPath := filepath.Join(modDir, "package.zip")
|
|
||||||
if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
sum, err := fileSHA256(zipPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
|
|
||||||
return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
|
|
||||||
}
|
|
||||||
|
|
||||||
extractDir := filepath.Join(modDir, ".extract-tmp")
|
|
||||||
_ = os.RemoveAll(extractDir)
|
|
||||||
if err := os.MkdirAll(extractDir, 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer os.RemoveAll(extractDir)
|
|
||||||
|
|
||||||
if err := unzipSafe(zipPath, extractDir); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
// Flatten a single top-level folder (bbc/...) into extractDir root.
|
|
||||||
if err := flattenSingleRoot(extractDir); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := promoteHostBinary(extractDir, m.Name); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move extracted contents into modDir (keep package.zip + sha sidecar).
|
|
||||||
ents, err := os.ReadDir(extractDir)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, e := range ents {
|
|
||||||
src := filepath.Join(extractDir, e.Name())
|
|
||||||
dst := filepath.Join(modDir, e.Name())
|
|
||||||
_ = os.RemoveAll(dst)
|
|
||||||
if err := os.Rename(src, dst); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
|
|
||||||
ents, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, e := range ents {
|
for _, e := range ents {
|
||||||
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if _, ok := keep[e.Name()]; ok {
|
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
|
continue
|
||||||
}
|
}
|
||||||
path := filepath.Join(dir, e.Name())
|
sum := sha256.Sum256(raw)
|
||||||
if err := os.RemoveAll(path); err != nil {
|
localSHA := hex.EncodeToString(sum[:])
|
||||||
s.logf("modules sync: prune %s: %v", e.Name(), err)
|
rm, ok := byName[name]
|
||||||
|
if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
s.logf("modules sync: pruned %s", e.Name())
|
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.
|
// Loop runs Once immediately, then on Interval until stop closes.
|
||||||
|
|
@ -217,161 +119,3 @@ func (s *Syncer) logf(format string, args ...any) {
|
||||||
}
|
}
|
||||||
log.Printf(format, args...)
|
log.Printf(format, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func localSHA(path string) string {
|
|
||||||
b, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(string(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
func fileSHA256(path string) (string, error) {
|
|
||||||
f, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
h := sha256.New()
|
|
||||||
if _, err := io.Copy(h, f); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return hex.EncodeToString(h.Sum(nil)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func atomicWrite(path string, data []byte, mode os.FileMode) error {
|
|
||||||
tmp := path + ".tmp"
|
|
||||||
if err := os.WriteFile(tmp, data, mode); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := os.Rename(tmp, path); err != nil {
|
|
||||||
_ = os.Remove(tmp)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func unzipSafe(zipPath, destDir string) error {
|
|
||||||
r, err := zip.OpenReader(zipPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer r.Close()
|
|
||||||
absDest, err := filepath.Abs(destDir)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, f := range r.File {
|
|
||||||
name := strings.ReplaceAll(f.Name, "\\", "/")
|
|
||||||
name = strings.TrimPrefix(name, "./")
|
|
||||||
if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.Contains(name, "..") {
|
|
||||||
return fmt.Errorf("zip slip: %s", f.Name)
|
|
||||||
}
|
|
||||||
target := filepath.Join(destDir, filepath.FromSlash(name))
|
|
||||||
absTarget, err := filepath.Abs(target)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rel, err := filepath.Rel(absDest, absTarget)
|
|
||||||
if err != nil || strings.HasPrefix(rel, "..") {
|
|
||||||
return fmt.Errorf("zip slip: %s", f.Name)
|
|
||||||
}
|
|
||||||
if f.FileInfo().IsDir() || strings.HasSuffix(name, "/") {
|
|
||||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rc, err := f.Open()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
mode := os.FileMode(0o644)
|
|
||||||
if f.Mode()&0o111 != 0 {
|
|
||||||
mode = 0o755
|
|
||||||
}
|
|
||||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
|
||||||
if err != nil {
|
|
||||||
_ = rc.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, copyErr := io.Copy(out, rc)
|
|
||||||
_ = out.Close()
|
|
||||||
_ = rc.Close()
|
|
||||||
if copyErr != nil {
|
|
||||||
return copyErr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func flattenSingleRoot(dir string) error {
|
|
||||||
ents, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var dirs []os.DirEntry
|
|
||||||
var files []os.DirEntry
|
|
||||||
for _, e := range ents {
|
|
||||||
if strings.HasPrefix(e.Name(), ".") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if e.IsDir() {
|
|
||||||
dirs = append(dirs, e)
|
|
||||||
} else {
|
|
||||||
files = append(files, e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(files) > 0 || len(dirs) != 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
root := filepath.Join(dir, dirs[0].Name())
|
|
||||||
inner, err := os.ReadDir(root)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, e := range inner {
|
|
||||||
src := filepath.Join(root, e.Name())
|
|
||||||
dst := filepath.Join(dir, e.Name())
|
|
||||||
if err := os.Rename(src, dst); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return os.RemoveAll(root)
|
|
||||||
}
|
|
||||||
|
|
||||||
func promoteHostBinary(modDir, name string) error {
|
|
||||||
want := name
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
want += ".exe"
|
|
||||||
}
|
|
||||||
dest := filepath.Join(modDir, ".bin", want)
|
|
||||||
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
src := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH, want)
|
|
||||||
in, err := os.Open(src)
|
|
||||||
if err != nil {
|
|
||||||
return nil // soft: host arch may be missing
|
|
||||||
}
|
|
||||||
defer in.Close()
|
|
||||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, copyErr := io.Copy(out, in)
|
|
||||||
closeErr := out.Close()
|
|
||||||
if copyErr != nil {
|
|
||||||
return copyErr
|
|
||||||
}
|
|
||||||
return closeErr
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,154 +0,0 @@
|
||||||
package modsync
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/zip"
|
|
||||||
"bytes"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPullPackageThenYAMLOnly(t *testing.T) {
|
|
||||||
arch := runtime.GOOS + "-" + runtime.GOARCH
|
|
||||||
binName := "demo"
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
binName += ".exe"
|
|
||||||
}
|
|
||||||
zip1 := mustZip(t, map[string][]byte{
|
|
||||||
"module.yaml": []byte("package: a\n"),
|
|
||||||
".bin/" + arch + "/" + binName: []byte("bin-v1"),
|
|
||||||
})
|
|
||||||
sum1 := sha256.Sum256(zip1)
|
|
||||||
pkgSHA1 := hex.EncodeToString(sum1[:])
|
|
||||||
yaml1SHA := sha256Hex([]byte("package: a\n"))
|
|
||||||
|
|
||||||
zip2 := mustZip(t, map[string][]byte{
|
|
||||||
"module.yaml": []byte("package: a\n"),
|
|
||||||
".bin/" + arch + "/" + binName: []byte("bin-v2"),
|
|
||||||
})
|
|
||||||
sum2 := sha256.Sum256(zip2)
|
|
||||||
pkgSHA2 := hex.EncodeToString(sum2[:])
|
|
||||||
|
|
||||||
yamlEdited := []byte("package: a\nchannels: {}\n")
|
|
||||||
yamlEditedSHA := sha256Hex(yamlEdited)
|
|
||||||
|
|
||||||
state := struct {
|
|
||||||
pkg []byte
|
|
||||||
pkgSHA string
|
|
||||||
yaml []byte
|
|
||||||
yamlSHA string
|
|
||||||
}{pkg: zip1, pkgSHA: pkgSHA1, yaml: []byte("package: a\n"), yamlSHA: yaml1SHA}
|
|
||||||
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch {
|
|
||||||
case r.URL.Path == "/api/modules" && r.Method == http.MethodGet:
|
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
||||||
"modules": []map[string]any{{
|
|
||||||
"name": "demo",
|
|
||||||
"has_yaml": true,
|
|
||||||
"yaml_sha256": state.yamlSHA,
|
|
||||||
"has_package": true,
|
|
||||||
"package_sha256": state.pkgSHA,
|
|
||||||
}},
|
|
||||||
})
|
|
||||||
case r.URL.Path == "/api/modules/demo/package":
|
|
||||||
w.Header().Set("Content-Type", "application/zip")
|
|
||||||
_, _ = w.Write(state.pkg)
|
|
||||||
case r.URL.Path == "/api/modules/demo/yaml":
|
|
||||||
w.Header().Set("Content-Type", "text/yaml")
|
|
||||||
_, _ = w.Write(state.yaml)
|
|
||||||
default:
|
|
||||||
http.NotFound(w, r)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
api := &client.Client{BaseURL: srv.URL, HTTP: srv.Client()}
|
|
||||||
s := &Syncer{API: api, ModulesDir: dir}
|
|
||||||
|
|
||||||
if err := s.Once(); err != nil {
|
|
||||||
t.Fatalf("first sync: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(filepath.Join(dir, "demo", "module.yaml")); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
promoted := filepath.Join(dir, "demo", ".bin", binName)
|
|
||||||
if b, err := os.ReadFile(promoted); err != nil || string(b) != "bin-v1" {
|
|
||||||
t.Fatalf("promoted binary: %v %q", err, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// YAML-only change on panel.
|
|
||||||
state.yaml = yamlEdited
|
|
||||||
state.yamlSHA = yamlEditedSHA
|
|
||||||
if err := s.Once(); err != nil {
|
|
||||||
t.Fatalf("yaml sync: %v", err)
|
|
||||||
}
|
|
||||||
raw, _ := os.ReadFile(filepath.Join(dir, "demo", "module.yaml"))
|
|
||||||
if !bytes.Equal(raw, yamlEdited) {
|
|
||||||
t.Fatalf("yaml not updated: %s", raw)
|
|
||||||
}
|
|
||||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v1" {
|
|
||||||
t.Fatalf("binary should be unchanged after yaml-only sync, got %q", b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Package change.
|
|
||||||
state.pkg = zip2
|
|
||||||
state.pkgSHA = pkgSHA2
|
|
||||||
state.yaml = []byte("package: a\n")
|
|
||||||
state.yamlSHA = yaml1SHA
|
|
||||||
if err := s.Once(); err != nil {
|
|
||||||
t.Fatalf("package sync: %v", err)
|
|
||||||
}
|
|
||||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v2" {
|
|
||||||
t.Fatalf("binary not updated: %q", b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mustZip(t *testing.T, files map[string][]byte) []byte {
|
|
||||||
t.Helper()
|
|
||||||
var buf bytes.Buffer
|
|
||||||
zw := zip.NewWriter(&buf)
|
|
||||||
for name, body := range files {
|
|
||||||
w, err := zw.Create(name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, err := w.Write(body); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := zw.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return buf.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
func sha256Hex(b []byte) string {
|
|
||||||
sum := sha256.Sum256(b)
|
|
||||||
return hex.EncodeToString(sum[:])
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUnzipSlip(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
var buf bytes.Buffer
|
|
||||||
zw := zip.NewWriter(&buf)
|
|
||||||
w, _ := zw.Create("../evil")
|
|
||||||
_, _ = w.Write([]byte("x"))
|
|
||||||
_ = zw.Close()
|
|
||||||
zipPath := filepath.Join(dir, "bad.zip")
|
|
||||||
_ = os.WriteFile(zipPath, buf.Bytes(), 0o644)
|
|
||||||
err := unzipSafe(zipPath, filepath.Join(dir, "out"))
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "slip") {
|
|
||||||
t.Fatalf("want zip slip error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -6,8 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
"drmdecryption/apps/agent/internal/client"
|
||||||
"streamd/apps/agent/internal/queue"
|
"drmdecryption/apps/agent/internal/queue"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Poller struct {
|
type Poller struct {
|
||||||
|
|
@ -51,27 +51,6 @@ func (p *Poller) Once() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnqueueNow is the entry point for a capture streamd has pushed over the
|
|
||||||
// websocket, for a viewer waking an on-demand stream or a scheduled event
|
|
||||||
// about to start. It jumps ahead of routine refreshes because somebody is
|
|
||||||
// waiting on it.
|
|
||||||
func (p *Poller) EnqueueNow(streamID int64, name, app, channel, reason string) {
|
|
||||||
if reason == "" {
|
|
||||||
reason = "requested"
|
|
||||||
}
|
|
||||||
j, added, err := p.Queue.EnqueueIfIdlePriority(
|
|
||||||
streamID, name, app, channel, reason, p.MaxAttempts, queue.PriorityInteractive)
|
|
||||||
switch {
|
|
||||||
case err != nil:
|
|
||||||
p.logf("push capture for stream %s failed: %v", name, err)
|
|
||||||
case added:
|
|
||||||
p.logf("enqueued job=%d stream=%s reason=%s (pushed by streamd, priority)", j.ID, name, reason)
|
|
||||||
default:
|
|
||||||
// Already queued or running: EnqueueIfIdlePriority promoted it.
|
|
||||||
p.logf("push capture for stream %s: a job is already pending (promoted)", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Poller) Loop(stop <-chan struct{}) {
|
func (p *Poller) Loop(stop <-chan struct{}) {
|
||||||
t := time.NewTicker(p.Interval)
|
t := time.NewTicker(p.Interval)
|
||||||
defer t.Stop()
|
defer t.Stop()
|
||||||
|
|
@ -88,24 +67,11 @@ func (p *Poller) Loop(stop <-chan struct{}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// needsRefresh decides whether a stream wants fresh credentials.
|
|
||||||
//
|
|
||||||
// The verdict comes from streamd, not from inspecting the key: credentials are
|
|
||||||
// redacted out of the stream list, so a local "is the key empty?" test would
|
|
||||||
// see every stream as broken and queue a capture for all of them forever.
|
|
||||||
// streamd also knows things this agent does not — whether the stream is clear
|
|
||||||
// rather than encrypted, whether it is an idle on-demand stream, and whether
|
|
||||||
// it is still inside its start-up window.
|
|
||||||
func needsRefresh(st client.Stream) string {
|
func needsRefresh(st client.Stream) string {
|
||||||
if !st.NeedsCapture {
|
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
|
||||||
return ""
|
return "missing_credentials"
|
||||||
}
|
}
|
||||||
switch {
|
if !validKeyPair(st.Key) {
|
||||||
case strings.TrimSpace(st.MPD) == "":
|
|
||||||
return "missing_credentials"
|
|
||||||
case st.DRMRequired && !st.HasKey:
|
|
||||||
return "missing_credentials"
|
|
||||||
case st.DRMRequired && !st.KeyValid:
|
|
||||||
return "invalid_credentials"
|
return "invalid_credentials"
|
||||||
}
|
}
|
||||||
h := strings.ToLower(strings.TrimSpace(st.Health))
|
h := strings.ToLower(strings.TrimSpace(st.Health))
|
||||||
|
|
@ -113,44 +79,27 @@ func needsRefresh(st client.Stream) string {
|
||||||
case "down", "error", "failed":
|
case "down", "error", "failed":
|
||||||
return "down"
|
return "down"
|
||||||
}
|
}
|
||||||
return "stale"
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
|
// validKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID ignored).
|
||||||
// ignored). The authoritative check lives in streamd; this copy exists only
|
func validKeyPair(key string) bool {
|
||||||
// to sanity-check what a worker is about to POST.
|
parts := strings.SplitN(strings.TrimSpace(key), ":", 2)
|
||||||
func ValidKeyPair(key string) bool {
|
if len(parts) != 2 {
|
||||||
for _, line := range splitKeyLines(key) {
|
return false
|
||||||
kid, k, ok := strings.Cut(line, ":")
|
|
||||||
if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return len(splitKeyLines(key)) > 0
|
hexOnly := func(s string) string {
|
||||||
}
|
var b strings.Builder
|
||||||
|
for _, r := range s {
|
||||||
// splitKeyLines mirrors how streamd and the packager split a key field, so a
|
switch {
|
||||||
// multi-KID capture is not mistaken for a malformed one.
|
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
||||||
func splitKeyLines(raw string) []string {
|
b.WriteRune(r)
|
||||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
}
|
||||||
var out []string
|
|
||||||
for _, line := range strings.Split(raw, "\n") {
|
|
||||||
if line = strings.TrimSpace(line); line != "" {
|
|
||||||
out = append(out, line)
|
|
||||||
}
|
}
|
||||||
|
return b.String()
|
||||||
}
|
}
|
||||||
return out
|
kid, k := hexOnly(parts[0]), hexOnly(parts[1])
|
||||||
}
|
return len(kid) == 32 && len(k) == 32
|
||||||
|
|
||||||
func hexOnly(s string) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for _, r := range s {
|
|
||||||
switch {
|
|
||||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
|
||||||
b.WriteRune(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Poller) logf(format string, args ...any) {
|
func (p *Poller) logf(format string, args ...any) {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package queue
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
@ -101,56 +100,24 @@ func parseTime(s string) time.Time {
|
||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
// Job priorities. ClaimNext orders by priority ascending, so a lower number
|
// EnqueueIfIdle inserts a job unless one is already queued/running for the stream.
|
||||||
// runs sooner.
|
|
||||||
const (
|
|
||||||
// PriorityInteractive is for a capture a viewer or a schedule is actively
|
|
||||||
// waiting on, pushed by streamd over the agent websocket.
|
|
||||||
PriorityInteractive = 10
|
|
||||||
// PriorityRoutine is a background refresh found by polling.
|
|
||||||
PriorityRoutine = 100
|
|
||||||
)
|
|
||||||
|
|
||||||
// EnqueueIfIdle inserts a routine job unless one is already queued/running
|
|
||||||
// for the stream.
|
|
||||||
func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) {
|
func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) {
|
||||||
return s.EnqueueIfIdlePriority(streamID, name, app, channel, reason, maxAttempts, PriorityRoutine)
|
var existing int
|
||||||
}
|
|
||||||
|
|
||||||
// EnqueueIfIdlePriority is EnqueueIfIdle with an explicit priority. A job that
|
|
||||||
// someone is waiting on is enqueued ahead of routine refreshes; if a routine
|
|
||||||
// job for the same stream is already queued, its priority is raised instead of
|
|
||||||
// adding a duplicate.
|
|
||||||
func (s *Store) EnqueueIfIdlePriority(streamID int64, name, app, channel, reason string, maxAttempts, priority int) (Job, bool, error) {
|
|
||||||
var existingID int64
|
|
||||||
var existingPriority int
|
|
||||||
err := s.DB.QueryRow(`
|
err := s.DB.QueryRow(`
|
||||||
SELECT id, priority FROM jobs
|
SELECT COUNT(1) FROM jobs WHERE stream_id=? AND status IN ('queued','running')`, streamID).Scan(&existing)
|
||||||
WHERE stream_id=? AND status IN ('queued','running')
|
if err != nil {
|
||||||
ORDER BY id LIMIT 1`, streamID).Scan(&existingID, &existingPriority)
|
|
||||||
switch {
|
|
||||||
case err == nil:
|
|
||||||
// Already pending. Promote it when this request is more urgent, and
|
|
||||||
// clear any backoff so it runs now rather than after the delay.
|
|
||||||
if priority < existingPriority {
|
|
||||||
_, _ = s.DB.Exec(
|
|
||||||
`UPDATE jobs SET priority=?, reason=?, not_before='' WHERE id=? AND status='queued'`,
|
|
||||||
priority, reason, existingID)
|
|
||||||
}
|
|
||||||
return Job{}, false, nil
|
|
||||||
case !errors.Is(err, sql.ErrNoRows):
|
|
||||||
return Job{}, false, err
|
return Job{}, false, err
|
||||||
}
|
}
|
||||||
|
if existing > 0 {
|
||||||
|
return Job{}, false, nil
|
||||||
|
}
|
||||||
if maxAttempts <= 0 {
|
if maxAttempts <= 0 {
|
||||||
maxAttempts = 5
|
maxAttempts = 5
|
||||||
}
|
}
|
||||||
if priority <= 0 {
|
|
||||||
priority = PriorityRoutine
|
|
||||||
}
|
|
||||||
res, err := s.DB.Exec(`
|
res, err := s.DB.Exec(`
|
||||||
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
|
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
|
||||||
VALUES(?,?,?,?,?,'queued',?,0,?,?,?)`,
|
VALUES(?,?,?,?,?,'queued',100,0,?,?,?)`,
|
||||||
streamID, name, app, channel, reason, priority, maxAttempts, now(), now())
|
streamID, name, app, channel, reason, maxAttempts, now(), now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Job{}, false, err
|
return Job{}, false, err
|
||||||
}
|
}
|
||||||
|
|
@ -232,18 +199,17 @@ func (s *Store) MarkOK(id int64) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarkFailed increments attempts. Re-queues unless maxed out.
|
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
|
||||||
// waitingDevice=true keeps status queued without burning an attempt.
|
// waitingDevice=true keeps status queued without burning an attempt.
|
||||||
// backoff is how long to wait before the job is runnable again (0 = immediate).
|
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
|
||||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
|
|
||||||
j, err := s.Get(id)
|
j, err := s.Get(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if waitingDevice {
|
if waitingDevice {
|
||||||
_, err = s.DB.Exec(`
|
_, err = s.DB.Exec(`
|
||||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
|
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
|
||||||
msg, now(), id)
|
msg, id)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
attempts := j.Attempts + 1
|
attempts := j.Attempts + 1
|
||||||
|
|
@ -253,8 +219,9 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
|
||||||
attempts, msg, now(), id)
|
attempts, msg, now(), id)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if backoff < 0 {
|
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||||
backoff = 0
|
if backoff > 15*time.Minute {
|
||||||
|
backoff = 15 * time.Minute
|
||||||
}
|
}
|
||||||
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
||||||
_, err = s.DB.Exec(`
|
_, err = s.DB.Exec(`
|
||||||
|
|
@ -263,29 +230,6 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
|
|
||||||
func ExponentialBackoff(attempts int) time.Duration {
|
|
||||||
if attempts < 1 {
|
|
||||||
attempts = 1
|
|
||||||
}
|
|
||||||
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
|
||||||
if d > 15*time.Minute {
|
|
||||||
d = 15 * time.Minute
|
|
||||||
}
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
|
|
||||||
// after fixing modules, or when job_backoff is disabled).
|
|
||||||
func (s *Store) ClearAllBackoffs() (int, error) {
|
|
||||||
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, _ := res.RowsAffected()
|
|
||||||
return int(n), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func min(a, b int) int {
|
func min(a, b int) int {
|
||||||
if a < b {
|
if a < b {
|
||||||
return a
|
return a
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,18 @@
|
||||||
package worker
|
package worker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/phonecap"
|
"drmdecryption/phonecap"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
"drmdecryption/apps/agent/internal/client"
|
||||||
"streamd/apps/agent/internal/device"
|
"drmdecryption/apps/agent/internal/device"
|
||||||
"streamd/apps/agent/internal/poller"
|
"drmdecryption/apps/agent/internal/queue"
|
||||||
"streamd/apps/agent/internal/queue"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Worker struct {
|
type Worker struct {
|
||||||
|
|
@ -27,10 +25,7 @@ type Worker struct {
|
||||||
Python string
|
Python string
|
||||||
WVD string
|
WVD string
|
||||||
UserAgent string
|
UserAgent string
|
||||||
// JobBackoff enables exponential delays between failed capture attempts.
|
Log *log.Logger
|
||||||
// When false (default), failed jobs are re-queued immediately.
|
|
||||||
JobBackoff bool
|
|
||||||
Log *log.Logger
|
|
||||||
|
|
||||||
lastDelayLog time.Time
|
lastDelayLog time.Time
|
||||||
}
|
}
|
||||||
|
|
@ -70,18 +65,11 @@ func (w *Worker) tick() {
|
||||||
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
||||||
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
||||||
w.logf("job=%d waiting: %v", job.ID, err)
|
w.logf("job=%d waiting: %v", job.ID, err)
|
||||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
|
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.logf("job=%d failed: %v", job.ID, err)
|
w.logf("job=%d failed: %v", job.ID, err)
|
||||||
w.event(job, client.EventCaptureFailed, err.Error(),
|
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
|
||||||
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
|
||||||
backoff := time.Duration(0)
|
|
||||||
if w.JobBackoff {
|
|
||||||
backoff = queue.ExponentialBackoff(job.Attempts + 1)
|
|
||||||
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
|
|
||||||
}
|
|
||||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_ = w.Queue.MarkOK(job.ID)
|
_ = w.Queue.MarkOK(job.ID)
|
||||||
|
|
@ -92,11 +80,6 @@ func isAuthErr(err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
// The client now returns a typed error with an actionable message; the
|
|
||||||
// substring check stays as a fallback for errors raised elsewhere.
|
|
||||||
if errors.Is(err, client.ErrUnauthorized) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
s := strings.ToLower(err.Error())
|
s := strings.ToLower(err.Error())
|
||||||
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
|
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
|
||||||
}
|
}
|
||||||
|
|
@ -115,10 +98,6 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName)
|
label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName)
|
||||||
// Tell streamd a capture is under way, so the stream's timeline in the
|
|
||||||
// dashboard shows it rather than just an unexplained "down".
|
|
||||||
w.event(job, client.EventCaptureStarted,
|
|
||||||
fmt.Sprintf("capture started on %s (%s)", w.AgentID, job.Reason), nil)
|
|
||||||
c, serial, err := w.Pool.Acquire(a.Package(), label)
|
c, serial, err := w.Pool.Acquire(a.Package(), label)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -127,8 +106,8 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
_ = w.Queue.SetDevice(job.ID, serial)
|
_ = w.Queue.SetDevice(job.ID, serial)
|
||||||
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
||||||
|
|
||||||
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
|
// Short TTL; /ws/agent heartbeats renew while this process is alive.
|
||||||
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
|
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
|
||||||
return fmt.Errorf("streamd claim: %w", err)
|
return fmt.Errorf("streamd claim: %w", err)
|
||||||
}
|
}
|
||||||
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
||||||
|
|
@ -148,19 +127,6 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
needsKeys := true
|
|
||||||
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
|
|
||||||
needsKeys = false
|
|
||||||
}
|
|
||||||
hasKey := poller.ValidKeyPair(res.Key)
|
|
||||||
if needsKeys && !hasKey {
|
|
||||||
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
|
|
||||||
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(res.MPD) == "" {
|
|
||||||
return fmt.Errorf("refusing to post credentials without mpd")
|
|
||||||
}
|
|
||||||
|
|
||||||
cred := client.Credentials{
|
cred := client.Credentials{
|
||||||
MPD: res.MPD,
|
MPD: res.MPD,
|
||||||
Key: res.Key,
|
Key: res.Key,
|
||||||
|
|
@ -171,41 +137,9 @@ func (w *Worker) runJob(job queue.Job) error {
|
||||||
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
||||||
return fmt.Errorf("post credentials: %w", err)
|
return fmt.Errorf("post credentials: %w", err)
|
||||||
}
|
}
|
||||||
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
|
|
||||||
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
|
|
||||||
// Report what was captured, never the key itself.
|
|
||||||
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
|
||||||
"device": serial,
|
|
||||||
"has_key": strings.TrimSpace(res.Key) != "",
|
|
||||||
"key_valid": hasKey,
|
|
||||||
})
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func trimURL(s string) string {
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
if len(s) <= 96 {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return s[:96] + "…"
|
|
||||||
}
|
|
||||||
|
|
||||||
// event posts a stream event to streamd. A timeline entry is never worth
|
|
||||||
// failing a capture over, so errors are logged and dropped.
|
|
||||||
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
|
||||||
if w.API == nil || job.StreamID == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if detail == nil {
|
|
||||||
detail = map[string]any{}
|
|
||||||
}
|
|
||||||
detail["agent_id"] = w.AgentID
|
|
||||||
detail["job_id"] = job.ID
|
|
||||||
if err := w.API.PostEvent(job.StreamID, kind, message, detail); err != nil {
|
|
||||||
w.logf("job=%d: could not report %s to streamd: %v", job.ID, kind, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *Worker) logf(format string, args ...any) {
|
func (w *Worker) logf(format string, args ...any) {
|
||||||
prefix := fmt.Sprintf("worker/%d: ", w.ID)
|
prefix := fmt.Sprintf("worker/%d: ", w.ID)
|
||||||
if w.Log != nil {
|
if w.Log != nil {
|
||||||
|
|
|
||||||
|
|
@ -10,42 +10,16 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
|
||||||
"streamd/apps/agent/internal/client"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Message is one push from streamd.
|
|
||||||
type Message struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
OK bool `json:"ok"`
|
|
||||||
Error string `json:"error"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
StreamID int64 `json:"stream_id"`
|
|
||||||
StreamName string `json:"stream_name"`
|
|
||||||
App string `json:"app"`
|
|
||||||
Channel string `json:"channel"`
|
|
||||||
Reason string `json:"reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client keeps a streamd /ws/agent connection alive and sends heartbeats
|
// Client keeps a streamd /ws/agent connection alive and sends heartbeats
|
||||||
// so claims auto-renew; on disconnect streamd releases this agent's claims.
|
// so claims auto-renew; on disconnect streamd releases this agent's claims.
|
||||||
// It also carries pushes from streamd: a capture a viewer or a schedule is
|
|
||||||
// waiting on, which would otherwise not be noticed until the next poll.
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
BaseURL string
|
BaseURL string
|
||||||
Token string
|
Token string
|
||||||
AgentID string
|
AgentID string
|
||||||
Log *log.Logger
|
Log *log.Logger
|
||||||
|
|
||||||
// OnCapture is called when streamd asks for credentials now.
|
|
||||||
OnCapture func(streamID int64, name, app, channel, reason string)
|
|
||||||
// OnStreamChanged is called when a stream was edited, so the agent can
|
|
||||||
// re-poll instead of waiting out its interval.
|
|
||||||
OnStreamChanged func(name, reason string)
|
|
||||||
// OnModulesChanged is called when the panel uploaded/edited/deleted a
|
|
||||||
// module, so the agent can pull without waiting for the sync interval.
|
|
||||||
OnModulesChanged func(name, reason string)
|
|
||||||
|
|
||||||
stop chan struct{}
|
stop chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -73,8 +47,7 @@ func (c *Client) Loop() {
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
err := c.session()
|
if err := c.session(); err != nil {
|
||||||
if err != nil {
|
|
||||||
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
|
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
|
|
@ -102,29 +75,18 @@ func (c *Client) session() error {
|
||||||
u.Path = "/ws/agent"
|
u.Path = "/ws/agent"
|
||||||
q := u.Query()
|
q := u.Query()
|
||||||
q.Set("agent_id", c.AgentID)
|
q.Set("agent_id", c.AgentID)
|
||||||
// The token is deliberately NOT put in the query string. It used to be,
|
if c.Token != "" {
|
||||||
// which wrote the shared secret into every reverse proxy access log.
|
q.Set("token", c.Token)
|
||||||
// streamd authenticates the handshake from the Authorization header below.
|
}
|
||||||
u.RawQuery = q.Encode()
|
u.RawQuery = q.Encode()
|
||||||
|
|
||||||
hdr := http.Header{}
|
hdr := http.Header{}
|
||||||
if c.Token != "" {
|
if c.Token != "" {
|
||||||
hdr.Set("Authorization", "Bearer "+c.Token)
|
hdr.Set("Authorization", "Bearer "+c.Token)
|
||||||
}
|
}
|
||||||
if c.AgentID != "" {
|
|
||||||
hdr.Set("X-Agent-ID", c.AgentID)
|
|
||||||
}
|
|
||||||
hdr.Set("User-Agent", "streamd-agent/"+client.Version)
|
|
||||||
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
|
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
|
||||||
conn, resp, err := dialer.Dial(u.String(), hdr)
|
conn, _, err := dialer.Dial(u.String(), hdr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if resp != nil {
|
|
||||||
switch resp.StatusCode {
|
|
||||||
case http.StatusUnauthorized, http.StatusForbidden:
|
|
||||||
return fmt.Errorf("dial: %w (streamd rejected this agent's API key for /ws/agent; "+
|
|
||||||
"it needs at least the operator role)", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("dial: %w", err)
|
return fmt.Errorf("dial: %w", err)
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
|
|
@ -145,11 +107,14 @@ func (c *Client) session() error {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||||
var msg Message
|
var msg map[string]any
|
||||||
if json.Unmarshal(data, &msg) != nil {
|
if json.Unmarshal(data, &msg) == nil {
|
||||||
continue
|
if t, _ := msg["type"].(string); t == "heartbeat_ack" {
|
||||||
|
if ok, _ := msg["ok"].(bool); !ok {
|
||||||
|
c.Log.Printf("ws: heartbeat nack: %v", msg["error"])
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c.handle(msg)
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
|
@ -174,33 +139,6 @@ func (c *Client) session() error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) handle(msg Message) {
|
|
||||||
switch strings.ToLower(msg.Type) {
|
|
||||||
case "heartbeat_ack":
|
|
||||||
if !msg.OK {
|
|
||||||
c.Log.Printf("ws: heartbeat nack: %s", msg.Error)
|
|
||||||
}
|
|
||||||
case "capture_requested":
|
|
||||||
if msg.StreamID == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Log.Printf("ws: streamd requested a capture for stream=%s reason=%s",
|
|
||||||
msg.StreamName, msg.Reason)
|
|
||||||
if c.OnCapture != nil {
|
|
||||||
c.OnCapture(msg.StreamID, msg.StreamName, msg.App, msg.Channel, msg.Reason)
|
|
||||||
}
|
|
||||||
case "stream_changed":
|
|
||||||
if c.OnStreamChanged != nil {
|
|
||||||
c.OnStreamChanged(msg.StreamName, msg.Reason)
|
|
||||||
}
|
|
||||||
case "modules_changed":
|
|
||||||
c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
|
|
||||||
if c.OnModulesChanged != nil {
|
|
||||||
c.OnModulesChanged(msg.StreamName, msg.Reason)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) writeHeartbeat(conn *websocket.Conn) error {
|
func (c *Client) writeHeartbeat(conn *websocket.Conn) error {
|
||||||
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||||
return conn.WriteJSON(map[string]string{
|
return conn.WriteJSON(map[string]string{
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# capture
|
# capture
|
||||||
|
|
||||||
One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
|
One-shot phone MITM capture, hosted by the single binary as `drm capture`.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
apps/capture/
|
apps/capture/
|
||||||
|
|
@ -8,17 +8,17 @@ apps/capture/
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./bin/streamd capture # passive: play anything
|
./bin/drm capture # passive: play anything
|
||||||
./bin/streamd capture --app rte # launch, navigate by hand
|
./bin/drm capture --app rte # launch, navigate by hand
|
||||||
./bin/streamd capture --app rte --channel rteone --auto-play \
|
./bin/drm capture --app rte --channel rteone --auto-play \
|
||||||
--wvd data/device.wvd # fully automated
|
--wvd data/device.wvd # fully automated
|
||||||
```
|
```
|
||||||
|
|
||||||
Writes `outputs/<app>/<stamp>/` plus `latest/`. App modules are compiled in, so
|
Writes `outputs/<app>/<stamp>/` plus `latest/`. App modules are compiled in, so
|
||||||
there is no modules directory to point at; `streamd modules` lists what is available.
|
there is no modules directory to point at; `drm modules` lists what is available.
|
||||||
|
|
||||||
**Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
|
**Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
|
||||||
discovering a new app, and troubleshooting.
|
discovering a new app, and troubleshooting.
|
||||||
|
|
||||||
The catalog lookup that used to be a separate `tg4info` binary is now the
|
The catalog lookup that used to be a separate `tg4info` binary is now the
|
||||||
provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
|
provider-agnostic `drm catalog` (`apps/cli/catalogcmd`).
|
||||||
|
|
|
||||||
|
|
@ -3,25 +3,22 @@
|
||||||
package capturecmd
|
package capturecmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/app"
|
"drmdecryption/app"
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/phonecap"
|
"drmdecryption/phonecap"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run performs one capture. Providers live under modules/<name>/ and are built
|
// Run performs one capture. Providers live under modules/<name>/ and are built
|
||||||
// and executed by modhost — they are not linked into streamd.
|
// and executed by modhost — they are not linked into drm.exe.
|
||||||
func Run(args []string) error {
|
func Run(args []string) error {
|
||||||
args = normalizeArgs(args)
|
args = normalizeArgs(args)
|
||||||
|
|
||||||
|
|
@ -35,17 +32,16 @@ func Run(args []string) error {
|
||||||
fs := flag.NewFlagSet("capture", flag.ContinueOnError)
|
fs := flag.NewFlagSet("capture", flag.ContinueOnError)
|
||||||
appName := fs.String("app", "", "app module under modules/<name>/. Empty = passive MITM, no launch/auto-play")
|
appName := fs.String("app", "", "app module under modules/<name>/. Empty = passive MITM, no launch/auto-play")
|
||||||
channel := fs.String("channel", "", "channel id for --auto-play")
|
channel := fs.String("channel", "", "channel id for --auto-play")
|
||||||
allChannels := fs.Bool("all", false, "capture every channel declared by the module (grab-all)")
|
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel is set)")
|
||||||
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel / --all is set)")
|
waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture")
|
||||||
waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture (per channel with --all)")
|
|
||||||
python := fs.String("python", "", "python for wvkey.py (default: .venv)")
|
python := fs.String("python", "", "python for wvkey.py (default: .venv)")
|
||||||
wvd := fs.String("wvd", "", "path to .wvd device file (required by some apps e.g. c4; MPD-only if omitted)")
|
wvd := fs.String("wvd", "", "path to .wvd device file (required for key fetch)")
|
||||||
userAgent := fs.String("user-agent", "", "optional User-Agent for license requests")
|
userAgent := fs.String("user-agent", "", "optional User-Agent for license requests")
|
||||||
serial := fs.String("serial", "", "adb device serial (default: sole/USB selected device)")
|
serial := fs.String("serial", "", "adb device serial (default: sole/USB selected device)")
|
||||||
closeApp := fs.Bool("close", true, "force-stop --app when capture finishes (ignored in passive mode)")
|
closeApp := fs.Bool("close", true, "force-stop --app when capture finishes (ignored in passive mode)")
|
||||||
keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | wrap | none")
|
keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | none")
|
||||||
fs.Usage = func() {
|
fs.Usage = func() {
|
||||||
fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID | --all] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExamples:\n capture --app bbc --channel bbcone --wait 120\n capture --app c4 --channel film4 --wvd data/device.wvd\n capture --app c4 --all --wvd data/device.wvd --wait 90\n\nFlags:\n", appChoices)
|
fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExample (BBC + NordVPN UK):\n capture --app bbc --channel bbcone --wait 120\n\nFlags:\n", appChoices)
|
||||||
fs.PrintDefaults()
|
fs.PrintDefaults()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -64,9 +60,6 @@ func Run(args []string) error {
|
||||||
// No --app: passive MITM — the operator plays whatever they want and we dump
|
// No --app: passive MITM — the operator plays whatever they want and we dump
|
||||||
// whatever DRM traffic appears.
|
// whatever DRM traffic appears.
|
||||||
if strings.TrimSpace(*appName) == "" {
|
if strings.TrimSpace(*appName) == "" {
|
||||||
if *allChannels {
|
|
||||||
return fmt.Errorf("--all requires --app")
|
|
||||||
}
|
|
||||||
_, err := phonecap.RunPassive(phonecap.Options{
|
_, err := phonecap.RunPassive(phonecap.Options{
|
||||||
Client: c,
|
Client: c,
|
||||||
Python: *python,
|
Python: *python,
|
||||||
|
|
@ -83,26 +76,7 @@ func Run(args []string) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return modhost.FormatUnknown(root, *appName)
|
return modhost.FormatUnknown(root, *appName)
|
||||||
}
|
}
|
||||||
if needsWVD(a) && strings.TrimSpace(*wvd) == "" {
|
|
||||||
return fmt.Errorf("%s requires --wvd PATH (Widevine device file) — encrypted capture cannot be MPD-only", a.Name())
|
|
||||||
}
|
|
||||||
channelID := strings.TrimSpace(*channel)
|
channelID := strings.TrimSpace(*channel)
|
||||||
if *allChannels && channelID != "" {
|
|
||||||
return fmt.Errorf("use either --channel or --all, not both")
|
|
||||||
}
|
|
||||||
if *allChannels {
|
|
||||||
return runAll(root, a, c, phonecap.Options{
|
|
||||||
App: a,
|
|
||||||
Client: c,
|
|
||||||
Python: *python,
|
|
||||||
WVD: *wvd,
|
|
||||||
UserAgent: *userAgent,
|
|
||||||
Wait: time.Duration(*waitSec) * time.Second,
|
|
||||||
CloseApp: *closeApp,
|
|
||||||
KeyMode: *keyMode,
|
|
||||||
ClearProxy: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// --channel implies interactive auto-play (Explore → channel → Watch live).
|
// --channel implies interactive auto-play (Explore → channel → Watch live).
|
||||||
doAutoPlay := *autoPlay || channelID != ""
|
doAutoPlay := *autoPlay || channelID != ""
|
||||||
if *autoPlay && channelID == "" {
|
if *autoPlay && channelID == "" {
|
||||||
|
|
@ -128,106 +102,6 @@ func Run(args []string) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
type channelResult struct {
|
|
||||||
Channel string `json:"channel"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
OK bool `json:"ok"`
|
|
||||||
MPD string `json:"mpd,omitempty"`
|
|
||||||
LicenseURL string `json:"license_url,omitempty"`
|
|
||||||
Key string `json:"key,omitempty"`
|
|
||||||
Path string `json:"path,omitempty"`
|
|
||||||
Error string `json:"error,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func runAll(root string, a app.App, c *adb.Client, base phonecap.Options) error {
|
|
||||||
chs := a.Channels()
|
|
||||||
if len(chs) == 0 {
|
|
||||||
return fmt.Errorf("no channels configured for %s (%s)", a.Name(), knownChannels(a))
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] Grab-all %s — %d channel(s)\n", a.Name(), len(chs))
|
|
||||||
results := make([]channelResult, 0, len(chs))
|
|
||||||
okN := 0
|
|
||||||
for i, ch := range chs {
|
|
||||||
fmt.Printf("\n======== [%d/%d] %s (%s) ========\n", i+1, len(chs), ch.Label, ch.ID)
|
|
||||||
opt := base
|
|
||||||
opt.Channel = ch.ID
|
|
||||||
opt.NoAutoPlay = false
|
|
||||||
opt.App = a
|
|
||||||
opt.Client = c
|
|
||||||
res, err := phonecap.Run(opt)
|
|
||||||
row := channelResult{
|
|
||||||
Channel: ch.ID,
|
|
||||||
Label: ch.Label,
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
row.Error = err.Error()
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] %s: %v\n", ch.ID, err)
|
|
||||||
} else {
|
|
||||||
row.OK = res.MPD != ""
|
|
||||||
row.MPD = res.MPD
|
|
||||||
row.LicenseURL = res.Session.LicenseURL
|
|
||||||
row.Key = res.Key
|
|
||||||
row.Path = res.Path
|
|
||||||
if row.OK {
|
|
||||||
okN++
|
|
||||||
} else {
|
|
||||||
row.Error = "no mpd"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
results = append(results, row)
|
|
||||||
if i+1 < len(chs) {
|
|
||||||
// Let iptables / appproxy fully release before the next transparent start.
|
|
||||||
time.Sleep(4 * time.Second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stamp := time.Now().Format("20060102-150405")
|
|
||||||
batchDir := filepath.Join(root, "outputs", a.Name(), "all-"+stamp)
|
|
||||||
_ = os.MkdirAll(batchDir, 0o755)
|
|
||||||
summaryPath := filepath.Join(batchDir, "SUMMARY.json")
|
|
||||||
if b, err := json.MarshalIndent(results, "", " "); err == nil {
|
|
||||||
_ = os.WriteFile(summaryPath, b, 0o644)
|
|
||||||
}
|
|
||||||
printAllSummary(a.Name(), results, okN, summaryPath)
|
|
||||||
if okN == 0 {
|
|
||||||
return fmt.Errorf("grab-all %s: 0/%d channels captured", a.Name(), len(chs))
|
|
||||||
}
|
|
||||||
if okN < len(chs) {
|
|
||||||
return fmt.Errorf("grab-all %s: %d/%d channels captured (see %s)", a.Name(), okN, len(chs), summaryPath)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func printAllSummary(appName string, results []channelResult, okN int, summaryPath string) {
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("========== GRAB-ALL SUMMARY ==========")
|
|
||||||
fmt.Printf("app: %s ok: %d/%d\n", appName, okN, len(results))
|
|
||||||
fmt.Println("--------------------------------------")
|
|
||||||
fmt.Printf("%-12s %-14s %-6s %s\n", "ID", "LABEL", "OK", "MPD / ERROR")
|
|
||||||
for _, r := range results {
|
|
||||||
status := "no"
|
|
||||||
if r.OK {
|
|
||||||
status = "yes"
|
|
||||||
}
|
|
||||||
detail := r.Error
|
|
||||||
if r.OK {
|
|
||||||
detail = trimURL(r.MPD, 72)
|
|
||||||
}
|
|
||||||
fmt.Printf("%-12s %-14s %-6s %s\n", r.Channel, r.Label, status, detail)
|
|
||||||
}
|
|
||||||
fmt.Println("--------------------------------------")
|
|
||||||
fmt.Println("summary:", summaryPath)
|
|
||||||
fmt.Println("======================================")
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimURL(s string, n int) string {
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
if len(s) <= n {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return s[:n] + "…"
|
|
||||||
}
|
|
||||||
|
|
||||||
// normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −)
|
// normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −)
|
||||||
// into ASCII - so `--app` is not silently dropped as a positional token.
|
// into ASCII - so `--app` is not silently dropped as a positional token.
|
||||||
func normalizeArgs(args []string) []string {
|
func normalizeArgs(args []string) []string {
|
||||||
|
|
@ -256,13 +130,6 @@ func normalizeArgs(args []string) []string {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func needsWVD(a app.App) bool {
|
|
||||||
if rw, ok := a.(app.RequireWVD); ok {
|
|
||||||
return rw.RequireWVD()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// knownChannels describes what the operator can pick, or where to declare it when
|
// knownChannels describes what the operator can pick, or where to declare it when
|
||||||
// the module has no local values file yet.
|
// the module has no local values file yet.
|
||||||
func knownChannels(a app.App) string {
|
func knownChannels(a app.App) string {
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
module streamd/apps/capture
|
module drmdecryption/apps/capture
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require streamd v0.0.0
|
require drmdecryption v0.0.0
|
||||||
|
|
||||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
require (
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
|
||||||
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
replace streamd => ../pkg
|
replace drmdecryption => ../pkg
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,11 @@
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
|
||||||
|
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
|
||||||
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"streamd/apps/capture/capturecmd"
|
"drmdecryption/apps/capture/capturecmd"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCaptureRejectsChannelAsApp(t *testing.T) {
|
func TestCaptureRejectsChannelAsApp(t *testing.T) {
|
||||||
|
|
|
||||||
|
|
@ -11,9 +11,9 @@ import (
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run performs a catalog lookup for one channel.
|
// Run performs a catalog lookup for one channel.
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
module streamd/apps/cli
|
module drmdecryption/apps/cli
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
streamd v0.0.0
|
drmdecryption v0.0.0
|
||||||
streamd/apps/agent v0.0.0
|
drmdecryption/apps/agent v0.0.0
|
||||||
streamd/apps/capture v0.0.0
|
drmdecryption/apps/capture v0.0.0
|
||||||
streamd/apps/proxy v0.0.0
|
drmdecryption/apps/proxy v0.0.0
|
||||||
streamd/apps/streamd v0.0.0
|
drmdecryption/apps/streamd v0.0.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|
@ -26,9 +26,9 @@ require (
|
||||||
)
|
)
|
||||||
|
|
||||||
replace (
|
replace (
|
||||||
streamd => ../pkg
|
drmdecryption => ../pkg
|
||||||
streamd/apps/agent => ../agent
|
drmdecryption/apps/agent => ../agent
|
||||||
streamd/apps/capture => ../capture
|
drmdecryption/apps/capture => ../capture
|
||||||
streamd/apps/proxy => ../proxy
|
drmdecryption/apps/proxy => ../proxy
|
||||||
streamd/apps/streamd => ../streamd
|
drmdecryption/apps/streamd => ../streamd
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,22 @@
|
||||||
// Command streamd is the single entry point for the toolchain: phone capture,
|
// Command drm is the single entry point for the toolchain: phone capture,
|
||||||
// catalog lookups, the always-on agent, the streamd control plane and the
|
// catalog lookups, the always-on agent, the streamd control plane and the
|
||||||
// on-device MITM. Providers live under modules/<name>/ and are discovered,
|
// on-device MITM. Providers live under modules/<name>/ and are discovered,
|
||||||
// built, and executed by the host — they are not linked into this binary.
|
// built, and executed by the host — they are not linked into this binary.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
// The scheduler resolves IANA zone names so a weekly event stays at its
|
|
||||||
// local wall-clock time. Windows ships no zone database, so embed one.
|
|
||||||
_ "time/tzdata"
|
|
||||||
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/apps/agent/agentcmd"
|
"drmdecryption/apps/agent/agentcmd"
|
||||||
"streamd/apps/capture/capturecmd"
|
"drmdecryption/apps/capture/capturecmd"
|
||||||
"streamd/apps/cli/catalogcmd"
|
"drmdecryption/apps/cli/catalogcmd"
|
||||||
"streamd/apps/cli/modulescmd"
|
"drmdecryption/apps/cli/modulescmd"
|
||||||
"streamd/apps/proxy/proxyctlcmd"
|
"drmdecryption/apps/proxy/proxyctlcmd"
|
||||||
"streamd/apps/streamd/servecmd"
|
"drmdecryption/apps/streamd/servecmd"
|
||||||
"streamd/bootstrap"
|
"drmdecryption/bootstrap"
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
@ -39,12 +35,12 @@ func main() {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
|
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
|
fmt.Fprintln(os.Stderr, "[!] DRM_MODULES_DIR:", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
|
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
|
||||||
// missing so a lone downloaded streamd.exe becomes a usable install tree.
|
// missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
|
||||||
if cmd != "help" && cmd != "-h" && cmd != "--help" {
|
if cmd != "help" && cmd != "-h" && cmd != "--help" {
|
||||||
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
|
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
|
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
|
||||||
|
|
@ -102,19 +98,18 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func usage() {
|
func usage() {
|
||||||
fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
|
fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
streamd [--modules-dir DIR] modules
|
drm [--modules-dir DIR] modules
|
||||||
streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
|
drm [--modules-dir DIR] capture --app NAME [--channel ID] [--wvd PATH]
|
||||||
streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
|
drm [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
|
||||||
streamd agent run|status|devices|enqueue|cancel [--config …]
|
drm agent run|status|devices|enqueue|cancel [--config …]
|
||||||
streamd serve start|stop|restart|status|update|run [flags]
|
drm serve [--bind …] [--data …] [--token …]
|
||||||
streamd serve [--bind …] [--data …] # foreground (same as run)
|
drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
|
||||||
streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
|
|
||||||
|
|
||||||
Global flags:
|
Global flags:
|
||||||
--modules-dir DIR provider folder (default: <install>/modules, or $STREAMD_MODULES_DIR)
|
--modules-dir DIR provider folder (default: <install>/modules, or $DRM_MODULES_DIR)
|
||||||
|
|
||||||
Providers live under modules/<name>/ (Go source + module-publish.yaml).
|
Providers live under modules/<name>/ (Go source + module-publish.yaml).
|
||||||
Local module.yaml holds secrets and is never published; release zips ship
|
Local module.yaml holds secrets and is never published; release zips ship
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,8 @@ import (
|
||||||
"sort"
|
"sort"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run prints external modules under modules/.
|
// Run prints external modules under modules/.
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ One Go package per streaming app. Every module is **compiled into the binary**
|
||||||
there is no plugin loading and no modules directory to point a binary at.
|
there is no plugin loading and no modules directory to point a binary at.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
apps/modules/ Go module: streamd/modules
|
apps/modules/ Go module: drmdecryption/modules
|
||||||
go.mod replace streamd => ../pkg
|
go.mod replace drmdecryption => ../pkg
|
||||||
all/all.go blank-imports every module — the link point
|
all/all.go blank-imports every module — the link point
|
||||||
provider/ shared base: values loading, channel aliases, durations
|
provider/ shared base: values loading, channel aliases, durations
|
||||||
<name>/*.go TRACKED: the app's logic
|
<name>/*.go TRACKED: the app's logic
|
||||||
|
|
@ -37,7 +37,7 @@ Values arrive by **flag → environment → module.yaml → Go default**, and on
|
||||||
mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
|
mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./bin/streamd catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
|
./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
|
||||||
export TG4_POLICY_KEY=BCpkAD... # same thing
|
export TG4_POLICY_KEY=BCpkAD... # same thing
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -46,9 +46,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
|
||||||
1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
|
1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
|
||||||
2. Register from `init()`: `appreg.Register(Name, New)` and
|
2. Register from `init()`: `appreg.Register(Name, New)` and
|
||||||
`appreg.RegisterFlags(bindFlags)`
|
`appreg.RegisterFlags(bindFlags)`
|
||||||
3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
|
3. Add one line to `all/all.go`: `_ "drmdecryption/modules/myapp"`
|
||||||
4. Create `apps/modules/myapp/module.yaml` with your values
|
4. Create `apps/modules/myapp/module.yaml` with your values
|
||||||
5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd modules`
|
5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
|
||||||
|
|
||||||
**Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
|
**Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
|
||||||
`uiflow` reference, optional capability interfaces, and a checklist.
|
`uiflow` reference, optional capability interfaces, and a checklist.
|
||||||
|
|
@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./bin/streamd modules # what is compiled in
|
./bin/drm modules # what is compiled in
|
||||||
./bin/streamd capture --app rte --channel rteone --auto-play
|
./bin/drm capture --app rte --channel rteone --auto-play
|
||||||
./bin/streamd capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
|
./bin/drm capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
|
||||||
./bin/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
|
./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
|
||||||
./bin/streamd agent run --config apps/agent/agent.yaml
|
./bin/drm agent run --config apps/agent/agent.yaml
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
package all
|
package all
|
||||||
|
|
||||||
import (
|
import (
|
||||||
_ "streamd/modules/bbc"
|
_ "drmdecryption/modules/bbc"
|
||||||
_ "streamd/modules/rte"
|
_ "drmdecryption/modules/rte"
|
||||||
_ "streamd/modules/tg4"
|
_ "drmdecryption/modules/tg4"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import (
|
||||||
"flag"
|
"flag"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Every module must be constructible with no module.yaml present — a fresh clone
|
// Every module must be constructible with no module.yaml present — a fresh clone
|
||||||
|
|
@ -23,9 +23,9 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
|
||||||
t.Errorf("%s: Name() = %q", n, a.Name())
|
t.Errorf("%s: Name() = %q", n, a.Name())
|
||||||
}
|
}
|
||||||
switch a.KeyMode() {
|
switch a.KeyMode() {
|
||||||
case "raw", "modulardrm", "wrap", "none":
|
case "raw", "modulardrm", "none":
|
||||||
default:
|
default:
|
||||||
t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, wrap, or none", n, a.KeyMode())
|
t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, or none", n, a.KeyMode())
|
||||||
}
|
}
|
||||||
if a.CAHash() == "" {
|
if a.CAHash() == "" {
|
||||||
t.Errorf("%s: CAHash() empty", n)
|
t.Errorf("%s: CAHash() empty", n)
|
||||||
|
|
@ -39,12 +39,6 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
|
||||||
if a.CaptureHints().RemoteLog == "" {
|
if a.CaptureHints().RemoteLog == "" {
|
||||||
t.Errorf("%s: CaptureHints has no remote log", n)
|
t.Errorf("%s: CaptureHints has no remote log", n)
|
||||||
}
|
}
|
||||||
if n == "c4" {
|
|
||||||
rw, ok := a.(appreg.RequireWVD)
|
|
||||||
if !ok || !rw.RequireWVD() {
|
|
||||||
t.Errorf("c4 must RequireWVD() so capture refuses MPD-only runs")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,12 +9,12 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,11 @@ package bbc
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ import (
|
||||||
"regexp"
|
"regexp"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Name is the module id (--app bbc).
|
// Name is the module id (--app bbc).
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
|
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
|
||||||
|
|
|
||||||
|
|
@ -1,148 +0,0 @@
|
||||||
// Package c4 is the Channel 4 (All 4) Live TV provider module.
|
|
||||||
// Live list rows use content-desc "Select to watch Channel Four" / "E Four" / etc.
|
|
||||||
package c4
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/adb"
|
|
||||||
appreg "streamd/app"
|
|
||||||
"streamd/capture"
|
|
||||||
"streamd/modules/provider"
|
|
||||||
"streamd/mpd"
|
|
||||||
"streamd/uiflow"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
appreg.Register(Name, New)
|
|
||||||
appreg.RegisterFlags(bindFlags)
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindFlags(fs *flag.FlagSet) {
|
|
||||||
fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
|
|
||||||
fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
|
|
||||||
fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
|
|
||||||
}
|
|
||||||
|
|
||||||
// App is the Channel 4 plugin.
|
|
||||||
type App struct {
|
|
||||||
*provider.Base
|
|
||||||
cfg Config
|
|
||||||
}
|
|
||||||
|
|
||||||
// New constructs the plugin from module.yaml + flags + env.
|
|
||||||
func New() (appreg.App, error) {
|
|
||||||
cfg, res, err := loadConfig()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
labels := make(map[string]string, len(cfg.Channels))
|
|
||||||
for id, ch := range cfg.Channels {
|
|
||||||
labels[id] = ch.Label
|
|
||||||
}
|
|
||||||
return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeyMode: Channel 4 / RedBee needs the phone's JSON license POST (token +
|
|
||||||
// challenge). Capture stores that body; wvkey --mode wrap re-issues it.
|
|
||||||
func (a *App) KeyMode() string { return "wrap" }
|
|
||||||
|
|
||||||
// RequireWVD: C4 live is always encrypted — refuse MPD-only captures.
|
|
||||||
func (a *App) RequireWVD() bool { return true }
|
|
||||||
|
|
||||||
// CaptureHints: need the DASH MPD and the phone's RedBee license POST body
|
|
||||||
// (token + challenge). MPD alone is not enough for keys.
|
|
||||||
func (a *App) CaptureHints() capture.Hints {
|
|
||||||
return a.Hints("mpd", "license_body")
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureHintsFor prefers the simulcast path for this live channel so a
|
|
||||||
// neighbouring Auto-play / prefetch MPD does not win the Wait score race.
|
|
||||||
func (a *App) CaptureHintsFor(channel string) capture.Hints {
|
|
||||||
h := a.CaptureHints()
|
|
||||||
id, err := a.Resolve(channel)
|
|
||||||
if err != nil {
|
|
||||||
id = strings.ToLower(strings.TrimSpace(channel))
|
|
||||||
}
|
|
||||||
prefer := map[string]string{
|
|
||||||
"channel4": "channel(c4)",
|
|
||||||
"e4": "channel(e4)",
|
|
||||||
"more4": "channel(m4)",
|
|
||||||
"film4": "channel(f4)",
|
|
||||||
"fourseven": "channel(4s)",
|
|
||||||
}
|
|
||||||
if p, ok := prefer[id]; ok {
|
|
||||||
h.PreferURLContains = []string{p}
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
|
|
||||||
func (a *App) UseTransparentMITM() bool { return true }
|
|
||||||
|
|
||||||
func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
|
|
||||||
|
|
||||||
func (a *App) Channels() []appreg.Channel {
|
|
||||||
out := make([]appreg.Channel, 0, len(a.cfg.Channels))
|
|
||||||
for _, id := range a.ChannelIDs() {
|
|
||||||
out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Launch cold-starts Channel 4.
|
|
||||||
func (a *App) Launch(c *adb.Client) error {
|
|
||||||
c.EnsureAwake()
|
|
||||||
fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
|
|
||||||
c.DismissShadeIfFocused()
|
|
||||||
if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
|
|
||||||
DescContains: a.cfg.UI.LaunchDescContains,
|
|
||||||
TextContains: a.cfg.UI.LaunchDescContains,
|
|
||||||
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AutoPlay opens Live TV, scrolls to the channel card, and taps Select to watch.
|
|
||||||
func (a *App) AutoPlay(c *adb.Client, channel string) error {
|
|
||||||
id, err := a.Resolve(channel)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ch := a.cfg.Channels[id]
|
|
||||||
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
|
|
||||||
c.DismissShadeIfFocused()
|
|
||||||
|
|
||||||
if err := a.openLiveTab(c); err != nil {
|
|
||||||
return fmt.Errorf("Live TV tab: %w", err)
|
|
||||||
}
|
|
||||||
if err := a.tapChannelCard(c, ch); err != nil {
|
|
||||||
return fmt.Errorf("channel play %s: %w", a.Label(id), err)
|
|
||||||
}
|
|
||||||
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
|
|
||||||
Timeout: time.Duration(a.cfg.Timeouts.Playback),
|
|
||||||
SoftFail: true,
|
|
||||||
OrDescContains: []string{
|
|
||||||
"Pause",
|
|
||||||
"Unmute",
|
|
||||||
"Cast",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) VideoSelect() string { return "for=best" }
|
|
||||||
func (a *App) AudioSelect() string { return "for=best" }
|
|
||||||
func (a *App) RewriterName() string { return "none" }
|
|
||||||
func (a *App) LiveWaitSeconds() int { return 2 }
|
|
||||||
func (a *App) TSReadyBytes() int64 { return 256 << 10 }
|
|
||||||
|
|
@ -1,116 +0,0 @@
|
||||||
package c4
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/modcfg"
|
|
||||||
"streamd/modules/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Name is the module id (--app c4).
|
|
||||||
const Name = "c4"
|
|
||||||
|
|
||||||
// Channel is one Channel 4 Live TV target.
|
|
||||||
type Channel struct {
|
|
||||||
Label string `yaml:"label"`
|
|
||||||
ChipDesc []string `yaml:"chip_desc"`
|
|
||||||
PlayDesc []string `yaml:"play_desc"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config is modules/c4/module.yaml (preferred) or apps/modules/c4/module.yaml.
|
|
||||||
type Config struct {
|
|
||||||
provider.Common `yaml:",inline"`
|
|
||||||
|
|
||||||
Channels map[string]Channel `yaml:"channels"`
|
|
||||||
Timeouts Timeouts `yaml:"timeouts"`
|
|
||||||
UI UI `yaml:"ui"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Timeouts struct {
|
|
||||||
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
|
|
||||||
LaunchSettle provider.Duration `yaml:"launch_settle"`
|
|
||||||
LiveNav provider.Duration `yaml:"live_nav"`
|
|
||||||
ChannelFind provider.Duration `yaml:"channel_find"`
|
|
||||||
AfterChannel provider.Duration `yaml:"after_channel"`
|
|
||||||
WatchLive provider.Duration `yaml:"watch_live"`
|
|
||||||
Playback provider.Duration `yaml:"playback"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UI struct {
|
|
||||||
LaunchDescContains []string `yaml:"launch_desc_contains"`
|
|
||||||
LiveTab []string `yaml:"live_tab"`
|
|
||||||
LiveTabDescRE []string `yaml:"live_tab_desc_re"`
|
|
||||||
LiveTabTextRE []string `yaml:"live_tab_text_re"`
|
|
||||||
WatchLive []string `yaml:"watch_live"`
|
|
||||||
PlaybackDescContains []string `yaml:"playback_desc_contains"`
|
|
||||||
ChannelScrollMax int `yaml:"channel_scroll_max"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c Config) withDefaults() Config {
|
|
||||||
t := &c.Timeouts
|
|
||||||
t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
|
|
||||||
t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
|
|
||||||
t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
|
|
||||||
t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
|
|
||||||
t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
|
|
||||||
t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
|
|
||||||
t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
|
|
||||||
|
|
||||||
u := &c.UI
|
|
||||||
if len(u.LaunchDescContains) == 0 {
|
|
||||||
u.LaunchDescContains = []string{"Home", "Live TV", "My Shows", "Downloads", "Search"}
|
|
||||||
}
|
|
||||||
if len(u.LiveTab) == 0 {
|
|
||||||
u.LiveTab = []string{"Live TV"}
|
|
||||||
}
|
|
||||||
if len(u.LiveTabDescRE) == 0 {
|
|
||||||
u.LiveTabDescRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if len(u.LiveTabTextRE) == 0 {
|
|
||||||
u.LiveTabTextRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if len(u.WatchLive) == 0 {
|
|
||||||
u.WatchLive = []string{"Select to watch", "Play Episode", "Restart"}
|
|
||||||
}
|
|
||||||
if len(u.PlaybackDescContains) == 0 {
|
|
||||||
u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
|
|
||||||
}
|
|
||||||
if u.ChannelScrollMax <= 0 {
|
|
||||||
u.ChannelScrollMax = 10
|
|
||||||
}
|
|
||||||
if c.Package == "" {
|
|
||||||
c.Package = "com.channel4.ondemand"
|
|
||||||
}
|
|
||||||
if c.Channels == nil {
|
|
||||||
c.Channels = map[string]Channel{}
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadConfig() (Config, modcfg.Result, error) {
|
|
||||||
var cfg Config
|
|
||||||
res, err := modcfg.Load(Name, &cfg)
|
|
||||||
if err != nil {
|
|
||||||
return cfg, res, err
|
|
||||||
}
|
|
||||||
cfg = cfg.withDefaults()
|
|
||||||
if v := modcfg.Env(Name, "package"); v != "" {
|
|
||||||
cfg.Package = v
|
|
||||||
}
|
|
||||||
if flags.packageName != "" {
|
|
||||||
cfg.Package = flags.packageName
|
|
||||||
}
|
|
||||||
if flags.caHash != "" {
|
|
||||||
cfg.CAHash = flags.caHash
|
|
||||||
}
|
|
||||||
if flags.proxyBin != "" {
|
|
||||||
cfg.ProxyBin = flags.proxyBin
|
|
||||||
}
|
|
||||||
return cfg, res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var flags struct {
|
|
||||||
packageName string
|
|
||||||
caHash string
|
|
||||||
proxyBin string
|
|
||||||
}
|
|
||||||
|
|
@ -1,84 +0,0 @@
|
||||||
# Channel 4 (All 4) — published universal values (renamed to module.yaml in release zips).
|
|
||||||
# Live cards: content-desc "Select to watch Channel Four" / "E Four" / "More Four" / …
|
|
||||||
|
|
||||||
package: com.channel4.ondemand
|
|
||||||
proxy_bin: bin/proxy-android-arm64
|
|
||||||
|
|
||||||
# SENSITIVE — set in local module.yaml:
|
|
||||||
# license_url: "https://c4.eme.lp.aws.redbeemedia.com/wvlicenceproxy-service/widevine/acquire"
|
|
||||||
|
|
||||||
# Transparent mode only MITMs open.live by default. Force C4 playlist / license hosts.
|
|
||||||
mitm_hosts:
|
|
||||||
- c4assets.com
|
|
||||||
- olsp.live.dash.c4assets.com
|
|
||||||
- stream.c4assets.com
|
|
||||||
- channel4.com
|
|
||||||
- api.channel4.com
|
|
||||||
- c4.eme.lp.aws.redbeemedia.com
|
|
||||||
- redbeemedia.com
|
|
||||||
- all4nav.channel4.com
|
|
||||||
|
|
||||||
score:
|
|
||||||
hosts:
|
|
||||||
- c4assets.com
|
|
||||||
- olsp.live.dash.c4assets.com
|
|
||||||
- stream.c4assets.com
|
|
||||||
- channel4.com
|
|
||||||
- api.channel4.com
|
|
||||||
- redbeemedia.com
|
|
||||||
- akamaized.net
|
|
||||||
deny:
|
|
||||||
- google-analytics
|
|
||||||
- googletagmanager
|
|
||||||
- doubleclick
|
|
||||||
- scorecardresearch
|
|
||||||
- facebook.com
|
|
||||||
- crashlytics
|
|
||||||
- appsflyer
|
|
||||||
- optimizely
|
|
||||||
|
|
||||||
aliases:
|
|
||||||
c4: channel4
|
|
||||||
four: channel4
|
|
||||||
ch4: channel4
|
|
||||||
channel: channel4
|
|
||||||
e: e4
|
|
||||||
more: more4
|
|
||||||
film: film4
|
|
||||||
"4seven": fourseven
|
|
||||||
seven: fourseven
|
|
||||||
|
|
||||||
channels:
|
|
||||||
channel4:
|
|
||||||
label: Channel Four
|
|
||||||
chip_desc: ["(?i)Select to watch\\s+Channel Four"]
|
|
||||||
e4:
|
|
||||||
label: E Four
|
|
||||||
chip_desc: ["(?i)Select to watch\\s+E Four"]
|
|
||||||
more4:
|
|
||||||
label: More Four
|
|
||||||
chip_desc: ["(?i)Select to watch\\s+More Four"]
|
|
||||||
film4:
|
|
||||||
label: Film Four
|
|
||||||
chip_desc: ["(?i)Select to watch\\s+Film Four"]
|
|
||||||
fourseven:
|
|
||||||
label: Four Seven
|
|
||||||
chip_desc: ["(?i)Select to watch\\s+Four Seven"]
|
|
||||||
|
|
||||||
ui:
|
|
||||||
launch_desc_contains: ["Home", "Live TV", "My Shows", "Downloads", "Search"]
|
|
||||||
live_tab: ["Live TV"]
|
|
||||||
live_tab_desc_re: ["(?i)^Live TV$"]
|
|
||||||
live_tab_text_re: ["(?i)^Live TV$"]
|
|
||||||
watch_live: ["Select to watch", "Play Episode"]
|
|
||||||
playback_desc_contains: ["Pause", "Unmute", "Cast"]
|
|
||||||
channel_scroll_max: 16
|
|
||||||
|
|
||||||
timeouts:
|
|
||||||
launch_wait_ui: 30s
|
|
||||||
launch_settle: 5s
|
|
||||||
live_nav: 20s
|
|
||||||
channel_find: 45s
|
|
||||||
after_channel: 2s
|
|
||||||
watch_live: 20s
|
|
||||||
playback: 45s
|
|
||||||
|
|
@ -1,175 +0,0 @@
|
||||||
package c4
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/adb"
|
|
||||||
"streamd/uiflow"
|
|
||||||
)
|
|
||||||
|
|
||||||
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 TV")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("[*] open Live TV…")
|
|
||||||
descRE := a.cfg.UI.LiveTabDescRE
|
|
||||||
if len(descRE) == 0 {
|
|
||||||
descRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
textRE := a.cfg.UI.LiveTabTextRE
|
|
||||||
if len(textRE) == 0 {
|
|
||||||
textRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
|
|
||||||
DescRE: descRE,
|
|
||||||
TextRE: textRE,
|
|
||||||
DescContains: a.cfg.UI.LiveTab,
|
|
||||||
TextContains: a.cfg.UI.LiveTab,
|
|
||||||
Pick: uiflow.PickFirst,
|
|
||||||
}, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
|
|
||||||
return fmt.Errorf("live tab: %w", err)
|
|
||||||
}
|
|
||||||
time.Sleep(1500 * time.Millisecond)
|
|
||||||
|
|
||||||
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err == nil && a.onLiveTab(nodes) {
|
|
||||||
fmt.Println("[*] Live TV ready")
|
|
||||||
a.disableLiveAutoPlay(c)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
time.Sleep(700 * time.Millisecond)
|
|
||||||
}
|
|
||||||
return fmt.Errorf("Live TV did not open")
|
|
||||||
}
|
|
||||||
|
|
||||||
// disableLiveAutoPlay turns off the Live TV "Auto-play" toggle so the app does
|
|
||||||
// not advance to the next channel while we wait for MITM.
|
|
||||||
func (a *App) disableLiveAutoPlay(c *adb.Client) {
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, n := range nodes {
|
|
||||||
d := strings.ToLower(strings.TrimSpace(n.Desc))
|
|
||||||
t := strings.ToLower(strings.TrimSpace(n.Text))
|
|
||||||
if d != "auto-play" && t != "auto-play" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if n.Selected || n.Checked {
|
|
||||||
fmt.Println("[*] disable Live Auto-play")
|
|
||||||
_ = c.Tap(n.CX(), n.CY())
|
|
||||||
time.Sleep(500 * time.Millisecond)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// State may not be exposed — leave alone when already off / unknown.
|
|
||||||
fmt.Println("[*] Live Auto-play control present (left as-is)")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) onLiveTab(nodes []adb.Node) bool {
|
|
||||||
for _, n := range nodes {
|
|
||||||
d := strings.ToLower(n.Desc)
|
|
||||||
if strings.Contains(d, "select to watch") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if strings.Contains(d, "now showing on") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if strings.EqualFold(n.Desc, "Live TV, heading") || strings.EqualFold(n.Text, "On now") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// tapChannelCard scrolls the Live list for "Select to watch {Label}" and taps it.
|
|
||||||
func (a *App) tapChannelCard(c *adb.Client, ch Channel) error {
|
|
||||||
pats := ch.ChipDesc
|
|
||||||
if len(pats) == 0 {
|
|
||||||
pats = []string{`(?i)Select to watch\s+` + regexp.QuoteMeta(ch.Label)}
|
|
||||||
}
|
|
||||||
chipRE := uiflow.CompileRes(pats)
|
|
||||||
fmt.Printf("[*] find Live card for %s…\n", ch.Label)
|
|
||||||
|
|
||||||
row, err := a.findChannelCard(c, chipRE)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] tap %q @ %d,%d\n", trimDesc(row.Desc, 60), row.CX(), row.CY())
|
|
||||||
if err := c.Tap(row.CX(), row.CY()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) findChannelCard(c *adb.Client, chipRE []*regexp.Regexp) (*adb.Node, error) {
|
|
||||||
scrollMax := a.cfg.UI.ChannelScrollMax
|
|
||||||
if scrollMax <= 0 {
|
|
||||||
scrollMax = 10
|
|
||||||
}
|
|
||||||
// Prefer starting near the top so Channel Four / E4 are reachable.
|
|
||||||
_ = c.Swipe(540, 1100, 540, 1900, 250)
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
|
|
||||||
for attempt := 0; attempt <= scrollMax; attempt++ {
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var best *adb.Node
|
|
||||||
for i := range nodes {
|
|
||||||
n := &nodes[i]
|
|
||||||
hay := n.Desc
|
|
||||||
if hay == "" {
|
|
||||||
hay = n.Text
|
|
||||||
}
|
|
||||||
if hay == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Skip cards clipped into the bottom nav (false taps).
|
|
||||||
if n.Y2 > 2100 || n.CY() > 2050 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, p := range chipRE {
|
|
||||||
if !p.MatchString(hay) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Prefer the explicit "Select to watch" control when present.
|
|
||||||
if strings.Contains(strings.ToLower(hay), "select to watch") {
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
if best == nil {
|
|
||||||
best = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if best != nil {
|
|
||||||
return best, nil
|
|
||||||
}
|
|
||||||
if attempt == scrollMax {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] scroll Live list (%d/%d)…\n", attempt+1, scrollMax)
|
|
||||||
_ = c.Swipe(540, 1950, 540, 900, 320)
|
|
||||||
time.Sleep(700 * time.Millisecond)
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("channel card not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimDesc(s string, n int) string {
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
if len(s) <= n {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return s[:n] + "…"
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
module streamd/modules
|
module drmdecryption/modules
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require streamd v0.0.0
|
require drmdecryption v0.0.0
|
||||||
|
|
||||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
|
||||||
replace streamd => ../pkg
|
replace drmdecryption => ../pkg
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,8 @@ package itv
|
||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Name is the module id (--app itv).
|
// Name is the module id (--app itv).
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,12 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
|
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
|
||||||
|
|
|
||||||
|
|
@ -1,133 +0,0 @@
|
||||||
package my5
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/modcfg"
|
|
||||||
"streamd/modules/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Name is the module id (--app my5).
|
|
||||||
const Name = "my5"
|
|
||||||
|
|
||||||
// Channel is one My5 / Channel 5 Live TV target.
|
|
||||||
// Logos in the Live TV rail have no accessibility text, so selection uses
|
|
||||||
// logo_index (0-based order in the left channel-logo recycler).
|
|
||||||
type Channel struct {
|
|
||||||
Label string `yaml:"label"`
|
|
||||||
LogoIndex int `yaml:"logo_index"`
|
|
||||||
ChipDesc []string `yaml:"chip_desc"` // unused; kept for YAML parity with other modules
|
|
||||||
PlayDesc []string `yaml:"play_desc"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config is modules/my5/module.yaml (preferred) or apps/modules/my5/module.yaml.
|
|
||||||
type Config struct {
|
|
||||||
provider.Common `yaml:",inline"`
|
|
||||||
|
|
||||||
Channels map[string]Channel `yaml:"channels"`
|
|
||||||
Timeouts Timeouts `yaml:"timeouts"`
|
|
||||||
UI UI `yaml:"ui"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Timeouts struct {
|
|
||||||
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
|
|
||||||
LaunchSettle provider.Duration `yaml:"launch_settle"`
|
|
||||||
LiveNav provider.Duration `yaml:"live_nav"`
|
|
||||||
ChannelFind provider.Duration `yaml:"channel_find"`
|
|
||||||
AfterChannel provider.Duration `yaml:"after_channel"`
|
|
||||||
WatchLive provider.Duration `yaml:"watch_live"`
|
|
||||||
Playback provider.Duration `yaml:"playback"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UI struct {
|
|
||||||
LaunchDescContains []string `yaml:"launch_desc_contains"`
|
|
||||||
LiveTab []string `yaml:"live_tab"`
|
|
||||||
LiveTabDescRE []string `yaml:"live_tab_desc_re"`
|
|
||||||
LiveTabTextRE []string `yaml:"live_tab_text_re"`
|
|
||||||
WatchLive []string `yaml:"watch_live"`
|
|
||||||
PlaybackDescContains []string `yaml:"playback_desc_contains"`
|
|
||||||
ChannelScrollMax int `yaml:"channel_scroll_max"`
|
|
||||||
// LogoMaxX: ImageViews with X1 below this are treated as channel logos.
|
|
||||||
LogoMaxX int `yaml:"logo_max_x"`
|
|
||||||
// LogoMinY / LogoMaxY: vertical band of the logos recycler (excludes player + nav).
|
|
||||||
LogoMinY int `yaml:"logo_min_y"`
|
|
||||||
LogoMaxY int `yaml:"logo_max_y"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c Config) withDefaults() Config {
|
|
||||||
t := &c.Timeouts
|
|
||||||
t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
|
|
||||||
t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
|
|
||||||
t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
|
|
||||||
t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
|
|
||||||
t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
|
|
||||||
t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
|
|
||||||
t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
|
|
||||||
|
|
||||||
u := &c.UI
|
|
||||||
if len(u.LaunchDescContains) == 0 {
|
|
||||||
u.LaunchDescContains = []string{"Home", "Live TV", "Search", "More", "Milkshake"}
|
|
||||||
}
|
|
||||||
if len(u.LiveTab) == 0 {
|
|
||||||
u.LiveTab = []string{"Live TV"}
|
|
||||||
}
|
|
||||||
if len(u.LiveTabDescRE) == 0 {
|
|
||||||
u.LiveTabDescRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if len(u.LiveTabTextRE) == 0 {
|
|
||||||
u.LiveTabTextRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if len(u.WatchLive) == 0 {
|
|
||||||
u.WatchLive = []string{"Play", "Watch"}
|
|
||||||
}
|
|
||||||
if len(u.PlaybackDescContains) == 0 {
|
|
||||||
u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
|
|
||||||
}
|
|
||||||
if u.ChannelScrollMax <= 0 {
|
|
||||||
u.ChannelScrollMax = 20
|
|
||||||
}
|
|
||||||
if u.LogoMaxX <= 0 {
|
|
||||||
u.LogoMaxX = 230
|
|
||||||
}
|
|
||||||
if u.LogoMinY <= 0 {
|
|
||||||
u.LogoMinY = 700
|
|
||||||
}
|
|
||||||
if u.LogoMaxY <= 0 {
|
|
||||||
u.LogoMaxY = 2100
|
|
||||||
}
|
|
||||||
if c.Package == "" {
|
|
||||||
c.Package = "com.mobileiq.demand5"
|
|
||||||
}
|
|
||||||
if c.Channels == nil {
|
|
||||||
c.Channels = map[string]Channel{}
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadConfig() (Config, modcfg.Result, error) {
|
|
||||||
var cfg Config
|
|
||||||
res, err := modcfg.Load(Name, &cfg)
|
|
||||||
if err != nil {
|
|
||||||
return cfg, res, err
|
|
||||||
}
|
|
||||||
cfg = cfg.withDefaults()
|
|
||||||
if v := modcfg.Env(Name, "package"); v != "" {
|
|
||||||
cfg.Package = v
|
|
||||||
}
|
|
||||||
if flags.packageName != "" {
|
|
||||||
cfg.Package = flags.packageName
|
|
||||||
}
|
|
||||||
if flags.caHash != "" {
|
|
||||||
cfg.CAHash = flags.caHash
|
|
||||||
}
|
|
||||||
if flags.proxyBin != "" {
|
|
||||||
cfg.ProxyBin = flags.proxyBin
|
|
||||||
}
|
|
||||||
return cfg, res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var flags struct {
|
|
||||||
packageName string
|
|
||||||
caHash string
|
|
||||||
proxyBin string
|
|
||||||
}
|
|
||||||
|
|
@ -1,118 +0,0 @@
|
||||||
# Channel 5 (My5 / "5") — published universal values (renamed to module.yaml in release zips).
|
|
||||||
# Live TV left-rail logos have no accessibility text; selection uses logo_index (0-based).
|
|
||||||
|
|
||||||
package: com.mobileiq.demand5
|
|
||||||
proxy_bin: bin/proxy-android-arm64
|
|
||||||
|
|
||||||
# SENSITIVE — set in local module.yaml after capture:
|
|
||||||
# license_url: "https://cassie.channel5.com/api/v2/licences/widevine/…"
|
|
||||||
|
|
||||||
# Transparent mode only MITMs open.live by default. Force My5 playlist / license hosts.
|
|
||||||
mitm_hosts:
|
|
||||||
- channel5.com
|
|
||||||
- corona.channel5.com
|
|
||||||
- cassie.channel5.com
|
|
||||||
- cassie-auth.channel5.com
|
|
||||||
- hwdash.channel5.com
|
|
||||||
- c5apps.channel5.com
|
|
||||||
|
|
||||||
score:
|
|
||||||
hosts:
|
|
||||||
- channel5.com
|
|
||||||
- corona.channel5.com
|
|
||||||
- cassie.channel5.com
|
|
||||||
- cassie-auth.channel5.com
|
|
||||||
- hwdash.channel5.com
|
|
||||||
- akamaized.net
|
|
||||||
- akadash
|
|
||||||
deny:
|
|
||||||
- google-analytics
|
|
||||||
- googletagmanager
|
|
||||||
- doubleclick
|
|
||||||
- scorecardresearch
|
|
||||||
- facebook.com
|
|
||||||
- crashlytics
|
|
||||||
- appsflyer
|
|
||||||
- optimizely
|
|
||||||
- kantarmedia
|
|
||||||
|
|
||||||
aliases:
|
|
||||||
c5: channel5
|
|
||||||
five: channel5
|
|
||||||
ch5: channel5
|
|
||||||
channel: channel5
|
|
||||||
my5: channel5
|
|
||||||
usa: 5usa
|
|
||||||
star: 5star
|
|
||||||
action: 5action
|
|
||||||
select: 5select
|
|
||||||
cops: 5cops
|
|
||||||
christmas: 5christmas
|
|
||||||
drama: 5drama
|
|
||||||
crime: 5crime
|
|
||||||
interceptors: policeinterceptors
|
|
||||||
pi: policeinterceptors
|
|
||||||
|
|
||||||
channels:
|
|
||||||
# Linear Freeview/Freely channels (logo rail order observed on moto g56).
|
|
||||||
channel5:
|
|
||||||
label: Channel 5
|
|
||||||
logo_index: 0
|
|
||||||
5usa:
|
|
||||||
label: 5USA
|
|
||||||
logo_index: 1
|
|
||||||
5star:
|
|
||||||
label: 5STAR
|
|
||||||
logo_index: 2
|
|
||||||
5action:
|
|
||||||
label: 5ACTION
|
|
||||||
logo_index: 3
|
|
||||||
5select:
|
|
||||||
label: 5SELECT
|
|
||||||
logo_index: 4
|
|
||||||
# FAST / box-set live rails (indices from Live TV scroll; may shift with seasons).
|
|
||||||
policeinterceptors:
|
|
||||||
label: Police Interceptors
|
|
||||||
logo_index: 5
|
|
||||||
5cops:
|
|
||||||
label: 5 Cops
|
|
||||||
logo_index: 6
|
|
||||||
5christmas:
|
|
||||||
label: 5 Christmas
|
|
||||||
logo_index: 7
|
|
||||||
5drama:
|
|
||||||
label: 5 Drama
|
|
||||||
logo_index: 8
|
|
||||||
bargainbrits:
|
|
||||||
label: Bargain Loving Brits
|
|
||||||
logo_index: 9
|
|
||||||
casualty247:
|
|
||||||
label: Casualty 24/7
|
|
||||||
logo_index: 10
|
|
||||||
rogueclaimers:
|
|
||||||
label: Rogue Claimers
|
|
||||||
logo_index: 11
|
|
||||||
5crime:
|
|
||||||
label: 5 Crime
|
|
||||||
logo_index: 12
|
|
||||||
|
|
||||||
ui:
|
|
||||||
launch_desc_contains: ["Home", "Live TV", "Search", "More", "Milkshake"]
|
|
||||||
live_tab: ["Live TV"]
|
|
||||||
live_tab_desc_re: ["(?i)^Live TV$"]
|
|
||||||
live_tab_text_re: ["(?i)^Live TV$"]
|
|
||||||
watch_live: ["Play", "Watch"]
|
|
||||||
playback_desc_contains: ["Pause", "Unmute", "Cast"]
|
|
||||||
channel_scroll_max: 20
|
|
||||||
logo_max_x: 230
|
|
||||||
logo_min_y: 700
|
|
||||||
logo_max_y: 2100
|
|
||||||
|
|
||||||
timeouts:
|
|
||||||
launch_wait_ui: 30s
|
|
||||||
launch_settle: 5s
|
|
||||||
live_nav: 20s
|
|
||||||
channel_find: 45s
|
|
||||||
after_channel: 2s
|
|
||||||
watch_live: 20s
|
|
||||||
playback: 45s
|
|
||||||
|
|
@ -1,160 +0,0 @@
|
||||||
// Package my5 is the Channel 5 (My5 / "5") Live TV provider module.
|
|
||||||
// Live TV uses a left-rail of channel logos (no content-desc); selection is by logo_index.
|
|
||||||
package my5
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/adb"
|
|
||||||
appreg "streamd/app"
|
|
||||||
"streamd/capture"
|
|
||||||
"streamd/modules/provider"
|
|
||||||
"streamd/mpd"
|
|
||||||
"streamd/uiflow"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
appreg.Register(Name, New)
|
|
||||||
appreg.RegisterFlags(bindFlags)
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindFlags(fs *flag.FlagSet) {
|
|
||||||
fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
|
|
||||||
fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
|
|
||||||
fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
|
|
||||||
}
|
|
||||||
|
|
||||||
// App is the My5 plugin.
|
|
||||||
type App struct {
|
|
||||||
*provider.Base
|
|
||||||
cfg Config
|
|
||||||
}
|
|
||||||
|
|
||||||
// New constructs the plugin from module.yaml + flags + env.
|
|
||||||
func New() (appreg.App, error) {
|
|
||||||
cfg, res, err := loadConfig()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
labels := make(map[string]string, len(cfg.Channels))
|
|
||||||
for id, ch := range cfg.Channels {
|
|
||||||
labels[id] = ch.Label
|
|
||||||
}
|
|
||||||
return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeyMode: My5 live uses a raw Widevine license response (Cassie).
|
|
||||||
func (a *App) KeyMode() string { return "raw" }
|
|
||||||
|
|
||||||
// CaptureHints: transparent MITM should yield the DASH MPD (+ license_url).
|
|
||||||
func (a *App) CaptureHints() capture.Hints {
|
|
||||||
return a.Hints("mpd")
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureHintsFor prefers URL substrings for this live channel when known.
|
|
||||||
func (a *App) CaptureHintsFor(channel string) capture.Hints {
|
|
||||||
h := a.CaptureHints()
|
|
||||||
id, err := a.Resolve(channel)
|
|
||||||
if err != nil {
|
|
||||||
id = strings.ToLower(strings.TrimSpace(channel))
|
|
||||||
}
|
|
||||||
// Prefer patterns filled after first successful captures; safe no-ops until then.
|
|
||||||
prefer := map[string][]string{
|
|
||||||
"channel5": {"channel5", "c5-", "/c5"},
|
|
||||||
"5usa": {"5usa", "usa"},
|
|
||||||
"5star": {"5star", "star"},
|
|
||||||
"5action": {"5action", "action"},
|
|
||||||
"5select": {"5select", "select"},
|
|
||||||
}
|
|
||||||
if p, ok := prefer[id]; ok {
|
|
||||||
h.PreferURLContains = p
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
|
|
||||||
func (a *App) UseTransparentMITM() bool { return true }
|
|
||||||
|
|
||||||
func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
|
|
||||||
|
|
||||||
func (a *App) Channels() []appreg.Channel {
|
|
||||||
out := make([]appreg.Channel, 0, len(a.cfg.Channels))
|
|
||||||
for _, id := range a.ChannelIDs() {
|
|
||||||
out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Launch cold-starts My5 and dismisses common first-run prompts.
|
|
||||||
func (a *App) Launch(c *adb.Client) error {
|
|
||||||
c.EnsureAwake()
|
|
||||||
fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
|
|
||||||
c.DismissShadeIfFocused()
|
|
||||||
a.dismissOnboarding(c)
|
|
||||||
if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
|
|
||||||
DescContains: a.cfg.UI.LaunchDescContains,
|
|
||||||
TextContains: a.cfg.UI.LaunchDescContains,
|
|
||||||
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AutoPlay opens Live TV, taps the channel logo by index, then the Now EPG cell.
|
|
||||||
func (a *App) AutoPlay(c *adb.Client, channel string) error {
|
|
||||||
id, err := a.Resolve(channel)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ch := a.cfg.Channels[id]
|
|
||||||
fmt.Printf("[*] Auto-play %s (logo %d)…\n", a.Label(id), ch.LogoIndex)
|
|
||||||
c.EnsureAwake()
|
|
||||||
c.DismissShadeIfFocused()
|
|
||||||
// Capture host normally Launch()s first; still start the app if we landed on the launcher.
|
|
||||||
if !a.appFocused(c) {
|
|
||||||
if err := a.Launch(c); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.dismissOnboarding(c)
|
|
||||||
|
|
||||||
if err := a.openLiveTab(c); err != nil {
|
|
||||||
return fmt.Errorf("Live TV tab: %w", err)
|
|
||||||
}
|
|
||||||
if err := a.tapChannelLogo(c, ch); err != nil {
|
|
||||||
return fmt.Errorf("channel logo %s: %w", a.Label(id), err)
|
|
||||||
}
|
|
||||||
if err := a.tapNowCell(c, ch); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] Now cell tap: %v — relying on embedded player\n", err)
|
|
||||||
}
|
|
||||||
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
|
|
||||||
Timeout: time.Duration(a.cfg.Timeouts.Playback),
|
|
||||||
SoftFail: true,
|
|
||||||
OrDescContains: []string{
|
|
||||||
"Pause",
|
|
||||||
"Unmute",
|
|
||||||
"Cast",
|
|
||||||
},
|
|
||||||
OrResourceContains: []string{
|
|
||||||
"c5player",
|
|
||||||
"video_view",
|
|
||||||
"video_player",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) VideoSelect() string { return "for=best" }
|
|
||||||
func (a *App) AudioSelect() string { return "for=best" }
|
|
||||||
func (a *App) RewriterName() string { return "none" }
|
|
||||||
func (a *App) LiveWaitSeconds() int { return 2 }
|
|
||||||
func (a *App) TSReadyBytes() int64 { return 256 << 10 }
|
|
||||||
|
|
@ -1,265 +0,0 @@
|
||||||
package my5
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"streamd/adb"
|
|
||||||
"streamd/uiflow"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (a *App) appFocused(c *adb.Client) bool {
|
|
||||||
out, err := c.Shell("dumpsys", "window")
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
pkg := a.Package()
|
|
||||||
for _, line := range strings.Split(out, "\n") {
|
|
||||||
if strings.Contains(line, "mCurrentFocus") && strings.Contains(line, pkg) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) dismissOnboarding(c *adb.Client) {
|
|
||||||
deadline := time.Now().Add(8 * time.Second)
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, n := range nodes {
|
|
||||||
t := strings.TrimSpace(n.Text)
|
|
||||||
switch {
|
|
||||||
case strings.EqualFold(t, "Not now"),
|
|
||||||
strings.EqualFold(t, "Just browse"),
|
|
||||||
strings.EqualFold(t, "Skip register"):
|
|
||||||
fmt.Printf("[*] dismiss %q\n", t)
|
|
||||||
_ = c.Tap(n.CX(), n.CY())
|
|
||||||
time.Sleep(800 * time.Millisecond)
|
|
||||||
goto next
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
next:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 TV")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("[*] open Live TV…")
|
|
||||||
descRE := a.cfg.UI.LiveTabDescRE
|
|
||||||
if len(descRE) == 0 {
|
|
||||||
descRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
textRE := a.cfg.UI.LiveTabTextRE
|
|
||||||
if len(textRE) == 0 {
|
|
||||||
textRE = []string{`(?i)^Live TV$`}
|
|
||||||
}
|
|
||||||
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
|
|
||||||
DescRE: descRE,
|
|
||||||
TextRE: textRE,
|
|
||||||
DescContains: a.cfg.UI.LiveTab,
|
|
||||||
TextContains: a.cfg.UI.LiveTab,
|
|
||||||
Pick: uiflow.PickFirst,
|
|
||||||
}, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
|
|
||||||
return fmt.Errorf("live tab: %w", err)
|
|
||||||
}
|
|
||||||
time.Sleep(1500 * time.Millisecond)
|
|
||||||
|
|
||||||
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err == nil && a.onLiveTab(nodes) {
|
|
||||||
fmt.Println("[*] Live TV ready")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
time.Sleep(700 * time.Millisecond)
|
|
||||||
}
|
|
||||||
return fmt.Errorf("Live TV did not open")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) onLiveTab(nodes []adb.Node) bool {
|
|
||||||
for _, n := range nodes {
|
|
||||||
id := strings.ToLower(n.ResourceID)
|
|
||||||
if strings.Contains(id, "tv_guide_channel_logos") ||
|
|
||||||
strings.Contains(id, "tv_guide_epg") ||
|
|
||||||
strings.Contains(id, "tv_guide_player") ||
|
|
||||||
strings.Contains(id, "tv_guide_navigation") && n.Selected {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if strings.EqualFold(n.Text, "Now") && strings.Contains(id, "tv_guide_header_now") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) logoNodes(nodes []adb.Node) []adb.Node {
|
|
||||||
maxX := a.cfg.UI.LogoMaxX
|
|
||||||
minY := a.cfg.UI.LogoMinY
|
|
||||||
maxY := a.cfg.UI.LogoMaxY
|
|
||||||
var out []adb.Node
|
|
||||||
for _, n := range nodes {
|
|
||||||
if !strings.Contains(n.Class, "ImageView") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Channel logos in the Live rail have empty resource-id; EPG thumbs do not.
|
|
||||||
if strings.TrimSpace(n.ResourceID) != "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if n.X1 >= maxX || n.Y1 < minY || n.Y1 >= maxY {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Skip tiny icons / nav glyphs.
|
|
||||||
if (n.Y2-n.Y1) < 120 || (n.X2-n.X1) < 120 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !n.Clickable {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, n)
|
|
||||||
}
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
if out[i].Y1 == out[j].Y1 {
|
|
||||||
return out[i].X1 < out[j].X1
|
|
||||||
}
|
|
||||||
return out[i].Y1 < out[j].Y1
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// tapChannelLogo scrolls the left logo rail from the top by logo_index rows, then taps.
|
|
||||||
func (a *App) tapChannelLogo(c *adb.Client, ch Channel) error {
|
|
||||||
want := ch.LogoIndex
|
|
||||||
if want < 0 {
|
|
||||||
return fmt.Errorf("logo_index must be >= 0")
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] find logo index %d (%s)…\n", want, ch.Label)
|
|
||||||
|
|
||||||
// Scroll to the top of the logo rail.
|
|
||||||
for i := 0; i < 8; i++ {
|
|
||||||
_ = c.Swipe(118, 1000, 118, 1950, 250)
|
|
||||||
time.Sleep(280 * time.Millisecond)
|
|
||||||
}
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
logos := a.logoNodes(nodes)
|
|
||||||
if len(logos) == 0 {
|
|
||||||
return fmt.Errorf("no channel logos visible")
|
|
||||||
}
|
|
||||||
rowH := logos[0].Y2 - logos[0].Y1
|
|
||||||
if rowH < 120 {
|
|
||||||
rowH = 205
|
|
||||||
}
|
|
||||||
// Gap between rows is small; step ≈ row height + ~10px from observed layout.
|
|
||||||
step := rowH + 10
|
|
||||||
|
|
||||||
// Bring target near the top by single-row swipes, then tap it in-view.
|
|
||||||
for i := 0; i < want; i++ {
|
|
||||||
_ = c.Swipe(118, 1200, 118, 1200-step, 220)
|
|
||||||
time.Sleep(350 * time.Millisecond)
|
|
||||||
}
|
|
||||||
time.Sleep(400 * time.Millisecond)
|
|
||||||
|
|
||||||
nodes, err = c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
logos = a.logoNodes(nodes)
|
|
||||||
if len(logos) == 0 {
|
|
||||||
return fmt.Errorf("no channel logos after scroll to index %d", want)
|
|
||||||
}
|
|
||||||
|
|
||||||
var n adb.Node
|
|
||||||
if want == 0 {
|
|
||||||
n = logos[0]
|
|
||||||
} else {
|
|
||||||
// After want single-row swipes from top, the target is the first fully
|
|
||||||
// visible logo (previous rows scrolled off). Prefer logos[0] when fully
|
|
||||||
// on-screen; otherwise logos[1] if the top one is clipped.
|
|
||||||
n = logos[0]
|
|
||||||
if n.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
|
|
||||||
n = logos[1]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if n.CY() >= 2050 || n.Y2 > a.cfg.UI.LogoMaxY {
|
|
||||||
return fmt.Errorf("logo index %d clipped into nav", want)
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] tap logo %d @ %d,%d\n", want, n.CX(), n.CY())
|
|
||||||
if err := c.Tap(n.CX(), n.CY()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func abs(v int) int {
|
|
||||||
if v < 0 {
|
|
||||||
return -v
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
// tapNowCell taps the "Now" EPG cell aligned with the selected logo row.
|
|
||||||
// After tapChannelLogo scrolls the target to the top of the rail, align to logos[0].
|
|
||||||
func (a *App) tapNowCell(c *adb.Client, ch Channel) error {
|
|
||||||
_ = ch
|
|
||||||
nodes, err := c.DumpUI(a.CacheDir())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
logos := a.logoNodes(nodes)
|
|
||||||
if len(logos) == 0 {
|
|
||||||
return fmt.Errorf("no logos after select")
|
|
||||||
}
|
|
||||||
logo := &logos[0]
|
|
||||||
if logo.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
|
|
||||||
logo = &logos[1]
|
|
||||||
}
|
|
||||||
|
|
||||||
var best *adb.Node
|
|
||||||
bestDist := 1 << 30
|
|
||||||
for i := range nodes {
|
|
||||||
n := &nodes[i]
|
|
||||||
id := strings.ToLower(n.ResourceID)
|
|
||||||
if !strings.Contains(id, "epg_now_view") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
d := abs(n.CY() - logo.CY())
|
|
||||||
if d < bestDist {
|
|
||||||
bestDist = d
|
|
||||||
best = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if best == nil {
|
|
||||||
// Fallback: tap embedded player surface.
|
|
||||||
for i := range nodes {
|
|
||||||
n := &nodes[i]
|
|
||||||
id := strings.ToLower(n.ResourceID)
|
|
||||||
if strings.Contains(id, "video_view") || strings.Contains(id, "c5player") {
|
|
||||||
fmt.Printf("[*] tap player @ %d,%d\n", n.CX(), n.CY())
|
|
||||||
return c.Tap(n.CX(), n.CY())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("Now cell not found")
|
|
||||||
}
|
|
||||||
fmt.Printf("[*] tap Now cell @ %d,%d\n", best.CX(), best.CY())
|
|
||||||
if err := c.Tap(best.CX(), best.CY()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
@ -10,10 +10,10 @@ import (
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/phonecap"
|
"drmdecryption/phonecap"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Common is the part of a module.yaml that every module has. Modules embed it in
|
// Common is the part of a module.yaml that every module has. Modules embed it in
|
||||||
|
|
@ -57,7 +57,7 @@ func (b *Base) ConfigPath() string { return b.cfg.Path }
|
||||||
func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
|
func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
|
||||||
|
|
||||||
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
|
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
|
||||||
// proxy.FindLocalBin — next to streamd, then repo bin/).
|
// proxy.FindLocalBin — next to drm.exe, then repo bin/).
|
||||||
func (b *Base) ProxyBin() string {
|
func (b *Base) ProxyBin() string {
|
||||||
if b.common.ProxyBin != "" {
|
if b.common.ProxyBin != "" {
|
||||||
return modcfg.Resolve(b.common.ProxyBin)
|
return modcfg.Resolve(b.common.ProxyBin)
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,9 @@ package rte
|
||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Name is the module id (--app rte).
|
// Name is the module id (--app rte).
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The rewriter must publish a usable manifest from the KID alone — this is the
|
// The rewriter must publish a usable manifest from the KID alone — this is the
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -9,12 +9,12 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Compile-time proof the plugin satisfies every interface the host expects.
|
// Compile-time proof the plugin satisfies every interface the host expects.
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,8 @@ import (
|
||||||
"regexp"
|
"regexp"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
|
// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,9 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/brightcove"
|
"drmdecryption/brightcove"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// playbackConfig is the app's remote config blob. It is decoded generically: the
|
// playbackConfig is the app's remote config blob. It is decoded generically: the
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,9 @@ package tg4
|
||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Name is the module id (--app tg4).
|
// Name is the module id (--app tg4).
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,10 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/brightcove"
|
"drmdecryption/brightcove"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
"streamd/wvkey"
|
"drmdecryption/wvkey"
|
||||||
)
|
)
|
||||||
|
|
||||||
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
|
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// openLivePage navigates to the Live page: if a menu entry is visible tap it,
|
// openLivePage navigates to the Live page: if a menu entry is visible tap it,
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,12 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/uiflow"
|
"drmdecryption/uiflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,9 @@ package tg4
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
appreg "streamd/app"
|
appreg "drmdecryption/app"
|
||||||
"streamd/modcfg"
|
"drmdecryption/modcfg"
|
||||||
"streamd/modules/provider"
|
"drmdecryption/modules/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Compile-time proof the plugin satisfies every interface the host expects.
|
// Compile-time proof the plugin satisfies every interface the host expects.
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
# pkg — shared Go libraries
|
# pkg — shared Go libraries
|
||||||
|
|
||||||
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
|
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
|
||||||
and `apps/modules` as module `streamd` via:
|
and `apps/modules` as module `drmdecryption` via:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
replace streamd => ../pkg
|
replace drmdecryption => ../pkg
|
||||||
```
|
```
|
||||||
|
|
||||||
## Packages
|
## Packages
|
||||||
|
|
@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
|
||||||
go -C apps/pkg test ./...
|
go -C apps/pkg test ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
|
No binary of its own — everything ships in `bin/drm`, built from `apps/cli`.
|
||||||
|
|
|
||||||
|
|
@ -219,8 +219,6 @@ type Node struct {
|
||||||
Class string
|
Class string
|
||||||
ResourceID string
|
ResourceID string
|
||||||
Clickable bool
|
Clickable bool
|
||||||
Selected bool
|
|
||||||
Checked bool
|
|
||||||
X1, Y1 int
|
X1, Y1 int
|
||||||
X2, Y2 int
|
X2, Y2 int
|
||||||
}
|
}
|
||||||
|
|
@ -262,8 +260,6 @@ func parseNodes(xml string) []Node {
|
||||||
Class: attr("class"),
|
Class: attr("class"),
|
||||||
ResourceID: attr("resource-id"),
|
ResourceID: attr("resource-id"),
|
||||||
Clickable: attr("clickable") == "true",
|
Clickable: attr("clickable") == "true",
|
||||||
Selected: attr("selected") == "true",
|
|
||||||
Checked: attr("checked") == "true",
|
|
||||||
X1: x1, Y1: y1, X2: x2, Y2: y2,
|
X1: x1, Y1: y1, X2: x2, Y2: y2,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,10 @@ import (
|
||||||
"sort"
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Channel is a named live target inside an app (e.g. rteone).
|
// Channel is a named live target inside an app (e.g. rteone).
|
||||||
|
|
@ -89,19 +89,6 @@ type MitmHostList interface {
|
||||||
MitmHosts() []string
|
MitmHosts() []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChannelCaptureHints lets a module bias Wait scoring for a specific channel
|
|
||||||
// (e.g. prefer channel(e4) MPD when capturing E4 while neighbours prefetch).
|
|
||||||
type ChannelCaptureHints interface {
|
|
||||||
CaptureHintsFor(channel string) capture.Hints
|
|
||||||
}
|
|
||||||
|
|
||||||
// RequireWVD is implemented by apps that refuse MPD-only captures. When true,
|
|
||||||
// `drm capture --app …` must pass --wvd; phonecap will not soft-save a session
|
|
||||||
// without keys.
|
|
||||||
type RequireWVD interface {
|
|
||||||
RequireWVD() bool
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
registry = map[string]func() (App, error){}
|
registry = map[string]func() (App, error){}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// Package bootstrap materialises a GitHub-like install tree next to streamd
|
// Package bootstrap materialises a GitHub-like install tree next to drm.exe
|
||||||
// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
|
// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
|
||||||
package bootstrap
|
package bootstrap
|
||||||
|
|
||||||
|
|
@ -17,7 +17,7 @@ var embedded embed.FS
|
||||||
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
|
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
|
||||||
|
|
||||||
// InstallRoot is the directory that should contain apps/, bin/, outputs/.
|
// InstallRoot is the directory that should contain apps/, bin/, outputs/.
|
||||||
// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
|
// If drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory.
|
||||||
func InstallRoot() (string, error) {
|
func InstallRoot() (string, error) {
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -91,30 +91,27 @@ func Ensure(root string) (created []string, err error) {
|
||||||
return created, err
|
return created, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If streamd is not already under bin/, copy it there for 1:1 layout.
|
// If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout.
|
||||||
if err := ensureBinHost(root); err != nil {
|
if err := ensureBinDrm(root); err != nil {
|
||||||
return created, err
|
return created, err
|
||||||
}
|
}
|
||||||
return created, nil
|
return created, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ensureBinHost(root string) error {
|
func ensureBinDrm(root string) error {
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
exe, _ = filepath.EvalSymlinks(exe)
|
exe, _ = filepath.EvalSymlinks(exe)
|
||||||
return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
|
dest := filepath.Join(root, "bin", "drm.exe")
|
||||||
}
|
if sameFile(exe, dest) {
|
||||||
|
|
||||||
func copyExeIfMissing(src, dest string) error {
|
|
||||||
if sameFile(src, dest) {
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(src)
|
data, err := os.ReadFile(exe)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -157,7 +154,7 @@ func EnsureAndLogFor(cmd string) error {
|
||||||
}
|
}
|
||||||
proxy := filepath.Join(root, "bin", "proxy-android-arm64")
|
proxy := filepath.Join(root, "bin", "proxy-android-arm64")
|
||||||
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
|
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
|
||||||
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd or use a release build that embeds it\n")
|
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n")
|
||||||
}
|
}
|
||||||
// Providers live under modules/; only warn when the command needs them.
|
// Providers live under modules/; only warn when the command needs them.
|
||||||
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
|
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,14 @@
|
||||||
# Streamd
|
# Null DRM
|
||||||
|
|
||||||
Host binary **`streamd`** + providers under **`modules/`**.
|
Host binary **`drm`** + providers under **`modules/`**.
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
|
1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
|
||||||
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
|
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
|
||||||
3. `streamd proxy install-ca --reinject`
|
3. `drm proxy install-ca --reinject`
|
||||||
4. `streamd capture --app bbc --channel bbcone --wait 120`
|
4. `drm capture --app bbc --channel bbcone --wait 120`
|
||||||
5. `streamd proxy reset` when finished.
|
5. `drm proxy reset` when finished.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
drm modules
|
drm modules
|
||||||
|
|
@ -17,6 +17,6 @@ drm catalog --app NAME --channel ID [--keys] [--json]
|
||||||
drm proxy install-ca --reinject | reset | transparent --package PKG
|
drm proxy install-ca --reinject | reset | transparent --package PKG
|
||||||
```
|
```
|
||||||
|
|
||||||
`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
|
`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
|
||||||
|
|
||||||
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
|
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
module streamd
|
module drmdecryption
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# Dependencies for wvkey.py (the only Python in the project).
|
|
||||||
# Install into a venv at the repo root:
|
|
||||||
# python -m venv .venv
|
|
||||||
# .venv/bin/pip install -r apps/wvkey/requirements.txt
|
|
||||||
pywidevine==1.9.0
|
|
||||||
requests==2.34.2
|
|
||||||
|
|
@ -1,367 +0,0 @@
|
||||||
#!/usr/bin/env python3
|
|
||||||
"""Thin Widevine CDM helper for the Go capture tooling.
|
|
||||||
|
|
||||||
Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
|
|
||||||
Exit code 0 on success.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
.venv/Scripts/python.exe wvkey.py \\
|
|
||||||
--wvd path/to/device.wvd \\
|
|
||||||
--pssh 'AAAA…' \\
|
|
||||||
--license-url 'https://…' \\
|
|
||||||
--auth 'Basic …' \\
|
|
||||||
--pid 'xxxx' \\
|
|
||||||
--quiet
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import base64
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import requests
|
|
||||||
from pywidevine.cdm import Cdm
|
|
||||||
from pywidevine.device import Device
|
|
||||||
from pywidevine.pssh import PSSH
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_content_keys_modulardrm(
|
|
||||||
*,
|
|
||||||
wvd: Path,
|
|
||||||
pssh_b64: str,
|
|
||||||
auth: str,
|
|
||||||
release_pid: str,
|
|
||||||
license_url: str,
|
|
||||||
user_agent: str,
|
|
||||||
) -> list[str]:
|
|
||||||
"""RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
|
|
||||||
device = Device.load(str(wvd))
|
|
||||||
cdm = Cdm.from_device(device)
|
|
||||||
session_id = cdm.open()
|
|
||||||
try:
|
|
||||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
|
||||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
|
||||||
payload = {
|
|
||||||
"getWidevineLicense": {
|
|
||||||
"releasePid": release_pid,
|
|
||||||
"widevineChallenge": challenge_b64,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Accept-Encoding": "gzip",
|
|
||||||
"Authorization": auth,
|
|
||||||
"Content-Type": "application/json; charset=utf-8",
|
|
||||||
}
|
|
||||||
if user_agent:
|
|
||||||
headers["User-Agent"] = user_agent
|
|
||||||
response = requests.post(license_url, json=payload, headers=headers, timeout=30)
|
|
||||||
data = response.json()
|
|
||||||
if data.get("isException"):
|
|
||||||
raise RuntimeError(data.get("description") or "license server exception")
|
|
||||||
license_b64 = (
|
|
||||||
data.get("getWidevineLicenseResponse", {}).get("license")
|
|
||||||
or data.get("license")
|
|
||||||
)
|
|
||||||
if not license_b64:
|
|
||||||
raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
|
|
||||||
cdm.parse_license(session_id, base64.b64decode(license_b64))
|
|
||||||
keys = [
|
|
||||||
f"{key.kid.hex}:{key.key.hex()}"
|
|
||||||
for key in cdm.get_keys(session_id)
|
|
||||||
if key.type == "CONTENT"
|
|
||||||
]
|
|
||||||
finally:
|
|
||||||
cdm.close(session_id)
|
|
||||||
if not keys:
|
|
||||||
raise RuntimeError("no CONTENT keys")
|
|
||||||
return keys
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_content_keys_raw(
|
|
||||||
*,
|
|
||||||
wvd: Path,
|
|
||||||
pssh_b64: str,
|
|
||||||
license_url: str,
|
|
||||||
user_agent: str,
|
|
||||||
) -> list[str]:
|
|
||||||
"""Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
|
|
||||||
device = Device.load(str(wvd))
|
|
||||||
cdm = Cdm.from_device(device)
|
|
||||||
session_id = cdm.open()
|
|
||||||
try:
|
|
||||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/octet-stream",
|
|
||||||
"Accept": "*/*",
|
|
||||||
}
|
|
||||||
if user_agent:
|
|
||||||
headers["User-Agent"] = user_agent
|
|
||||||
response = requests.post(
|
|
||||||
license_url, data=challenge, headers=headers, timeout=30
|
|
||||||
)
|
|
||||||
if response.status_code >= 400:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
|
||||||
)
|
|
||||||
body = response.content
|
|
||||||
if not body:
|
|
||||||
raise RuntimeError("empty license response body")
|
|
||||||
# Some servers wrap base64 text; try raw first, then b64.
|
|
||||||
try:
|
|
||||||
cdm.parse_license(session_id, body)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
cdm.parse_license(session_id, base64.b64decode(body))
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"parse_license failed ({len(body)} bytes): {exc}"
|
|
||||||
) from exc
|
|
||||||
keys = [
|
|
||||||
f"{key.kid.hex}:{key.key.hex()}"
|
|
||||||
for key in cdm.get_keys(session_id)
|
|
||||||
if key.type == "CONTENT"
|
|
||||||
]
|
|
||||||
finally:
|
|
||||||
cdm.close(session_id)
|
|
||||||
if not keys:
|
|
||||||
raise RuntimeError("no CONTENT keys")
|
|
||||||
return keys
|
|
||||||
|
|
||||||
|
|
||||||
_CHALLENGE_KEYS = (
|
|
||||||
"request",
|
|
||||||
"licenseRequest",
|
|
||||||
"license_request",
|
|
||||||
"widevineChallenge",
|
|
||||||
"widevine_challenge",
|
|
||||||
"challenge",
|
|
||||||
"payload",
|
|
||||||
"rawLicenseRequestBase64",
|
|
||||||
"message",
|
|
||||||
"drm_info",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
|
|
||||||
"""Replace the Widevine challenge field inside a captured JSON license body."""
|
|
||||||
if isinstance(obj, dict):
|
|
||||||
for key in _CHALLENGE_KEYS:
|
|
||||||
if key not in obj:
|
|
||||||
continue
|
|
||||||
val = obj[key]
|
|
||||||
if key == "drm_info" and isinstance(val, list):
|
|
||||||
obj[key] = list(challenge_bytes)
|
|
||||||
return True
|
|
||||||
if isinstance(val, str) and len(val) >= 8:
|
|
||||||
obj[key] = challenge_b64
|
|
||||||
return True
|
|
||||||
if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
|
|
||||||
return True
|
|
||||||
for val in obj.values():
|
|
||||||
if _replace_challenge(val, challenge_b64, challenge_bytes):
|
|
||||||
return True
|
|
||||||
elif isinstance(obj, list):
|
|
||||||
for item in obj:
|
|
||||||
if _replace_challenge(item, challenge_b64, challenge_bytes):
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _license_bytes_from_response(response: requests.Response) -> bytes:
|
|
||||||
body = response.content
|
|
||||||
if not body:
|
|
||||||
raise RuntimeError("empty license response body")
|
|
||||||
# Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
|
|
||||||
try:
|
|
||||||
data = response.json()
|
|
||||||
except Exception:
|
|
||||||
data = None
|
|
||||||
if isinstance(data, dict):
|
|
||||||
for path in (
|
|
||||||
("license",),
|
|
||||||
("licenseResponse",),
|
|
||||||
("license_response",),
|
|
||||||
("payload",),
|
|
||||||
("message",),
|
|
||||||
("getWidevineLicenseResponse", "license"),
|
|
||||||
("status", "license"),
|
|
||||||
):
|
|
||||||
cur: object = data
|
|
||||||
ok = True
|
|
||||||
for key in path:
|
|
||||||
if not isinstance(cur, dict) or key not in cur:
|
|
||||||
ok = False
|
|
||||||
break
|
|
||||||
cur = cur[key]
|
|
||||||
if ok and isinstance(cur, str) and cur:
|
|
||||||
try:
|
|
||||||
return base64.b64decode(cur)
|
|
||||||
except Exception:
|
|
||||||
return cur.encode("utf-8")
|
|
||||||
# Some LSP responses nest the blob under status.success payload.
|
|
||||||
if data.get("status", {}).get("success") is False:
|
|
||||||
raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_content_keys_wrap(
|
|
||||||
*,
|
|
||||||
wvd: Path,
|
|
||||||
pssh_b64: str,
|
|
||||||
license_url: str,
|
|
||||||
wrap_json: str,
|
|
||||||
user_agent: str,
|
|
||||||
) -> list[str]:
|
|
||||||
"""Re-POST a captured JSON license body with a fresh local CDM challenge.
|
|
||||||
|
|
||||||
Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
|
|
||||||
octet-stream (HTTP 415) and need the phone's token fields intact.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
template = json.loads(wrap_json)
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
|
|
||||||
|
|
||||||
device = Device.load(str(wvd))
|
|
||||||
cdm = Cdm.from_device(device)
|
|
||||||
session_id = cdm.open()
|
|
||||||
try:
|
|
||||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
|
||||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
|
||||||
if not _replace_challenge(template, challenge_b64, challenge):
|
|
||||||
raise RuntimeError(
|
|
||||||
"wrap-json has no recognisable challenge field "
|
|
||||||
f"(tried {', '.join(_CHALLENGE_KEYS)})"
|
|
||||||
)
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Accept": "application/json, */*",
|
|
||||||
}
|
|
||||||
if user_agent:
|
|
||||||
headers["User-Agent"] = user_agent
|
|
||||||
response = requests.post(
|
|
||||||
license_url, json=template, headers=headers, timeout=30
|
|
||||||
)
|
|
||||||
if response.status_code >= 400:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
|
||||||
)
|
|
||||||
license_bytes = _license_bytes_from_response(response)
|
|
||||||
try:
|
|
||||||
cdm.parse_license(session_id, license_bytes)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
cdm.parse_license(session_id, base64.b64decode(license_bytes))
|
|
||||||
except Exception as exc:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"parse_license failed ({len(license_bytes)} bytes): {exc}"
|
|
||||||
) from exc
|
|
||||||
keys = [
|
|
||||||
f"{key.kid.hex}:{key.key.hex()}"
|
|
||||||
for key in cdm.get_keys(session_id)
|
|
||||||
if key.type == "CONTENT"
|
|
||||||
]
|
|
||||||
finally:
|
|
||||||
cdm.close(session_id)
|
|
||||||
if not keys:
|
|
||||||
raise RuntimeError("no CONTENT keys")
|
|
||||||
return keys
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
|
|
||||||
p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
|
|
||||||
p.add_argument("--pssh", required=True, help="Base64 PSSH box")
|
|
||||||
p.add_argument(
|
|
||||||
"--mode",
|
|
||||||
choices=("modulardrm", "raw", "wrap"),
|
|
||||||
default="modulardrm",
|
|
||||||
help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
|
|
||||||
)
|
|
||||||
p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
|
|
||||||
p.add_argument("--pid", default="", help="releasePid (modulardrm)")
|
|
||||||
p.add_argument(
|
|
||||||
"--wrap-json",
|
|
||||||
default="",
|
|
||||||
help="Captured phone license POST JSON (wrap mode)",
|
|
||||||
)
|
|
||||||
p.add_argument(
|
|
||||||
"--license-url",
|
|
||||||
required=True,
|
|
||||||
help="Widevine license server URL",
|
|
||||||
)
|
|
||||||
p.add_argument(
|
|
||||||
"--user-agent",
|
|
||||||
default="",
|
|
||||||
help="Optional User-Agent for the license request",
|
|
||||||
)
|
|
||||||
p.add_argument(
|
|
||||||
"--quiet",
|
|
||||||
action="store_true",
|
|
||||||
help="Print only KID:KEY lines (for Go tooling)",
|
|
||||||
)
|
|
||||||
p.add_argument(
|
|
||||||
"--all",
|
|
||||||
action="store_true",
|
|
||||||
help="Print every CONTENT key (default: first only)",
|
|
||||||
)
|
|
||||||
args = p.parse_args(argv)
|
|
||||||
|
|
||||||
if not args.wvd.is_file():
|
|
||||||
print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
|
|
||||||
try:
|
|
||||||
if args.mode == "raw":
|
|
||||||
keys = fetch_content_keys_raw(
|
|
||||||
wvd=args.wvd,
|
|
||||||
pssh_b64=args.pssh,
|
|
||||||
license_url=args.license_url,
|
|
||||||
user_agent=args.user_agent,
|
|
||||||
)
|
|
||||||
elif args.mode == "wrap":
|
|
||||||
if not args.wrap_json.strip():
|
|
||||||
print(
|
|
||||||
"[!] --wrap-json required for wrap mode "
|
|
||||||
"(phone must complete a license POST during capture)",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
return 2
|
|
||||||
keys = fetch_content_keys_wrap(
|
|
||||||
wvd=args.wvd,
|
|
||||||
pssh_b64=args.pssh,
|
|
||||||
license_url=args.license_url,
|
|
||||||
wrap_json=args.wrap_json,
|
|
||||||
user_agent=args.user_agent,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
if not args.auth or not args.pid:
|
|
||||||
print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
keys = fetch_content_keys_modulardrm(
|
|
||||||
wvd=args.wvd,
|
|
||||||
pssh_b64=args.pssh,
|
|
||||||
auth=args.auth,
|
|
||||||
release_pid=args.pid,
|
|
||||||
license_url=args.license_url,
|
|
||||||
user_agent=args.user_agent,
|
|
||||||
)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"[!] {exc}", file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
out = keys if args.all else keys[:1]
|
|
||||||
if not args.quiet:
|
|
||||||
print("[+] Keys:", file=sys.stderr)
|
|
||||||
for pair in out:
|
|
||||||
print(f"--key {pair}", file=sys.stderr)
|
|
||||||
for pair in out:
|
|
||||||
print(pair)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# External modules
|
# External modules
|
||||||
|
|
||||||
Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
|
Each subdirectory is a provider the `drm` host discovers, builds, and runs.
|
||||||
|
|
||||||
```
|
```
|
||||||
modules/
|
modules/
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
module streamd
|
module drmdecryption
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Hints tell the waiter which fields / log tags mean a capture is complete.
|
// Hints tell the waiter which fields / log tags mean a capture is complete.
|
||||||
|
|
@ -24,9 +24,6 @@ type Hints struct {
|
||||||
// Score ranks candidate manifest URLs. Zero value falls back to
|
// Score ranks candidate manifest URLs. Zero value falls back to
|
||||||
// DefaultScoreCfg, which has no provider hosts.
|
// DefaultScoreCfg, which has no provider hosts.
|
||||||
Score ScoreCfg
|
Score ScoreCfg
|
||||||
// PreferURLContains boosts MPDs whose URL contains any of these substrings
|
|
||||||
// (e.g. channel(e4) for Channel 4 Live). Used when an app prefetches neighbours.
|
|
||||||
PreferURLContains []string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoteCapPaths are the on-device locations the MITM may persist its capture
|
// RemoteCapPaths are the on-device locations the MITM may persist its capture
|
||||||
|
|
@ -62,23 +59,10 @@ func DefaultPassiveHints() Hints {
|
||||||
|
|
||||||
// score applies the hints' URL scoring, defaulting when unset.
|
// score applies the hints' URL scoring, defaulting when unset.
|
||||||
func (h Hints) score(u string) int {
|
func (h Hints) score(u string) int {
|
||||||
var sc int
|
|
||||||
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
|
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
|
||||||
sc = DefaultScoreCfg().Score(u)
|
return DefaultScoreCfg().Score(u)
|
||||||
} else {
|
|
||||||
sc = h.Score.Score(u)
|
|
||||||
}
|
}
|
||||||
if sc <= 0 || len(h.PreferURLContains) == 0 {
|
return h.Score.Score(u)
|
||||||
return sc
|
|
||||||
}
|
|
||||||
low := strings.ToLower(u)
|
|
||||||
for _, p := range h.PreferURLContains {
|
|
||||||
p = strings.ToLower(strings.TrimSpace(p))
|
|
||||||
if p != "" && strings.Contains(low, p) {
|
|
||||||
return sc + 1000
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sc
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Data is the merged capture payload before key fetch.
|
// Data is the merged capture payload before key fetch.
|
||||||
|
|
@ -86,25 +70,6 @@ type Data map[string]string
|
||||||
|
|
||||||
func (d Data) Get(k string) string { return d[k] }
|
func (d Data) Get(k string) string { return d[k] }
|
||||||
|
|
||||||
// preferSatisfied is true when no PreferURLContains is set, or the chosen MPD
|
|
||||||
// matches one of the preferred substrings.
|
|
||||||
func preferSatisfied(cap Data, hints Hints) bool {
|
|
||||||
if len(hints.PreferURLContains) == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
mpd := strings.ToLower(strings.TrimSpace(cap["mpd"]))
|
|
||||||
if mpd == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, p := range hints.PreferURLContains {
|
|
||||||
p = strings.ToLower(strings.TrimSpace(p))
|
|
||||||
if p != "" && strings.Contains(mpd, p) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait pulls device JSON + local mirrored log until required fields exist.
|
// Wait pulls device JSON + local mirrored log until required fields exist.
|
||||||
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
|
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
|
||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
|
|
@ -139,7 +104,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
|
||||||
enrichFromProxyLog(cap, logText, hints)
|
enrichFromProxyLog(cap, logText, hints)
|
||||||
|
|
||||||
if hints.BestEffort {
|
if hints.BestEffort {
|
||||||
if hasUseful(cap, hints) && preferSatisfied(cap, hints) {
|
if hasUseful(cap, hints) {
|
||||||
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
|
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
|
||||||
return cap, nil
|
return cap, nil
|
||||||
}
|
}
|
||||||
|
|
@ -151,7 +116,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !missing && preferSatisfied(cap, hints) {
|
if !missing {
|
||||||
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
|
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
|
||||||
return cap, nil
|
return cap, nil
|
||||||
}
|
}
|
||||||
|
|
@ -160,7 +125,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
|
||||||
have := []string{}
|
have := []string{}
|
||||||
keys := hints.Require
|
keys := hints.Require
|
||||||
if hints.BestEffort {
|
if hints.BestEffort {
|
||||||
keys = []string{"mpd", "license_url", "pssh", "auth", "pid", "license_body"}
|
keys = []string{"mpd", "license_url", "pssh", "auth", "pid"}
|
||||||
}
|
}
|
||||||
for _, k := range keys {
|
for _, k := range keys {
|
||||||
if cap[k] != "" {
|
if cap[k] != "" {
|
||||||
|
|
@ -260,8 +225,7 @@ func enrichFromProxyLog(cap Data, logText string, hints Hints) {
|
||||||
if sc <= 0 {
|
if sc <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Prefer higher score; on a tie keep the later URL (last stream played).
|
if sc > bestScore {
|
||||||
if sc > bestScore || (sc == bestScore && sc > 0) {
|
|
||||||
bestScore = sc
|
bestScore = sc
|
||||||
bestMPD = u
|
bestMPD = u
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
module streamd
|
module drmdecryption
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,14 +15,13 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/modhost"
|
"drmdecryption/modhost"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Dir returns the directory holding a module's values.
|
// Dir returns the directory holding a module's values.
|
||||||
// Prefers the active modules dir (see modhost / --modules-dir); then the
|
// Prefers the active modules dir (see modhost / --modules-dir); falls back to
|
||||||
// directory beside a panel/release binary (<mod>/.bin/<name>); then
|
|
||||||
// apps/modules/<name>/ for older checkouts.
|
// apps/modules/<name>/ for older checkouts.
|
||||||
func Dir(name string) string {
|
func Dir(name string) string {
|
||||||
preferred := filepath.Join(modhost.ModulesDir(""), name)
|
preferred := filepath.Join(modhost.ModulesDir(""), name)
|
||||||
|
|
@ -32,9 +31,6 @@ func Dir(name string) string {
|
||||||
if modhost.ModulesDirOverride() != "" {
|
if modhost.ModulesDirOverride() != "" {
|
||||||
return preferred
|
return preferred
|
||||||
}
|
}
|
||||||
if beside := dirBesideExecutable(name); beside != "" {
|
|
||||||
return beside
|
|
||||||
}
|
|
||||||
root := repo.Root()
|
root := repo.Root()
|
||||||
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
|
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
|
||||||
return filepath.Join(root, "modules", name)
|
return filepath.Join(root, "modules", name)
|
||||||
|
|
@ -42,43 +38,6 @@ func Dir(name string) string {
|
||||||
return filepath.Join(root, "apps", "modules", name)
|
return filepath.Join(root, "apps", "modules", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
|
|
||||||
// <modDir>/.bin/<name>[.exe]
|
|
||||||
// <modDir>/.bin/<goos>-<goarch>/<name>[.exe]
|
|
||||||
func dirBesideExecutable(name string) string {
|
|
||||||
exe, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
|
||||||
exe = resolved
|
|
||||||
}
|
|
||||||
base := strings.TrimSuffix(filepath.Base(exe), ".exe")
|
|
||||||
if !strings.EqualFold(base, name) {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
binDir := filepath.Dir(exe)
|
|
||||||
candidates := []string{}
|
|
||||||
if strings.EqualFold(filepath.Base(binDir), ".bin") {
|
|
||||||
candidates = append(candidates, filepath.Dir(binDir))
|
|
||||||
}
|
|
||||||
parent := filepath.Dir(binDir)
|
|
||||||
if strings.EqualFold(filepath.Base(parent), ".bin") {
|
|
||||||
candidates = append(candidates, filepath.Dir(parent))
|
|
||||||
}
|
|
||||||
for _, dir := range candidates {
|
|
||||||
if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) {
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func fileExists(p string) bool {
|
|
||||||
st, err := os.Stat(p)
|
|
||||||
return err == nil && !st.IsDir()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Path returns the preferred values file path (module.yaml).
|
// Path returns the preferred values file path (module.yaml).
|
||||||
func Path(name string) string {
|
func Path(name string) string {
|
||||||
return filepath.Join(Dir(name), "module.yaml")
|
return filepath.Join(Dir(name), "module.yaml")
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ type Module struct {
|
||||||
Dir string // absolute path to modules/<name>
|
Dir string // absolute path to modules/<name>
|
||||||
}
|
}
|
||||||
|
|
||||||
// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
|
// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
|
||||||
func ModulesDir(root string) string {
|
func ModulesDir(root string) string {
|
||||||
return EffectiveModulesDir(root)
|
return EffectiveModulesDir(root)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,39 +9,9 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
|
|
||||||
// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
|
|
||||||
// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
|
|
||||||
// panel module.yaml when describe returns no channels.
|
|
||||||
func prepareModuleCmd(cmd *exec.Cmd) {
|
|
||||||
ov := ModulesDirOverride()
|
|
||||||
if ov == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
|
|
||||||
"STREAMD_MODULES_DIR="+ov)
|
|
||||||
}
|
|
||||||
|
|
||||||
func withoutEnvKeys(env []string, keys ...string) []string {
|
|
||||||
drop := map[string]struct{}{}
|
|
||||||
for _, k := range keys {
|
|
||||||
drop[strings.ToUpper(k)] = struct{}{}
|
|
||||||
}
|
|
||||||
out := make([]string, 0, len(env))
|
|
||||||
for _, e := range env {
|
|
||||||
key, _, _ := strings.Cut(e, "=")
|
|
||||||
if _, skip := drop[strings.ToUpper(key)]; skip {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, e)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run executes the module binary with args, inheriting stdout/stderr.
|
// Run executes the module binary with args, inheriting stdout/stderr.
|
||||||
func Run(bin string, args ...string) error {
|
func Run(bin string, args ...string) error {
|
||||||
cmd := exec.Command(bin, args...)
|
cmd := exec.Command(bin, args...)
|
||||||
prepareModuleCmd(cmd)
|
|
||||||
cmd.Stdout = os.Stdout
|
cmd.Stdout = os.Stdout
|
||||||
cmd.Stderr = os.Stderr
|
cmd.Stderr = os.Stderr
|
||||||
cmd.Stdin = os.Stdin
|
cmd.Stdin = os.Stdin
|
||||||
|
|
@ -54,7 +24,6 @@ func Run(bin string, args ...string) error {
|
||||||
// RunOutput executes the module binary and returns combined stdout.
|
// RunOutput executes the module binary and returns combined stdout.
|
||||||
func RunOutput(bin string, args ...string) (string, error) {
|
func RunOutput(bin string, args ...string) (string, error) {
|
||||||
cmd := exec.Command(bin, args...)
|
cmd := exec.Command(bin, args...)
|
||||||
prepareModuleCmd(cmd)
|
|
||||||
var stdout, stderr bytes.Buffer
|
var stdout, stderr bytes.Buffer
|
||||||
cmd.Stdout = &stdout
|
cmd.Stdout = &stdout
|
||||||
cmd.Stderr = &stderr
|
cmd.Stderr = &stderr
|
||||||
|
|
@ -105,9 +74,5 @@ func Load(root, name string) (Module, string, Describe, error) {
|
||||||
if d.Name == "" {
|
if d.Name == "" {
|
||||||
d.Name = m.Name
|
d.Name = m.Name
|
||||||
}
|
}
|
||||||
// Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
|
|
||||||
// exe-adjacent layout, leaving package empty (breaks transparent MITM —
|
|
||||||
// iptables then treats the listen port as the package name).
|
|
||||||
enrichDescribeFromYAML(&d, m.Dir)
|
|
||||||
return m, bin, d, nil
|
return m, bin, d, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
package modhost
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPrepareModuleCmdSetsEnv(t *testing.T) {
|
|
||||||
t.Cleanup(func() { _ = SetModulesDir("") })
|
|
||||||
ov := filepath.Join(t.TempDir(), "modules")
|
|
||||||
if err := os.MkdirAll(ov, 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := SetModulesDir(ov); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
cmd := exec.Command("true")
|
|
||||||
prepareModuleCmd(cmd)
|
|
||||||
found := false
|
|
||||||
for _, e := range cmd.Env {
|
|
||||||
if e == "STREAMD_MODULES_DIR="+ov {
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
// Package modhost discovers, builds, and runs external provider modules that
|
// Package modhost discovers, builds, and runs external provider modules that
|
||||||
// live under modules/<name>/ (Go source + module.yaml), outside streamd.
|
// live under modules/<name>/ (Go source + module.yaml), outside drm.exe.
|
||||||
package modhost
|
package modhost
|
||||||
|
|
||||||
import "streamd/capture"
|
import "drmdecryption/capture"
|
||||||
|
|
||||||
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
|
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
|
||||||
const ProtocolVersion = 1
|
const ProtocolVersion = 1
|
||||||
|
|
@ -22,16 +22,13 @@ type Describe struct {
|
||||||
KeyMode string `json:"key_mode"`
|
KeyMode string `json:"key_mode"`
|
||||||
ProxyBin string `json:"proxy_bin,omitempty"`
|
ProxyBin string `json:"proxy_bin,omitempty"`
|
||||||
CAHash string `json:"ca_hash,omitempty"`
|
CAHash string `json:"ca_hash,omitempty"`
|
||||||
TransparentMITM bool `json:"transparent_mitm"`
|
TransparentMITM bool `json:"transparent_mitm"`
|
||||||
MitmHosts []string `json:"mitm_hosts,omitempty"`
|
MitmHosts []string `json:"mitm_hosts,omitempty"`
|
||||||
Rewriter string `json:"rewriter,omitempty"`
|
Rewriter string `json:"rewriter,omitempty"`
|
||||||
Channels []Channel `json:"channels"`
|
Channels []Channel `json:"channels"`
|
||||||
Require []string `json:"require,omitempty"`
|
Require []string `json:"require,omitempty"`
|
||||||
Score capture.ScoreCfg `json:"score,omitempty"`
|
Score capture.ScoreCfg `json:"score,omitempty"`
|
||||||
// ChannelMPDPrefer maps channel id → URL substrings that must win Wait scoring.
|
HasCatalog bool `json:"has_catalog"`
|
||||||
ChannelMPDPrefer map[string][]string `json:"channel_mpd_prefer,omitempty"`
|
ValuesPath string `json:"values_path,omitempty"`
|
||||||
HasCatalog bool `json:"has_catalog"`
|
ValuesLoaded bool `json:"values_loaded"`
|
||||||
RequireWVD bool `json:"require_wvd,omitempty"`
|
|
||||||
ValuesPath string `json:"values_path,omitempty"`
|
|
||||||
ValuesLoaded bool `json:"values_loaded"`
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,11 +6,11 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/app"
|
"drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/mpd"
|
"drmdecryption/mpd"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RemoteApp implements app.App by calling an external module binary.
|
// RemoteApp implements app.App by calling an external module binary.
|
||||||
|
|
@ -82,8 +82,6 @@ func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
|
||||||
|
|
||||||
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
|
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
|
||||||
|
|
||||||
func (r *RemoteApp) RequireWVD() bool { return r.Desc.RequireWVD }
|
|
||||||
|
|
||||||
func (r *RemoteApp) MitmHosts() []string {
|
func (r *RemoteApp) MitmHosts() []string {
|
||||||
out := make([]string, 0, len(r.Desc.MitmHosts))
|
out := make([]string, 0, len(r.Desc.MitmHosts))
|
||||||
for _, h := range r.Desc.MitmHosts {
|
for _, h := range r.Desc.MitmHosts {
|
||||||
|
|
@ -95,28 +93,6 @@ func (r *RemoteApp) MitmHosts() []string {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *RemoteApp) CaptureHintsFor(channel string) capture.Hints {
|
|
||||||
h := r.CaptureHints()
|
|
||||||
if len(r.Desc.ChannelMPDPrefer) == 0 {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
id := strings.ToLower(strings.TrimSpace(channel))
|
|
||||||
if prefs, ok := r.Desc.ChannelMPDPrefer[id]; ok && len(prefs) > 0 {
|
|
||||||
h.PreferURLContains = append([]string{}, prefs...)
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
// Alias / label fallback: match prefer keys against known channel ids only.
|
|
||||||
for _, ch := range r.Desc.Channels {
|
|
||||||
if strings.EqualFold(ch.ID, id) || strings.EqualFold(ch.Label, id) {
|
|
||||||
if prefs, ok := r.Desc.ChannelMPDPrefer[ch.ID]; ok && len(prefs) > 0 {
|
|
||||||
h.PreferURLContains = append([]string{}, prefs...)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *RemoteApp) RewriterName() string {
|
func (r *RemoteApp) RewriterName() string {
|
||||||
if r.Desc.Rewriter == "" {
|
if r.Desc.Rewriter == "" {
|
||||||
return "none"
|
return "none"
|
||||||
|
|
@ -150,13 +126,11 @@ func (r *RemoteApp) ValuesPath() string {
|
||||||
|
|
||||||
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
|
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
|
||||||
var (
|
var (
|
||||||
_ app.App = (*RemoteApp)(nil)
|
_ app.App = (*RemoteApp)(nil)
|
||||||
_ app.TransparentMITM = (*RemoteApp)(nil)
|
_ app.TransparentMITM = (*RemoteApp)(nil)
|
||||||
_ app.RequireWVD = (*RemoteApp)(nil)
|
_ app.MitmHostList = (*RemoteApp)(nil)
|
||||||
_ app.MitmHostList = (*RemoteApp)(nil)
|
_ app.StreamDefaults = (*RemoteApp)(nil)
|
||||||
_ app.ChannelCaptureHints = (*RemoteApp)(nil)
|
_ app.Catalog = (*RemoteApp)(nil)
|
||||||
_ app.StreamDefaults = (*RemoteApp)(nil)
|
|
||||||
_ app.Catalog = (*RemoteApp)(nil)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *RemoteApp) VideoSelect() string { return "" }
|
func (r *RemoteApp) VideoSelect() string { return "" }
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,9 @@ package modhost
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
@ -14,7 +13,7 @@ var (
|
||||||
modulesDirOV string // absolute path override for the modules directory
|
modulesDirOV string // absolute path override for the modules directory
|
||||||
)
|
)
|
||||||
|
|
||||||
// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
|
// SetModulesDir overrides where providers are discovered (drm --modules-dir).
|
||||||
// Empty clears the override. Relative paths are resolved against the process cwd.
|
// Empty clears the override. Relative paths are resolved against the process cwd.
|
||||||
func SetModulesDir(dir string) error {
|
func SetModulesDir(dir string) error {
|
||||||
rootMu.Lock()
|
rootMu.Lock()
|
||||||
|
|
@ -38,45 +37,24 @@ func ModulesDirOverride() string {
|
||||||
return modulesDirOV
|
return modulesDirOV
|
||||||
}
|
}
|
||||||
|
|
||||||
// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR.
|
|
||||||
func envModulesDir() string {
|
|
||||||
v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR"))
|
|
||||||
if v == "" {
|
|
||||||
v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR"))
|
|
||||||
}
|
|
||||||
if v == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if abs, err := filepath.Abs(v); err == nil {
|
|
||||||
return abs
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
// EffectiveModulesDir is the directory that Discover/Open scan.
|
// EffectiveModulesDir is the directory that Discover/Open scan.
|
||||||
// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else <root>/modules.
|
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules.
|
||||||
// Module binaries read the env here directly so they honour the panel store even
|
|
||||||
// when they never call ApplyEnvModulesDir.
|
|
||||||
func EffectiveModulesDir(root string) string {
|
func EffectiveModulesDir(root string) string {
|
||||||
if ov := ModulesDirOverride(); ov != "" {
|
if ov := ModulesDirOverride(); ov != "" {
|
||||||
return ov
|
return ov
|
||||||
}
|
}
|
||||||
if v := envModulesDir(); v != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
if root == "" {
|
if root == "" {
|
||||||
root = repo.Root()
|
root = repo.Root()
|
||||||
}
|
}
|
||||||
return filepath.Join(root, "modules")
|
return filepath.Join(root, "modules")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
|
// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
|
||||||
// DRM_MODULES_DIR when no flag was set.
|
|
||||||
func ApplyEnvModulesDir() error {
|
func ApplyEnvModulesDir() error {
|
||||||
if ModulesDirOverride() != "" {
|
if ModulesDirOverride() != "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
v := envModulesDir()
|
v := os.Getenv("DRM_MODULES_DIR")
|
||||||
if v == "" {
|
if v == "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
package modhost
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestEffectiveModulesDirEnv(t *testing.T) {
|
|
||||||
t.Cleanup(func() {
|
|
||||||
_ = SetModulesDir("")
|
|
||||||
_ = os.Unsetenv("STREAMD_MODULES_DIR")
|
|
||||||
_ = os.Unsetenv("DRM_MODULES_DIR")
|
|
||||||
})
|
|
||||||
_ = SetModulesDir("")
|
|
||||||
_ = os.Unsetenv("STREAMD_MODULES_DIR")
|
|
||||||
_ = os.Unsetenv("DRM_MODULES_DIR")
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
t.Setenv("STREAMD_MODULES_DIR", dir)
|
|
||||||
got := EffectiveModulesDir("")
|
|
||||||
want, _ := filepath.Abs(dir)
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("env modules dir: got %q want %q", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
override := filepath.Join(t.TempDir(), "override")
|
|
||||||
if err := os.MkdirAll(override, 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := SetModulesDir(override); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
got = EffectiveModulesDir("")
|
|
||||||
want, _ = filepath.Abs(override)
|
|
||||||
if got != want {
|
|
||||||
t.Fatalf("flag overrides env: got %q want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
package modhost
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
// enrichDescribeFromYAML fills gaps left by older module binaries that do not
|
|
||||||
// load panel/agent module.yaml (empty package breaks transparent MITM).
|
|
||||||
func enrichDescribeFromYAML(d *Describe, modDir string) {
|
|
||||||
if d == nil || strings.TrimSpace(modDir) == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
|
|
||||||
if err != nil {
|
|
||||||
raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var doc struct {
|
|
||||||
Package string `yaml:"package"`
|
|
||||||
LicenseURL string `yaml:"license_url"`
|
|
||||||
KeyMode string `yaml:"key_mode"`
|
|
||||||
ProxyBin string `yaml:"proxy_bin"`
|
|
||||||
CAHash string `yaml:"ca_hash"`
|
|
||||||
TransparentMITM *bool `yaml:"transparent_mitm"`
|
|
||||||
RequireWVD *bool `yaml:"require_wvd"`
|
|
||||||
Rewriter string `yaml:"rewriter"`
|
|
||||||
Channels map[string]struct {
|
|
||||||
Label string `yaml:"label"`
|
|
||||||
} `yaml:"channels"`
|
|
||||||
}
|
|
||||||
if err := yaml.Unmarshal(raw, &doc); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
|
|
||||||
d.Package = strings.TrimSpace(doc.Package)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
|
|
||||||
d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
|
|
||||||
d.KeyMode = strings.TrimSpace(doc.KeyMode)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
|
|
||||||
d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
|
|
||||||
d.CAHash = strings.TrimSpace(doc.CAHash)
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
|
|
||||||
d.Rewriter = strings.TrimSpace(doc.Rewriter)
|
|
||||||
}
|
|
||||||
if !d.TransparentMITM && doc.TransparentMITM != nil {
|
|
||||||
d.TransparentMITM = *doc.TransparentMITM
|
|
||||||
}
|
|
||||||
if !d.RequireWVD && doc.RequireWVD != nil {
|
|
||||||
d.RequireWVD = *doc.RequireWVD
|
|
||||||
}
|
|
||||||
if len(d.Channels) == 0 && len(doc.Channels) > 0 {
|
|
||||||
for id, ch := range doc.Channels {
|
|
||||||
label := strings.TrimSpace(ch.Label)
|
|
||||||
if label == "" {
|
|
||||||
label = id
|
|
||||||
}
|
|
||||||
d.Channels = append(d.Channels, Channel{ID: id, Label: label})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !d.ValuesLoaded {
|
|
||||||
d.ValuesLoaded = true
|
|
||||||
d.ValuesPath = filepath.Join(modDir, "module.yaml")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -12,13 +12,13 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/app"
|
"drmdecryption/app"
|
||||||
"streamd/capture"
|
"drmdecryption/capture"
|
||||||
"streamd/proxy"
|
"drmdecryption/proxy"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
"streamd/session"
|
"drmdecryption/session"
|
||||||
"streamd/wvkey"
|
"drmdecryption/wvkey"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
|
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
|
||||||
|
|
@ -199,28 +199,21 @@ func Run(opt Options) (res Result, err error) {
|
||||||
|
|
||||||
proxyBin, caHash := resolveProxy(a, root)
|
proxyBin, caHash := resolveProxy(a, root)
|
||||||
hints := a.CaptureHints()
|
hints := a.CaptureHints()
|
||||||
if chHints, ok := a.(app.ChannelCaptureHints); ok && strings.TrimSpace(opt.Channel) != "" {
|
|
||||||
hints = chHints.CaptureHintsFor(opt.Channel)
|
|
||||||
}
|
|
||||||
useTProxy := false
|
useTProxy := false
|
||||||
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
||||||
useTProxy = true
|
useTProxy = true
|
||||||
}
|
}
|
||||||
pkgName := strings.TrimSpace(a.Package())
|
|
||||||
if useTProxy && pkgName == "" {
|
|
||||||
return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
if useTProxy {
|
if useTProxy {
|
||||||
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
||||||
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
||||||
proxy.ClearHTTPProxy(c)
|
proxy.ClearHTTPProxy(c)
|
||||||
remoteDir := "/data/local/tmp/capture/" + pkgName
|
remoteDir := "/data/local/tmp/capture/" + a.Package()
|
||||||
var mitmHosts []string
|
var mitmHosts []string
|
||||||
if mh, ok := a.(app.MitmHostList); ok {
|
if mh, ok := a.(app.MitmHostList); ok {
|
||||||
mitmHosts = mh.MitmHosts()
|
mitmHosts = mh.MitmHosts()
|
||||||
}
|
}
|
||||||
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
|
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||||
return res, fmt.Errorf("transparent MITM start: %w", err)
|
return res, fmt.Errorf("transparent MITM start: %w", err)
|
||||||
}
|
}
|
||||||
defer proxy.StopTransparent(c)
|
defer proxy.StopTransparent(c)
|
||||||
|
|
@ -242,6 +235,17 @@ func Run(opt Options) (res Result, err error) {
|
||||||
proxy.ReinjectCA(c, caHash)
|
proxy.ReinjectCA(c, caHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := a.Launch(c); err != nil {
|
||||||
|
return res, fmt.Errorf("launch: %w", err)
|
||||||
|
}
|
||||||
|
if !opt.NoAutoPlay {
|
||||||
|
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
||||||
|
return res, fmt.Errorf("auto-play: %w", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
||||||
|
}
|
||||||
|
|
||||||
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
|
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
|
||||||
serialTag := c.Serial
|
serialTag := c.Serial
|
||||||
if serialTag == "" {
|
if serialTag == "" {
|
||||||
|
|
@ -253,168 +257,80 @@ func Run(opt Options) (res Result, err error) {
|
||||||
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
||||||
defer close(stop)
|
defer close(stop)
|
||||||
|
|
||||||
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
|
||||||
if keyMode == "" || keyMode == "auto" {
|
|
||||||
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
|
||||||
}
|
|
||||||
needsKeys := keyMode != "none" && keyMode != "clear"
|
|
||||||
|
|
||||||
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
|
|
||||||
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
|
|
||||||
attempts := 1
|
|
||||||
waitPer := opt.Wait
|
|
||||||
if needsKeys {
|
|
||||||
attempts = 3
|
|
||||||
waitPer = 90 * time.Second
|
|
||||||
if opt.Wait > 0 && opt.Wait < waitPer {
|
|
||||||
waitPer = opt.Wait
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
need := hints.Require
|
need := hints.Require
|
||||||
if len(need) == 0 {
|
if len(need) == 0 {
|
||||||
need = []string{"manifest"}
|
need = []string{"manifest"}
|
||||||
}
|
}
|
||||||
|
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
|
||||||
var (
|
fmt.Println(" watch:", localLog)
|
||||||
capData capture.Data
|
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
|
||||||
licenseURL string
|
if err != nil {
|
||||||
mpdURL string
|
return res, err
|
||||||
key string
|
}
|
||||||
lastErr error
|
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
|
||||||
)
|
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||||
|
if keyMode == "" || keyMode == "auto" {
|
||||||
for attempt := 1; attempt <= attempts; attempt++ {
|
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||||
if attempt > 1 {
|
}
|
||||||
fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
|
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
||||||
c.ForceStop(a.Package())
|
// Skip for clear/MPD-only apps (KeyMode none).
|
||||||
time.Sleep(800 * time.Millisecond)
|
if keyMode != "none" && keyMode != "clear" {
|
||||||
|
if strings.TrimSpace(capData.Get("pssh")) == "" && strings.TrimSpace(capData.Get("mpd")) != "" {
|
||||||
|
if pssh, err := extractHLSPSSH(capData.Get("mpd")); err == nil && pssh != "" {
|
||||||
|
capData["pssh"] = pssh
|
||||||
|
} else if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
|
mpdURL := strings.TrimSpace(capData.Get("mpd"))
|
||||||
_ = os.WriteFile(localLog, nil, 0o644)
|
// Console: always surface the MPD we will use (BBC clear streams only need this).
|
||||||
_ = os.Remove(localCap)
|
fmt.Println()
|
||||||
|
fmt.Println("========== MPD ==========")
|
||||||
if err := a.Launch(c); err != nil {
|
if mpdURL != "" {
|
||||||
lastErr = fmt.Errorf("launch: %w", err)
|
fmt.Println(mpdURL)
|
||||||
|
} else {
|
||||||
|
fmt.Println("(none)")
|
||||||
|
}
|
||||||
|
fmt.Println("=========================")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("[+] Capture:")
|
||||||
|
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh"} {
|
||||||
|
v := capData.Get(k)
|
||||||
|
if k == "license_url" {
|
||||||
|
v = first(v, licenseURL)
|
||||||
|
}
|
||||||
|
if v == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !opt.NoAutoPlay {
|
label := k
|
||||||
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
if k == "license_url" {
|
||||||
lastErr = fmt.Errorf("auto-play: %w", err)
|
label = "license"
|
||||||
c.ForceStop(a.Package())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
|
||||||
}
|
}
|
||||||
|
fmt.Println(" ", label+":", trim(v, 120))
|
||||||
|
}
|
||||||
|
|
||||||
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
|
key := ""
|
||||||
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
|
if keyMode == "none" || keyMode == "clear" {
|
||||||
fmt.Println(" watch:", localLog)
|
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
||||||
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
|
} else {
|
||||||
if err != nil {
|
var kerr error
|
||||||
lastErr = err
|
key, kerr = fetchKey(opt, root, capData, licenseURL)
|
||||||
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
capData = cap
|
|
||||||
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
|
|
||||||
|
|
||||||
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
|
||||||
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
|
||||||
if needsKeys {
|
|
||||||
enrichWidevinePSSH(capData)
|
|
||||||
}
|
|
||||||
|
|
||||||
mpdURL = strings.TrimSpace(capData.Get("mpd"))
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("========== MPD ==========")
|
|
||||||
if mpdURL != "" {
|
|
||||||
fmt.Println(mpdURL)
|
|
||||||
} else {
|
|
||||||
fmt.Println("(none)")
|
|
||||||
}
|
|
||||||
fmt.Println("=========================")
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("[+] Capture:")
|
|
||||||
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
|
|
||||||
v := capData.Get(k)
|
|
||||||
if k == "license_url" {
|
|
||||||
v = first(v, licenseURL)
|
|
||||||
}
|
|
||||||
if v == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
label := k
|
|
||||||
switch k {
|
|
||||||
case "license_url":
|
|
||||||
label = "license"
|
|
||||||
case "license_body":
|
|
||||||
label = "license_body"
|
|
||||||
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
|
|
||||||
}
|
|
||||||
fmt.Println(" ", label+":", trim(v, 120))
|
|
||||||
}
|
|
||||||
|
|
||||||
if !needsKeys {
|
|
||||||
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
|
||||||
lastErr = nil
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
k, kerr := fetchKey(opt, root, capData, licenseURL)
|
|
||||||
if kerr != nil {
|
if kerr != nil {
|
||||||
lastErr = kerr
|
return res, kerr
|
||||||
// Missing --wvd on a manual grab-all can soft-save MPD-only; agents
|
|
||||||
// always pass WVD so this path is for interactive capture only.
|
|
||||||
softOK := strings.Contains(kerr.Error(), "requires --wvd")
|
|
||||||
if softOK {
|
|
||||||
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
|
|
||||||
key = ""
|
|
||||||
lastErr = nil
|
|
||||||
break
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
|
|
||||||
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
|
|
||||||
c.ForceStop(a.Package())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
key = k
|
|
||||||
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
|
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
|
||||||
lastErr = nil
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if lastErr != nil {
|
|
||||||
if needsKeys {
|
|
||||||
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
|
|
||||||
}
|
|
||||||
return res, lastErr
|
|
||||||
}
|
|
||||||
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
|
|
||||||
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sess := session.Session{
|
sess := session.Session{
|
||||||
Channel: opt.Channel,
|
Channel: opt.Channel,
|
||||||
PSSH: capData.Get("pssh"),
|
PSSH: capData.Get("pssh"),
|
||||||
Auth: capData.Get("auth"),
|
Auth: capData.Get("auth"),
|
||||||
PID: capData.Get("pid"),
|
PID: capData.Get("pid"),
|
||||||
Key: key,
|
Key: key,
|
||||||
MPD: mpdURL,
|
MPD: mpdURL,
|
||||||
LicenseURL: licenseURL,
|
LicenseURL: licenseURL,
|
||||||
LicenseBody: capData.Get("license_body"),
|
|
||||||
}
|
}
|
||||||
path, err := session.Write(root, a.Name(), sess)
|
path, err := session.Write(root, a.Name(), sess)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -431,62 +347,6 @@ func Run(opt Options) (res Result, err error) {
|
||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func enrichWidevinePSSH(capData capture.Data) {
|
|
||||||
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
|
|
||||||
curPSSH := strings.TrimSpace(capData.Get("pssh"))
|
|
||||||
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
|
|
||||||
if !needPSSH || mpdForPSSH == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
|
|
||||||
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
|
|
||||||
if curPSSH != "" && curPSSH != pssh {
|
|
||||||
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
|
|
||||||
}
|
|
||||||
capData["pssh"] = pssh
|
|
||||||
} else if err != nil && curPSSH == "" {
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if curPSSH == "" {
|
|
||||||
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
|
|
||||||
capData["pssh"] = pssh
|
|
||||||
} else if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func looksLikeKey(raw string) bool {
|
|
||||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
|
||||||
for _, line := range strings.Split(raw, "\n") {
|
|
||||||
line = strings.TrimSpace(line)
|
|
||||||
if line == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
kid, k, ok := strings.Cut(line, ":")
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func hexDigits(s string) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for _, r := range s {
|
|
||||||
switch {
|
|
||||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
|
||||||
b.WriteRune(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
|
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
|
||||||
func ClearProxyLater(c *adb.Client) {
|
func ClearProxyLater(c *adb.Client) {
|
||||||
proxy.ClearHTTPProxy(c)
|
proxy.ClearHTTPProxy(c)
|
||||||
|
|
@ -517,25 +377,22 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
||||||
if strings.TrimSpace(opt.WVD) == "" {
|
if strings.TrimSpace(opt.WVD) == "" {
|
||||||
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
||||||
}
|
}
|
||||||
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
|
py := opt.Python
|
||||||
rt, err := wvkey.EnsureRuntime(root)
|
if py == "" {
|
||||||
if err != nil {
|
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
|
||||||
return "", err
|
if _, err := os.Stat(py); err != nil {
|
||||||
}
|
py = filepath.Join(root, ".venv", "bin", "python")
|
||||||
py := rt.Python
|
}
|
||||||
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
|
|
||||||
py = p
|
|
||||||
}
|
}
|
||||||
wopt := wvkey.Options{
|
wopt := wvkey.Options{
|
||||||
Python: py,
|
Python: py,
|
||||||
Script: rt.Script,
|
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
|
||||||
WVD: opt.WVD,
|
WVD: opt.WVD,
|
||||||
PSSH: cap.Get("pssh"),
|
PSSH: cap.Get("pssh"),
|
||||||
Auth: cap.Get("auth"),
|
Auth: cap.Get("auth"),
|
||||||
PID: cap.Get("pid"),
|
PID: cap.Get("pid"),
|
||||||
LicenseURL: licenseURL,
|
LicenseURL: licenseURL,
|
||||||
UserAgent: opt.UserAgent,
|
UserAgent: opt.UserAgent,
|
||||||
WrapJSON: cap.Get("license_body"),
|
|
||||||
}
|
}
|
||||||
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||||
if mode == "" || mode == "auto" {
|
if mode == "" || mode == "auto" {
|
||||||
|
|
@ -546,11 +403,6 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// RedBee / wrapped JSON: if the phone posted a license body, prefer wrap
|
|
||||||
// even when the module still says raw (migration safety).
|
|
||||||
if mode == "raw" && strings.TrimSpace(wopt.WrapJSON) != "" {
|
|
||||||
mode = "wrap"
|
|
||||||
}
|
|
||||||
switch mode {
|
switch mode {
|
||||||
case "raw":
|
case "raw":
|
||||||
// Brightcove returns multiple CONTENT keys; NRE needs all of them.
|
// Brightcove returns multiple CONTENT keys; NRE needs all of them.
|
||||||
|
|
@ -559,22 +411,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return strings.Join(keys, "\n"), nil
|
return strings.Join(keys, "\n"), nil
|
||||||
case "wrap":
|
|
||||||
keys, err := wvkey.FetchWrapAll(wopt)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return strings.Join(keys, "\n"), nil
|
|
||||||
default:
|
default:
|
||||||
return wvkey.Fetch(wopt)
|
return wvkey.Fetch(wopt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func fileExistsPath(path string) bool {
|
|
||||||
st, err := os.Stat(path)
|
|
||||||
return err == nil && !st.IsDir()
|
|
||||||
}
|
|
||||||
|
|
||||||
func first(vals ...string) string {
|
func first(vals ...string) string {
|
||||||
for _, v := range vals {
|
for _, v := range vals {
|
||||||
if strings.TrimSpace(v) != "" {
|
if strings.TrimSpace(v) != "" {
|
||||||
|
|
@ -612,62 +453,6 @@ func extractHLSPSSH(masterURL string) (string, error) {
|
||||||
return "", fmt.Errorf("no Widevine PSSH in HLS master")
|
return "", fmt.Errorf("no Widevine PSSH in HLS master")
|
||||||
}
|
}
|
||||||
|
|
||||||
// PlayReady system id fragment inside a base64 PSSH box.
|
|
||||||
const playReadyPSSHFrag = "AAAAAmgTweZhAQoarkuZb4IhflQ"
|
|
||||||
|
|
||||||
// Widevine system id fragment inside a base64 PSSH box.
|
|
||||||
const widevinePSSHFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q"
|
|
||||||
|
|
||||||
func isPlayReadyPSSH(b64 string) bool {
|
|
||||||
return strings.Contains(b64, playReadyPSSHFrag) && !strings.Contains(b64, widevinePSSHFrag)
|
|
||||||
}
|
|
||||||
|
|
||||||
func extractWidevinePSSHFromMPD(mpdURL string) (string, error) {
|
|
||||||
resp, err := http.Get(mpdURL)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != 200 {
|
|
||||||
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
mpd := string(body)
|
|
||||||
lower := strings.ToLower(mpd)
|
|
||||||
const (
|
|
||||||
wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
|
|
||||||
openTag = "<cenc:pssh"
|
|
||||||
closeTag = "</cenc:pssh>"
|
|
||||||
)
|
|
||||||
searchFrom := 0
|
|
||||||
for {
|
|
||||||
i := strings.Index(lower[searchFrom:], openTag)
|
|
||||||
if i < 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
i += searchFrom
|
|
||||||
j := strings.Index(mpd[i:], ">")
|
|
||||||
k := strings.Index(lower[i:], closeTag)
|
|
||||||
if j < 0 || k < 0 || k <= j {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
val := strings.TrimSpace(mpd[i+j+1 : i+k])
|
|
||||||
windowStart := i - 400
|
|
||||||
if windowStart < 0 {
|
|
||||||
windowStart = 0
|
|
||||||
}
|
|
||||||
window := lower[windowStart : i+j]
|
|
||||||
if strings.Contains(window, wvUUID) || strings.Contains(val, widevinePSSHFrag) {
|
|
||||||
return val, nil
|
|
||||||
}
|
|
||||||
searchFrom = i + k + len(closeTag)
|
|
||||||
}
|
|
||||||
return "", fmt.Errorf("no Widevine cenc:pssh in MPD")
|
|
||||||
}
|
|
||||||
|
|
||||||
func trim(s string, n int) string {
|
func trim(s string, n int) string {
|
||||||
if len(s) <= n {
|
if len(s) <= n {
|
||||||
return s
|
return s
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,15 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed embedded/tproxy_iptables.sh
|
//go:embed embedded/tproxy_iptables.sh
|
||||||
var embeddedTProxyScript []byte
|
var embeddedTProxyScript []byte
|
||||||
|
|
||||||
// ensureTProxyScript pushes the iptables helper to the phone.
|
// ensureTProxyScript pushes the iptables helper to the phone.
|
||||||
// Prefers the source-tree copy; falls back to the copy embedded in streamd
|
// Prefers the source-tree copy; falls back to the copy embedded in drm.exe
|
||||||
// so a portable release zip does not need apps/proxy/device/.
|
// so a portable release zip does not need apps/proxy/device/.
|
||||||
func ensureTProxyScript(c *adb.Client) error {
|
func ensureTProxyScript(c *adb.Client) error {
|
||||||
candidates := []string{
|
candidates := []string{
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -225,7 +225,7 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// FindLocalBin returns the on-device MITM binary.
|
// FindLocalBin returns the on-device MITM binary.
|
||||||
// Search order: next to this streamd binary (release zip layout), then under the repo.
|
// Search order: next to this drm.exe (release zip layout), then under the repo.
|
||||||
func FindLocalBin(root string) string {
|
func FindLocalBin(root string) string {
|
||||||
if root == "" {
|
if root == "" {
|
||||||
root = repo.Root()
|
root = repo.Root()
|
||||||
|
|
@ -322,11 +322,11 @@ func generateMITMCA(certPath, keyPath string) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
|
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
|
||||||
cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
|
cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
|
||||||
tmpl := &x509.Certificate{
|
tmpl := &x509.Certificate{
|
||||||
SerialNumber: serial,
|
SerialNumber: serial,
|
||||||
Subject: pkix.Name{
|
Subject: pkix.Name{
|
||||||
Organization: []string{"Streamd MITM CA"},
|
Organization: []string{"Null DRM MITM CA"},
|
||||||
CommonName: cn,
|
CommonName: cn,
|
||||||
},
|
},
|
||||||
NotBefore: time.Now().Add(-time.Hour),
|
NotBefore: time.Now().Add(-time.Hour),
|
||||||
|
|
@ -481,14 +481,10 @@ const (
|
||||||
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
||||||
// mode otherwise only MITMs open.live.bbc.co.uk.
|
// mode otherwise only MITMs open.live.bbc.co.uk.
|
||||||
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
|
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
|
||||||
pkg = strings.TrimSpace(pkg)
|
|
||||||
if pkg == "" {
|
|
||||||
return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
|
|
||||||
}
|
|
||||||
if port == "" {
|
if port == "" {
|
||||||
port = "8080"
|
port = "8080"
|
||||||
}
|
}
|
||||||
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
|
if remoteDir == "" {
|
||||||
remoteDir = RemoteCaptureRoot + "/" + pkg
|
remoteDir = RemoteCaptureRoot + "/" + pkg
|
||||||
}
|
}
|
||||||
stopProxy(c)
|
stopProxy(c)
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import (
|
||||||
//
|
//
|
||||||
// Search order:
|
// Search order:
|
||||||
// 1. Walk up from the current working directory
|
// 1. Walk up from the current working directory
|
||||||
// 2. Walk up from streamd (if the exe lives in bin/, start at the parent)
|
// 2. Walk up from drm.exe (if the exe lives in bin/, start at the parent)
|
||||||
func Root() string {
|
func Root() string {
|
||||||
if root := findRoot(wd()); root != "" {
|
if root := findRoot(wd()); root != "" {
|
||||||
return root
|
return root
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,6 @@ type Session struct {
|
||||||
KeyHex string `json:"key_hex,omitempty"`
|
KeyHex string `json:"key_hex,omitempty"`
|
||||||
MPD string `json:"mpd,omitempty"`
|
MPD string `json:"mpd,omitempty"`
|
||||||
LicenseURL string `json:"license_url,omitempty"`
|
LicenseURL string `json:"license_url,omitempty"`
|
||||||
// LicenseBody is the phone's JSON license POST (RedBee wrap). Used to
|
|
||||||
// re-issue with a local CDM challenge.
|
|
||||||
LicenseBody string `json:"license_body,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write creates outputs/<app>/<stamp>/session.json (+ field txt files + latest).
|
// Write creates outputs/<app>/<stamp>/session.json (+ field txt files + latest).
|
||||||
|
|
@ -54,12 +51,11 @@ func Write(root, app string, s Session) (string, error) {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
fields := map[string]string{
|
fields := map[string]string{
|
||||||
"pssh": s.PSSH,
|
"pssh": s.PSSH,
|
||||||
"auth": s.Auth,
|
"auth": s.Auth,
|
||||||
"pid": s.PID,
|
"pid": s.PID,
|
||||||
"key": s.Key,
|
"key": s.Key,
|
||||||
"mpd": s.MPD,
|
"mpd": s.MPD,
|
||||||
"license_body": s.LicenseBody,
|
|
||||||
}
|
}
|
||||||
for name, val := range fields {
|
for name, val := range fields {
|
||||||
if val == "" {
|
if val == "" {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pick selects among several matching nodes.
|
// Pick selects among several matching nodes.
|
||||||
|
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
package wvkey
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
|
|
||||||
type Runtime struct {
|
|
||||||
Python string
|
|
||||||
Script string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScriptPath returns <root>/apps/wvkey/wvkey.py.
|
|
||||||
func ScriptPath(root string) string {
|
|
||||||
return filepath.Join(root, "apps", "wvkey", "wvkey.py")
|
|
||||||
}
|
|
||||||
|
|
||||||
// VenvPython returns the platform venv interpreter under root, if present.
|
|
||||||
func VenvPython(root string) string {
|
|
||||||
candidates := []string{
|
|
||||||
filepath.Join(root, ".venv", "Scripts", "python.exe"),
|
|
||||||
filepath.Join(root, ".venv", "bin", "python"),
|
|
||||||
filepath.Join(root, ".venv", "bin", "python3"),
|
|
||||||
}
|
|
||||||
for _, c := range candidates {
|
|
||||||
if fileExists(c) {
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnsureRuntime makes sure wvkey.py exists and a usable Python with
|
|
||||||
// pywidevine is available under root (creating .venv when needed).
|
|
||||||
// Works on Windows, Linux, and macOS.
|
|
||||||
func EnsureRuntime(root string) (Runtime, error) {
|
|
||||||
var zero Runtime
|
|
||||||
if root == "" {
|
|
||||||
return zero, fmt.Errorf("wvkey: install root required")
|
|
||||||
}
|
|
||||||
script := ScriptPath(root)
|
|
||||||
if !fileExists(script) {
|
|
||||||
return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
|
|
||||||
}
|
|
||||||
req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
|
|
||||||
|
|
||||||
if py := VenvPython(root); py != "" {
|
|
||||||
if hasPywidevine(py) {
|
|
||||||
return Runtime{Python: py, Script: script}, nil
|
|
||||||
}
|
|
||||||
if err := pipInstall(py, req); err != nil {
|
|
||||||
return zero, err
|
|
||||||
}
|
|
||||||
if !hasPywidevine(py) {
|
|
||||||
return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
|
|
||||||
}
|
|
||||||
return Runtime{Python: py, Script: script}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
base, err := findSystemPython()
|
|
||||||
if err != nil {
|
|
||||||
return zero, err
|
|
||||||
}
|
|
||||||
venvDir := filepath.Join(root, ".venv")
|
|
||||||
fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
|
|
||||||
if err := createVenv(base, venvDir); err != nil {
|
|
||||||
return zero, err
|
|
||||||
}
|
|
||||||
py := VenvPython(root)
|
|
||||||
if py == "" {
|
|
||||||
return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
|
|
||||||
}
|
|
||||||
if err := pipInstall(py, req); err != nil {
|
|
||||||
return zero, err
|
|
||||||
}
|
|
||||||
if !hasPywidevine(py) {
|
|
||||||
return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
|
|
||||||
return Runtime{Python: py, Script: script}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// FindPython prefers an existing install-root venv, then PATH helpers.
|
|
||||||
func FindPython(root string) string {
|
|
||||||
if root != "" {
|
|
||||||
if py := VenvPython(root); py != "" {
|
|
||||||
return py
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return findPython()
|
|
||||||
}
|
|
||||||
|
|
||||||
func fileExists(path string) bool {
|
|
||||||
st, err := os.Stat(path)
|
|
||||||
return err == nil && !st.IsDir()
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasPywidevine(py string) bool {
|
|
||||||
cmd := exec.Command(py, "-c", "import pywidevine")
|
|
||||||
return cmd.Run() == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func pipInstall(py, requirements string) error {
|
|
||||||
if !fileExists(requirements) {
|
|
||||||
return fmt.Errorf("wvkey: requirements missing at %s", requirements)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
|
|
||||||
cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func createVenv(basePython, venvDir string) error {
|
|
||||||
cmd := exec.Command(basePython, "-m", "venv", venvDir)
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func findSystemPython() (string, error) {
|
|
||||||
var names []string
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "windows":
|
|
||||||
// Prefer the py launcher (real install) over the Store stub named "python".
|
|
||||||
names = []string{"py", "python3", "python"}
|
|
||||||
default:
|
|
||||||
names = []string{"python3", "python"}
|
|
||||||
}
|
|
||||||
for _, name := range names {
|
|
||||||
if name == "py" {
|
|
||||||
// `py -3` on Windows
|
|
||||||
if p, err := exec.LookPath("py"); err == nil {
|
|
||||||
cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
|
|
||||||
out, err := cmd.Output()
|
|
||||||
if err == nil {
|
|
||||||
exe := strings.TrimSpace(string(out))
|
|
||||||
if fileExists(exe) {
|
|
||||||
return exe, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if p, err := exec.LookPath(name); err == nil {
|
|
||||||
// Skip the WindowsApps Store alias stub when it cannot run -m venv.
|
|
||||||
if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
|
|
||||||
cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
|
|
||||||
out, err := cmd.Output()
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
exe := strings.TrimSpace(string(out))
|
|
||||||
if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return exe, nil
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
|
|
||||||
}
|
|
||||||
|
|
@ -19,13 +19,11 @@ type Options struct {
|
||||||
PID string
|
PID string
|
||||||
LicenseURL string
|
LicenseURL string
|
||||||
UserAgent string
|
UserAgent string
|
||||||
// WrapJSON is a captured phone license POST body (RedBee / wrapped Widevine).
|
|
||||||
WrapJSON string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line.
|
// Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line.
|
||||||
func Fetch(opt Options) (string, error) {
|
func Fetch(opt Options) (string, error) {
|
||||||
lines, err := run(opt, "modulardrm", false)
|
lines, err := run(opt, false, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
@ -37,7 +35,7 @@ func Fetch(opt Options) (string, error) {
|
||||||
|
|
||||||
// FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license).
|
// FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license).
|
||||||
func FetchRaw(opt Options) (string, error) {
|
func FetchRaw(opt Options) (string, error) {
|
||||||
lines, err := run(opt, "raw", false)
|
lines, err := run(opt, true, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
@ -49,30 +47,18 @@ func FetchRaw(opt Options) (string, error) {
|
||||||
|
|
||||||
// FetchRawAll returns every CONTENT key from a raw license response.
|
// FetchRawAll returns every CONTENT key from a raw license response.
|
||||||
func FetchRawAll(opt Options) ([]string, error) {
|
func FetchRawAll(opt Options) ([]string, error) {
|
||||||
return run(opt, "raw", true)
|
return run(opt, true, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FetchWrapAll re-POSTs a captured JSON license body with a local CDM challenge.
|
func run(opt Options, raw, all bool) ([]string, error) {
|
||||||
func FetchWrapAll(opt Options) ([]string, error) {
|
py := opt.Python
|
||||||
return run(opt, "wrap", true)
|
if py == "" {
|
||||||
}
|
py = findPython()
|
||||||
|
}
|
||||||
func run(opt Options, mode string, all bool) ([]string, error) {
|
|
||||||
py := resolvePython(opt.Python)
|
|
||||||
script := opt.Script
|
script := opt.Script
|
||||||
if script == "" {
|
if script == "" {
|
||||||
return nil, fmt.Errorf("wvkey script path required")
|
return nil, fmt.Errorf("wvkey script path required")
|
||||||
}
|
}
|
||||||
if !fileExists(script) {
|
|
||||||
return nil, fmt.Errorf("wvkey script not found: %s", script)
|
|
||||||
}
|
|
||||||
if !fileExists(py) {
|
|
||||||
// Bare names like "python3" are OK via LookPath inside resolvePython;
|
|
||||||
// absolute/relative paths must exist.
|
|
||||||
if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
|
|
||||||
return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(opt.WVD) == "" {
|
if strings.TrimSpace(opt.WVD) == "" {
|
||||||
return nil, fmt.Errorf("wvkey --wvd path required")
|
return nil, fmt.Errorf("wvkey --wvd path required")
|
||||||
}
|
}
|
||||||
|
|
@ -87,19 +73,12 @@ func run(opt Options, mode string, all bool) ([]string, error) {
|
||||||
"--wvd", opt.WVD,
|
"--wvd", opt.WVD,
|
||||||
"--pssh", opt.PSSH,
|
"--pssh", opt.PSSH,
|
||||||
"--license-url", opt.LicenseURL,
|
"--license-url", opt.LicenseURL,
|
||||||
"--mode", mode,
|
|
||||||
"--quiet",
|
"--quiet",
|
||||||
}
|
}
|
||||||
switch mode {
|
if raw {
|
||||||
case "raw":
|
args = append(args, "--mode", "raw")
|
||||||
// no extra fields
|
} else {
|
||||||
case "wrap":
|
args = append(args, "--mode", "modulardrm", "--auth", opt.Auth, "--pid", opt.PID)
|
||||||
if strings.TrimSpace(opt.WrapJSON) == "" {
|
|
||||||
return nil, fmt.Errorf("wvkey wrap mode requires a captured license_body from the phone (playback must start so RedBee gets a token)")
|
|
||||||
}
|
|
||||||
args = append(args, "--wrap-json", opt.WrapJSON)
|
|
||||||
default:
|
|
||||||
args = append(args, "--auth", opt.Auth, "--pid", opt.PID)
|
|
||||||
}
|
}
|
||||||
if all {
|
if all {
|
||||||
args = append(args, "--all")
|
args = append(args, "--all")
|
||||||
|
|
@ -127,30 +106,12 @@ func run(opt Options, mode string, all bool) ([]string, error) {
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolvePython uses an explicit path only when the file exists; otherwise
|
|
||||||
// discovers a usable interpreter. Passing a missing absolute path used to make
|
|
||||||
// exec fail with a confusing "not found in %PATH%" on Windows.
|
|
||||||
func resolvePython(explicit string) string {
|
|
||||||
if strings.TrimSpace(explicit) != "" {
|
|
||||||
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
|
|
||||||
return explicit
|
|
||||||
}
|
|
||||||
if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
|
|
||||||
if p, err := exec.LookPath(explicit); err == nil {
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return findPython()
|
|
||||||
}
|
|
||||||
|
|
||||||
func findPython() string {
|
func findPython() string {
|
||||||
candidates := []string{
|
candidates := []string{
|
||||||
filepath.Join(".venv", "Scripts", "python.exe"),
|
filepath.Join(".venv", "Scripts", "python.exe"),
|
||||||
filepath.Join(".venv", "bin", "python"),
|
filepath.Join(".venv", "bin", "python"),
|
||||||
"python3",
|
"python3",
|
||||||
"python",
|
"python",
|
||||||
"py",
|
|
||||||
}
|
}
|
||||||
for _, c := range candidates {
|
for _, c := range candidates {
|
||||||
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
apps/proxy/
|
apps/proxy/
|
||||||
proxyctlcmd/ host CLI, hosted by bin/streamd as `streamd proxy`
|
proxyctlcmd/ host CLI, hosted by bin/drm as `drm proxy`
|
||||||
device/ linux/arm64 MITM source (module: appproxy)
|
device/ linux/arm64 MITM source (module: appproxy)
|
||||||
rteproxy-ca.crt MITM CA (subject hash 6c3578b4)
|
rteproxy-ca.crt MITM CA (subject hash 6c3578b4)
|
||||||
```
|
```
|
||||||
|
|
@ -17,8 +17,8 @@ working.
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go -C apps/cli build -o ../../bin/streamd . # host CLI
|
go -C apps/cli build -o ../../bin/drm . # host CLI
|
||||||
./bin/streamd proxy build # cross-compile the device binary
|
./bin/drm proxy build # cross-compile the device binary
|
||||||
```
|
```
|
||||||
|
|
||||||
`proxy build` compiles `device/` for linux/arm64 into
|
`proxy build` compiles `device/` for linux/arm64 into
|
||||||
|
|
@ -28,20 +28,20 @@ go -C apps/cli build -o ../../bin/streamd . # host CLI
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# trust the MITM CA (needs Magisk; mounts into the system store)
|
# trust the MITM CA (needs Magisk; mounts into the system store)
|
||||||
./bin/streamd proxy install-ca --reinject
|
./bin/drm proxy install-ca --reinject
|
||||||
./bin/streamd proxy reinject-ca # mount only, CA already pushed
|
./bin/drm proxy reinject-ca # mount only, CA already pushed
|
||||||
|
|
||||||
# structured capture proxy
|
# structured capture proxy
|
||||||
./bin/streamd proxy start --install-ca --reinject
|
./bin/drm proxy start --install-ca --reinject
|
||||||
./bin/streamd proxy stop
|
./bin/drm proxy stop
|
||||||
|
|
||||||
# record everything while you explore an unknown app
|
# record everything while you explore an unknown app
|
||||||
./bin/streamd proxy discover --install-ca --reinject
|
./bin/drm proxy discover --install-ca --reinject
|
||||||
./bin/streamd proxy discover --force-stop <package> # so it inherits the CA mount
|
./bin/drm proxy discover --force-stop <package> # so it inherits the CA mount
|
||||||
|
|
||||||
# pull artifacts without re-running, and release the phone
|
# pull artifacts without re-running, and release the phone
|
||||||
./bin/streamd proxy pull
|
./bin/drm proxy pull
|
||||||
./bin/streamd proxy clear-proxy
|
./bin/drm proxy clear-proxy
|
||||||
```
|
```
|
||||||
|
|
||||||
Always clear the proxy when done, or the phone keeps pointing at a dead listener.
|
Always clear the proxy when done, or the phone keeps pointing at a dead listener.
|
||||||
|
|
@ -53,7 +53,7 @@ phone can stay on NordVPN UK; nothing sets `http_proxy`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# leave UK VPN connected on the phone, then:
|
# leave UK VPN connected on the phone, then:
|
||||||
./bin/streamd proxy transparent --package bbc.iplayer.android --reinject
|
./bin/drm proxy transparent --package bbc.iplayer.android --reinject
|
||||||
# open the app / play — Ctrl+C stops iptables and pulls files
|
# open the app / play — Ctrl+C stops iptables and pulls files
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -75,7 +75,7 @@ Force-stop the target app once after CA reinject so it inherits the Magisk CA mo
|
||||||
|
|
||||||
The device binary cannot read an app module's values file, so a module's
|
The device binary cannot read an app module's values file, so a module's
|
||||||
manifest-scoring hosts are passed to it as flags (`--match`, `--score-host`,
|
manifest-scoring hosts are passed to it as flags (`--match`, `--score-host`,
|
||||||
`--score-deny`). `streamd capture` does this automatically.
|
`--score-deny`). `drm capture` does this automatically.
|
||||||
|
|
||||||
## Artifacts
|
## Artifacts
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -44,11 +44,8 @@ type capture struct {
|
||||||
LicenseURL string `json:"license_url,omitempty"`
|
LicenseURL string `json:"license_url,omitempty"`
|
||||||
Auth string `json:"auth,omitempty"`
|
Auth string `json:"auth,omitempty"`
|
||||||
PID string `json:"pid,omitempty"`
|
PID string `json:"pid,omitempty"`
|
||||||
// LicenseBody is the raw JSON POST body from the phone's license request
|
|
||||||
// (RedBee / wrapped Widevine). Used to re-issue with a local CDM challenge.
|
|
||||||
LicenseBody string `json:"license_body,omitempty"`
|
|
||||||
UpdatedAt string `json:"updated_at,omitempty"`
|
UpdatedAt string `json:"updated_at,omitempty"`
|
||||||
PSSH string `json:"pssh,omitempty"` // Widevine cenc:pssh from an MPD body
|
PSSH string `json:"pssh,omitempty"` // first short Widevine PSSH seen in an MPD body
|
||||||
}
|
}
|
||||||
|
|
||||||
type licenseBody struct {
|
type licenseBody struct {
|
||||||
|
|
@ -327,7 +324,6 @@ func main() {
|
||||||
if json.Unmarshal(body, &lb) == nil {
|
if json.Unmarshal(body, &lb) == nil {
|
||||||
pid = lb.GetWidevineLicense.ReleasePID
|
pid = lb.GetWidevineLicense.ReleasePID
|
||||||
}
|
}
|
||||||
bodyStr := string(body)
|
|
||||||
cap.set(func(c *capture) {
|
cap.set(func(c *capture) {
|
||||||
c.LicenseURL = url
|
c.LicenseURL = url
|
||||||
if auth != "" {
|
if auth != "" {
|
||||||
|
|
@ -336,19 +332,10 @@ func main() {
|
||||||
if pid != "" {
|
if pid != "" {
|
||||||
c.PID = pid
|
c.PID = pid
|
||||||
}
|
}
|
||||||
// Keep JSON license wrappers (RedBee / wrapped Widevine) so the
|
|
||||||
// host can swap in a local CDM challenge and re-POST.
|
|
||||||
if len(body) > 0 && (strings.HasPrefix(strings.TrimSpace(bodyStr), "{") ||
|
|
||||||
strings.Contains(strings.ToLower(req.Header.Get("Content-Type")), "json")) {
|
|
||||||
c.LicenseBody = bodyStr
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
if *verbose {
|
if *verbose {
|
||||||
log.Printf("[LIC] pid=%s auth=%s body=%d", pid, trim(auth, 40), len(body))
|
log.Printf("[LIC] pid=%s auth=%s", pid, trim(auth, 40))
|
||||||
log.Printf(" %s", trim(url, 120))
|
log.Printf(" %s", trim(url, 120))
|
||||||
if len(body) > 0 {
|
|
||||||
log.Printf(" body: %s", trim(bodyStr, 200))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if *logAll {
|
if *logAll {
|
||||||
traffic.write(map[string]any{
|
traffic.write(map[string]any{
|
||||||
|
|
@ -361,7 +348,7 @@ func main() {
|
||||||
"authorization": trim(auth, 200),
|
"authorization": trim(auth, 200),
|
||||||
"pid": pid,
|
"pid": pid,
|
||||||
"body_len": len(body),
|
"body_len": len(body),
|
||||||
"body_head": trim(bodyStr, 240),
|
"body_head": trim(string(body), 240),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1218,74 +1205,34 @@ func trim(s string, n int) string {
|
||||||
return s[:n] + "…"
|
return s[:n] + "…"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prefer a Widevine cenc:pssh (system id edef8ba9-…) over PlayReady / Marlin.
|
// Prefer the short Widevine PSSH (AAAASnBzc2g…) over the giant PlayReady blob.
|
||||||
// Channel 4 MPDs list PlayReady first; taking "any cenc:pssh" yields a useless blob.
|
|
||||||
func firstShortPSSH(mpd string) string {
|
func firstShortPSSH(mpd string) string {
|
||||||
const (
|
|
||||||
wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
|
|
||||||
wvUUIDBare = "edef8ba979d64acea3c827dcd51d21ed"
|
|
||||||
openTag = "<cenc:pssh"
|
|
||||||
closeTag = "</cenc:pssh>"
|
|
||||||
)
|
|
||||||
lower := strings.ToLower(mpd)
|
|
||||||
searchFrom := 0
|
|
||||||
for {
|
|
||||||
i := strings.Index(lower[searchFrom:], openTag)
|
|
||||||
if i < 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
i += searchFrom
|
|
||||||
j := strings.Index(mpd[i:], ">")
|
|
||||||
k := strings.Index(lower[i:], closeTag)
|
|
||||||
if j < 0 || k < 0 || k <= j {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
val := strings.TrimSpace(mpd[i+j+1 : i+k])
|
|
||||||
// Prefer the Widevine ContentProtection block: UUID appears just before
|
|
||||||
// this pssh, or the decoded box itself starts with the Widevine system id.
|
|
||||||
windowStart := i - 400
|
|
||||||
if windowStart < 0 {
|
|
||||||
windowStart = 0
|
|
||||||
}
|
|
||||||
window := lower[windowStart : i+j]
|
|
||||||
if strings.Contains(window, wvUUID) || strings.Contains(window, wvUUIDBare) || looksLikeWidevinePSSH(val) {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
searchFrom = i + k + len(closeTag)
|
|
||||||
}
|
|
||||||
// Fallback: legacy short BBC-style marker, then first cenc:pssh.
|
|
||||||
const marker = "AAAASnBzc2g"
|
const marker = "AAAASnBzc2g"
|
||||||
if idx := strings.Index(mpd, marker); idx >= 0 {
|
idx := strings.Index(mpd, marker)
|
||||||
end := idx
|
if idx < 0 {
|
||||||
for end < len(mpd) {
|
// any cenc:pssh content
|
||||||
c := mpd[end]
|
const open = "<cenc:pssh"
|
||||||
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' {
|
i := strings.Index(mpd, open)
|
||||||
end++
|
if i < 0 {
|
||||||
continue
|
return ""
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
return mpd[idx:end]
|
j := strings.Index(mpd[i:], ">")
|
||||||
|
k := strings.Index(mpd[i:], "</cenc:pssh>")
|
||||||
|
if j < 0 || k < 0 || k <= j {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(mpd[i+j+1 : i+k])
|
||||||
}
|
}
|
||||||
i := strings.Index(lower, openTag)
|
end := idx
|
||||||
if i < 0 {
|
for end < len(mpd) {
|
||||||
return ""
|
c := mpd[end]
|
||||||
|
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' {
|
||||||
|
end++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
}
|
}
|
||||||
j := strings.Index(mpd[i:], ">")
|
return mpd[idx:end]
|
||||||
k := strings.Index(lower[i:], closeTag)
|
|
||||||
if j < 0 || k < 0 || k <= j {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(mpd[i+j+1 : i+k])
|
|
||||||
}
|
|
||||||
|
|
||||||
// looksLikeWidevinePSSH reports whether a base64 PSSH box uses the Widevine system id.
|
|
||||||
func looksLikeWidevinePSSH(b64 string) bool {
|
|
||||||
// Widevine system id bytes as they appear after base64 of a typical PSSH header.
|
|
||||||
// Full decode is avoided here to keep the on-device binary dependency-free;
|
|
||||||
// the standard Widevine UUID base64 fragment inside PSSH boxes is stable.
|
|
||||||
const wvFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q" // edef8ba9-79d6-4ace-a3c8-27dcd51d21ed
|
|
||||||
return strings.Contains(b64, wvFrag)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) {
|
func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) {
|
||||||
|
|
|
||||||
|
|
@ -19,13 +19,10 @@ uid_for_package() {
|
||||||
echo "$uid"
|
echo "$uid"
|
||||||
}
|
}
|
||||||
|
|
||||||
# -w waits for the xtables lock (needed when grab-all restarts transparent MITM quickly).
|
|
||||||
IPT="iptables -w 5"
|
|
||||||
|
|
||||||
stop_rules() {
|
stop_rules() {
|
||||||
$IPT -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
|
iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
|
||||||
$IPT -t nat -F "$CHAIN" 2>/dev/null || true
|
iptables -t nat -F "$CHAIN" 2>/dev/null || true
|
||||||
$IPT -t nat -X "$CHAIN" 2>/dev/null || true
|
iptables -t nat -X "$CHAIN" 2>/dev/null || true
|
||||||
echo "STOPPED"
|
echo "STOPPED"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -44,17 +41,17 @@ start_rules() {
|
||||||
fi
|
fi
|
||||||
|
|
||||||
stop_rules >/dev/null
|
stop_rules >/dev/null
|
||||||
$IPT -t nat -N "$CHAIN"
|
iptables -t nat -N "$CHAIN"
|
||||||
# Never redirect the mitm itself (loop).
|
# Never redirect the mitm itself (loop).
|
||||||
if [ -n "$proxy_uid" ]; then
|
if [ -n "$proxy_uid" ]; then
|
||||||
$IPT -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
|
iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
|
||||||
fi
|
fi
|
||||||
# Skip localhost / link-local.
|
# Skip localhost / link-local.
|
||||||
$IPT -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN
|
iptables -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN
|
||||||
$IPT -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true
|
iptables -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true
|
||||||
# Redirect only the target app's HTTPS.
|
# Redirect only the target app's HTTPS.
|
||||||
$IPT -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port"
|
iptables -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port"
|
||||||
$IPT -t nat -A OUTPUT -j "$CHAIN"
|
iptables -t nat -A OUTPUT -j "$CHAIN"
|
||||||
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
|
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
module streamd/apps/proxy
|
module drmdecryption/apps/proxy
|
||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require streamd v0.0.0
|
require drmdecryption v0.0.0
|
||||||
|
|
||||||
replace streamd => ../pkg
|
replace drmdecryption => ../pkg
|
||||||
|
|
|
||||||
|
|
@ -18,9 +18,9 @@ import (
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamd/adb"
|
"drmdecryption/adb"
|
||||||
"streamd/proxy"
|
"drmdecryption/proxy"
|
||||||
"streamd/repo"
|
"drmdecryption/repo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Run dispatches a proxy subcommand. args[0] is the subcommand name.
|
// Run dispatches a proxy subcommand. args[0] is the subcommand name.
|
||||||
|
|
@ -130,7 +130,7 @@ func buildCmd(args []string) {
|
||||||
|
|
||||||
if _, err := os.Stat(deviceDir); err != nil {
|
if _, err := os.Stat(deviceDir); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n")
|
fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n")
|
||||||
fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to streamd instead — no Go build required.\n")
|
fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to drm.exe instead — no Go build required.\n")
|
||||||
fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
|
fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,75 +1,67 @@
|
||||||
# streamd
|
# streamd
|
||||||
|
|
||||||
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
|
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
|
||||||
single binary as `streamd serve`.
|
single binary as `drm serve`.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
apps/streamd/
|
apps/streamd/
|
||||||
servecmd/ the command body, imported by apps/cli
|
servecmd/ the command body, imported by apps/cli
|
||||||
internal/api HTTP handlers
|
internal/api HTTP handlers
|
||||||
internal/auth sessions, API keys, roles
|
|
||||||
internal/db SQLite store
|
internal/db SQLite store
|
||||||
internal/ui dashboard
|
internal/ui dashboard (index.html, app.js, app.css)
|
||||||
internal/supervisor downloader + ffmpeg supervision
|
internal/supervisor downloader + ffmpeg supervision
|
||||||
internal/ws agent + dashboard websockets
|
internal/ws agent heartbeat
|
||||||
```
|
```
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./bin/streamd serve --bind 127.0.0.1:8083
|
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
|
||||||
# --data is optional: reuses existing .cache/streamd (cwd or next to the binary)
|
|
||||||
# or set STREAMD_DATA / pass --data explicitly
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
|
Port 8083 by default, to stay clear of anything already on 8080/8081. On start,
|
||||||
non-loopback address) logs a startup warning — put TLS in front, or keep loopback
|
missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt)
|
||||||
and reverse-proxy. Port 8083 stays clear of anything already on 8080/8081.
|
unless you pass `--skip-deps`. Flags / env still win when set.
|
||||||
|
|
||||||
On start, missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE,
|
Open `http://HOST:8083/` and put the token in the header box for mutating actions.
|
||||||
mp4decrypt) unless you pass `--skip-deps`.
|
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).
|
||||||
|
|
||||||
### Auth
|
## API
|
||||||
|
|
||||||
The old shared bearer token is optional and discouraged. Prefer:
|
|
||||||
|
|
||||||
1. First-run setup creates an **admin** account (or `--admin-user` / `--admin-pass`).
|
|
||||||
2. Sign in at the dashboard (session cookie + CSRF).
|
|
||||||
3. Create **API keys** (Settings → API keys) for agents and scripts — roles
|
|
||||||
`admin` / `operator` / `viewer`.
|
|
||||||
|
|
||||||
Legacy `--token` / `STREAMD_TOKEN` still works as an admin API key and logs a
|
|
||||||
warning so you can migrate.
|
|
||||||
|
|
||||||
`GET /api/health` stays readable without a principal (liveness only). Stream list,
|
|
||||||
credentials, and mutations need a session or API key.
|
|
||||||
|
|
||||||
## API (short)
|
|
||||||
|
|
||||||
| Method | Path | Notes |
|
| Method | Path | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/api/health` | liveness (+ deps when authenticated) |
|
| GET | `/api/health` | liveness + uptime |
|
||||||
| GET | `/api/apps` | modules, channels, rewriters |
|
| GET | `/api/apps` | modules/<name>/ providers, channels, registered rewriters |
|
||||||
| GET | `/api/streams` | list + runtime (agent polls this) |
|
| GET | `/api/streams` | list + runtime (the agent polls this) |
|
||||||
| POST | `/api/streams` | create (`enabled` defaults false unless set; use the form checkbox) |
|
| 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/capture` | ask connected agents to refresh credentials now |
|
| POST | `/api/streams/:id/credentials` | `{mpd,key?,pssh?,auth?,pid?}` — key optional; restarts if enabled |
|
||||||
| POST | `/api/streams/:id/credentials` | `{mpd,key?,…}` — restarts if enabled |
|
| POST | `/api/streams/:id/claim` | agent lease (`agent_id`, TTL ~3m) |
|
||||||
| POST | `/api/streams/:id/claim` | agent lease |
|
| POST | `/api/streams/:id/claim/release` | release lease |
|
||||||
|
|
||||||
HLS output is served from `--data/www` at `/hls/<name>/index.m3u8`.
|
Mutating routes need `Authorization: Bearer TOKEN` (or `X-Streamd-Token`, or
|
||||||
|
`?token=`). HLS output is served from `--data/www` at `/hls/<name>/index.m3u8`.
|
||||||
Installation-wide settings (`idle_timeout_s`, `default_on_demand`,
|
|
||||||
`default_outputs`, packager knobs) apply when creating a stream that omits those
|
|
||||||
fields, or at the next media start for packager knobs.
|
|
||||||
|
|
||||||
## No provider knowledge
|
## No provider knowledge
|
||||||
|
|
||||||
App/channel pickers come from `/api/apps`. Downloader settings resolve at start:
|
The schema has no provider defaults, and the dashboard's app/channel pickers come
|
||||||
|
from `/api/apps`. Per-stream downloader settings resolve at start time:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
stored row -> app module (StreamDefaults) -> installation settings -> neutral defaults
|
stored row -> the stream's app module (app.StreamDefaults) -> neutral defaults
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The manifest rewriter is a registry lookup on the stream's `rewriter` column, and
|
||||||
|
HLS is detected from the manifest shape — not from an app or stream name.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
| Area | State |
|
||||||
|
|---|---|
|
||||||
|
| serve + SQLite + CRUD UI + claims + credentials | done |
|
||||||
|
| `/api/apps` + module-driven defaults | done |
|
||||||
|
| Real downloader/ffmpeg workers + playlist health | partial — least exercised path |
|
||||||
|
|
||||||
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue