Compare commits

...
12 Commits
Author SHA1 Message Date
imSp4rky 0576d9d03c chore(release): 5.4.0 2026-08-15 15:54:07 -06:00
imSp4rky 9a2f7a6661 fix(kv): search remote vaults that cannot list their tables
Probe locally installed service tags in parallel when a vault has no table listing, and report every vault holding the KID instead of the first hit.
2026-08-15 15:09:42 -06:00
imSp4rky e1fbd11678 fix(dash): resolve representations by adaptation set, not id alone
Representation ids are only unique within an AdaptationSet, so re-finding a track by id could download a sibling set's stream (audio description in place of dialog). Applies to download_track and extract_dash.
2026-08-15 14:26:45 -06:00
imSp4rky 415a195957 test(serve): strip ANSI from CLI output before asserting error message 2026-08-13 16:33:08 -06:00
imSp4rky db9ec3e334 feat(cli): add named color themes and rich-formatted help
Render all click help through rich-click, themed by a new `theme` config key (9 palettes + aliases, previewable via `unshackle env theme`), and show service docstrings in local and remote `dl <TAG> -h`.
2026-08-13 16:25:14 -06:00
imSp4rky a248ae79bd feat(serve): gate server CDM licensing behind a per-key server_cdm opt-in
Keys configured under serve.users default to off, so they license with their own local CDM; session licensing and download jobs both refuse otherwise.
2026-08-13 11:40:30 -06:00
imSp4rky ccb4a69302 fix(services): re-raise ClickException for better error handling in remote services cache 2026-08-13 09:23:23 -06:00
imSp4rky 5796729bf3 feat(remote): accept serve.users keys in api-only mode and add client auth-header fallback
api-only/remote-only serve now authenticates every serve.users key (str-coerced), not just api_secret, so per-user service allowlists apply. RemoteClient tries X-Secret-Key then X-Api-Key on 401 (sticky winner); remote_services.auth_headers prepends extra header names to the defaults.
2026-08-12 17:58:55 -06:00
imSp4rky 274b2fc308 fix(subtitle): keep cue-less webvtt instead of failing the download
A rendition with headers but no cues raised CaptionReadNoCaptions when preserve_formatting is false, aborting the whole download.
2026-08-12 11:42:15 -06:00
imSp4rky 16ae73e3a0 feat(api): stream download job progress over server-sent events
Adds GET /api/download/jobs/{job_id}/events with snapshot, status, progress and terminal events, query-param auth for EventSource in both serve modes, atomic progress-file writes, and stream-safe CORS and compression middleware.
2026-08-12 10:35:43 -06:00
imSp4rky 581979c5a8 fix(dl): reset per-title language and range selection each iteration 2026-08-12 07:23:59 -06:00
imSp4rky c2f3577540 chore(changelog): update changelog 2026-08-11 21:46:54 -06:00
37 changed files with 1252 additions and 140 deletions
+30 -3
View File
@@ -6,11 +6,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
This changelog is automatically generated using [git-cliff](https://git-cliff.org).
## [Unreleased]
## [5.4.0] - 2026-08-15
### Features
- *dl*: Exclude a language with a `-` prefix on -l, -vl, -al, -sl and -fsl
- *api*: Report per-episode and per-track progress on download jobs
- *api*: Add job retry/priority/clear, history, config and maintenance endpoints
- *api*: Expose choice values and multiple flag in service cli_params
@@ -38,6 +37,17 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- *vaults*: Support custom headers on API vault
- *dl*: Add tag_rules to conditionally swap the group tag
- *titles*: Add optional Episode.part, selected with -w s1e1.2
- *enrich*: Fill in the original language from metadata providers
- *dl*: Allow --tvdb as an --enrich metadata source
- *dl*: Exclude languages with a - prefix on -l, -vl, -al, -sl and -fsl
- *metadata*: [**breaking**] Authoritative id resolver and keyless imdb provider
- *metadata*: [**breaking**] Replace animeapi with a first-class anilist provider
- *dl*: Add absolute episode numbers filled from tvdb absolute order
- *dl*: Add daily date-based episodes with tvdb air-date fill
- *api*: Stream download job progress over server-sent events
- *remote*: Accept serve.users keys in api-only mode and add client auth-header fallback
- *serve*: Gate server CDM licensing behind a per-key server_cdm opt-in
- *cli*: Add named color themes and rich-formatted help
### Bug Fixes
@@ -74,16 +84,27 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- *subtitles*: Strip X-TIMESTAMP-MAP so WebVTT cues are not offset on conversion
- *downloader*: Decode content-encoded bodies instead of writing raw
- *downloader*: Surface failed downloads instead of returning silently
- *dl*: Warn when --enrich source is missing title, year, or language
- *api*: Carry air_date, absolute, anime and daily across the title wire
- *dl*: Treat audio muxed into the video as an available language
- *hls*: Take the key id from EXT-X-KEY when the PSSH carries none
- *dl*: Reset per-title language and range selection each iteration
- *subtitle*: Keep cue-less webvtt instead of failing the download
- *services*: Re-raise ClickException for better error handling in remote services cache
- *dash*: Resolve representations by adaptation set, not id alone
- *kv*: Search remote vaults that cannot list their tables
### Documentation
- Restructure documentation into MkDocs Material site
- Expand config reference and genericize service names
- *changelog*: Regenerate with git-cliff
- Correct DRM, muxing, and proxy references (+ case-insensitive proxy prefix fix)
- Cleanup and correct documentation
- *core*: Drop service tags from framework comments
- Cover the TVDB provider, episode ordering and provider order
- Split configuration reference into per-area pages
- *api*: Note the - language exclusion prefix in the OpenAPI spec
### Performance Improvements
@@ -97,6 +118,12 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- *core*: [**breaking**] Bundle download_track args into DownloadContext
- *tracks*: Honour the best token and share one match rule
### Maintenance
- *changelog*: Update entries for new features and bug fixes
- *env*: Drop ML-Worker from the dependency check
- *changelog*: Update changelog
### Builds
- *deps*: Cap pycaption below 2.2.27
@@ -866,7 +893,7 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- Reorganize Planned Features section in README for clarity
- Improve track selection logic in dl.py
[unreleased]: https://github.com/unshackle-dl/unshackle/compare/5.3.0..HEAD
[5.4.0]: https://github.com/unshackle-dl/unshackle/compare/5.3.0..5.4.0
[5.3.0]: https://github.com/unshackle-dl/unshackle/compare/5.2.0..5.3.0
[5.2.0]: https://github.com/unshackle-dl/unshackle/compare/5.1.0..5.2.0
[5.1.0]: https://github.com/unshackle-dl/unshackle/compare/5.0.0..5.1.0
+15 -1
View File
@@ -108,6 +108,17 @@ X-Secret-Key: <your-secret>
The value must exactly match one of the configured keys (`api_secret`, or one of the keys under `users`). There is no login step, no session cookie, and no token exchange for API access. The same static key is sent on each request.
!!! info "One route also accepts the key as a query parameter"
The job event stream, `GET /api/download/jobs/{job_id}/events`, also accepts the key in a `secret_key` query parameter. This is for browsers: the `EventSource` API cannot set request headers. The exception applies to that one route only, and it works in both server modes.
```javascript
new EventSource(`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`);
```
The header always wins. If the request has an `X-Secret-Key` header, the server checks that header and ignores the query parameter, so a wrong header is rejected even when the query parameter holds a valid key.
A key in a URL is easier to leak than a key in a header, because proxies and browser history can record it. Use the header wherever your client can set one.
=== "curl"
```bash
@@ -269,6 +280,7 @@ With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located
| Item | Value |
|---|---|
| Auth header | `X-Secret-Key` |
| Query-parameter alternative | `?secret_key=` on `GET /api/download/jobs/{job_id}/events` only |
| Default bind address | `127.0.0.1:8786` |
| Exempt endpoint | `GET /api/health` |
| Failure status | `401 Unauthorized` |
@@ -287,12 +299,14 @@ With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located
The header and config are identical between modes, but the code that enforces them differs:
- **API-only server** (`--api-only`, or `--remote-only` which forces API-only). An `api_key_authentication` middleware runs on every request. It lets `GET /api/health` through unconditionally, then reads `X-Secret-Key`. An empty header returns the *"Secret Key is Empty."* body; a header that is not a configured user returns *"Secret Key is Invalid."*. In this mode the accepted-keys map contains exactly one entry: your `api_secret` (labelled `api_user`, with no devices). With `--no-key`, this middleware is simply not installed and the users map is empty.
- **API-only server** (`--api-only`, or `--remote-only` which forces API-only). An `api_key_authentication` middleware runs on every request. It lets `GET /api/health` through unconditionally, then reads `X-Secret-Key`. An empty header returns the *"Secret Key is Empty."* body; a header that is not a configured user returns *"Secret Key is Invalid."*. In this mode the accepted-keys map holds your `api_secret` (labelled `api_user`, with no devices) plus every key under `serve.users`, so a per-user key authenticates here exactly as it does on the integrated server, and that user's `services` allowlist applies as usual. With `--no-key`, this middleware is simply not installed and the users map is empty.
- **Integrated server** (default). A `serve_authentication` middleware wraps pywidevine's authentication (and pyplayready's for `/playready*` paths), and the REST routes live in the same application, guarded by the same check. Here the accepted-keys map is your full `serve` config: `api_secret` (auto-added with access to all loaded devices) plus every entry under `users`, each with its declared `devices` / `playready_devices`.
Because the API-only middleware guards *all* non-health paths, the Swagger UI at `/api/docs/` is also behind `X-Secret-Key` there. In `--remote-only` mode the Swagger UI is not mounted at all.
Both middlewares read the caller's key through the shared `request_secret_key()` helper in `unshackle/core/api/handlers.py`, which returns the `X-Secret-Key` header and falls back to the `secret_key` query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this: pywidevine's `authentication` is header-only, so `serve_authentication` compares the query-parameter key itself when the header is absent, and delegates to pywidevine in every other case. That is why a present-but-wrong header is rejected in both modes.
### CORS and the `Authorization` header
A `cors_middleware` runs on every response in both modes (and answers `OPTIONS` preflight requests with an empty response). It emits:
+67
View File
@@ -492,6 +492,73 @@ Fetch a single job with full details (equivalent to a `full=true` list entry).
| `200` | - | Job returned. |
| `404` | `JOB_NOT_FOUND` | No such job. |
### `GET /api/download/jobs/{job_id}/events`
Stream the job's progress as [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events). Use this instead of polling `GET /api/download/jobs/{job_id}`.
The response has the content type `text/event-stream`. Each event has this format:
```
event: <name>
data: <job JSON>
```
The `data` field of every event is the same job object that `GET /api/download/jobs/{job_id}` returns.
| Event | When it is sent |
| --- | --- |
| `snapshot` | Immediately, as the first event. Gives the job's current state. |
| `status` | The job leaves the queue and starts to download. |
| `progress` | The worker's progress record changed. The server reads that record every 0.5 seconds, so you get at most two of these events each second, and none while the record stays the same. |
| `completed` | The job finished. The server then closes the stream. |
| `failed` | The job failed. The server then closes the stream. |
| `cancelled` | The job was cancelled. The server then closes the stream. |
The server sends a `: keep-alive` comment each 15 seconds while the job is quiet, to keep proxies from closing an idle connection. Ignore these lines.
If the job is already in a terminal state, the server sends the `snapshot` event, then the terminal event, and closes the stream immediately.
!!! tip "Authentication from a browser"
`EventSource` cannot set headers. For this endpoint only, the server also accepts the key in the `secret_key` query parameter. This works in both server modes, the default integrated server and `--api-only`:
```javascript
const events = new EventSource(
`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`
);
events.addEventListener("progress", (e) => console.log(JSON.parse(e.data).progress));
events.addEventListener("completed", () => events.close());
```
The header always wins. Send the key in the query parameter *or* in the header, not both: if an `X-Secret-Key` header is present, the server checks that header and ignores the query parameter. See [Authentication](authentication.md#how-clients-present-credentials).
=== "Request"
```bash
curl -N -H "X-Secret-Key: $KEY" \
"http://127.0.0.1:8786/api/download/jobs/b0f7c8e2-.../events"
```
=== "Response `200`"
```
event: snapshot
data: {"job_id":"b0f7c8e2-...","status":"downloading","progress":42.5,...}
event: progress
data: {"job_id":"b0f7c8e2-...","status":"downloading","progress":48.0,...}
: keep-alive
event: completed
data: {"job_id":"b0f7c8e2-...","status":"completed","progress":100.0,...}
```
| Status | Error code | Meaning |
| --- | --- | --- |
| `200` | - | Event stream started. |
| `404` | `JOB_NOT_FOUND` | No such job. |
### `DELETE /api/download/jobs/{job_id}`
Cancel or remove a job. The behaviour depends on the job's current state:
+4 -2
View File
@@ -22,8 +22,9 @@ calls you can script against:
- **Discovery**: list the services available on the server, run a service's search,
and enumerate the titles and tracks behind a title ID.
- **Downloading**: submit a download as a background *job*, then poll its status and
live progress, cancel it, retry it, or bump it to the front of the queue.
- **Downloading**: submit a download as a background *job*, then follow its status and
live progress (by polling, or by subscribing to its Server-Sent Events stream),
cancel it, retry it, or bump it to the front of the queue.
- **History and housekeeping**: read the log of finished jobs, inspect the server's
effective (redacted) configuration, check external tool versions, and clear caches
or temp files.
@@ -161,6 +162,7 @@ request and response in full.
| `GET` | `/api/download/jobs` | List jobs, with filtering and sorting. |
| `POST` | `/api/download/jobs/clear-finished` | Remove all finished jobs. |
| `GET` | `/api/download/jobs/{job_id}` | Full detail for one job. |
| `GET` | `/api/download/jobs/{job_id}/events` | Stream one job's progress as Server-Sent Events. |
| `DELETE` | `/api/download/jobs/{job_id}` | Cancel a running job, or remove a finished one. |
| `POST` | `/api/download/jobs/{job_id}/retry` | Re-queue a finished job's parameters as a new job. |
| `POST` | `/api/download/jobs/{job_id}/priority` | Move a queued job to the front. |
+5
View File
@@ -177,6 +177,11 @@ The full detail adds `started_time`, `completed_time`, `output_files`, the redac
done
```
!!! tip "Or subscribe instead of polling"
`GET /api/download/jobs/{job_id}/events` pushes the same job object as Server-Sent
Events, and closes the stream when the job ends. See
[Endpoints](endpoints.md#get-apidownloadjobsjob_idevents).
!!! note "What the percentage means"
`progress` climbs from `0` toward `90` while tracks download, then the final stretch
to `100` covers post-download work such as decryption cleanup, repackaging, and
+9 -1
View File
@@ -310,7 +310,15 @@ done
```
!!! tip "Polling cadence"
A few seconds between polls is plenty. The server writes progress updates roughly twice a second internally, but there is no push/streaming channel; you read the current snapshot each time you ask.
A few seconds between polls is plenty. The server updates a job's progress roughly twice a second internally, and each poll reads the current snapshot.
!!! tip "Or let the server push the updates"
`GET /api/download/jobs/{job_id}/events` streams the same job record as Server-Sent Events, and closes the stream when the job ends. It removes the polling loop above. See [Endpoints](endpoints.md#get-apidownloadjobsjob_idevents).
```bash
curl -N "$BASE/api/download/jobs/$JOB/events" \
-H "X-Secret-Key: $SECRET"
```
If a job ends in `failed`, the full record includes `error_message`, `error_code`, and (when the server was started with `--debug-api`) `error_traceback` and `worker_stderr` to help you diagnose it. Sensitive values in these fields are scrubbed before they are returned.
+9
View File
@@ -322,6 +322,14 @@ unshackle env info
Shows where the config was loaded from (or lists the candidate config locations if none was found) and prints a table of every configured directory (downloads, temp, cache, cookies, logs, exports, WVDs, PRDs, services, and more).
### `env theme`
```
unshackle env theme
```
Prints a sample of every available CLI theme: colour swatches, help text with option rows, a track listing with video/audio/subtitle entries, log lines, a progress bar, and the gradient pulse bar. The active theme is marked and each theme's aliases are listed. Set your choice with the [`theme`](../reference/configuration/misc.md#appearance) config key.
### `env clear`
Clear an environment directory. The directory is emptied and recreated, and the number of files and bytes freed is reported.
@@ -335,6 +343,7 @@ Clear an environment directory. The directory is emptied and recreated, and the
```shell
unshackle env check
unshackle env info
unshackle env theme
unshackle env clear cache
unshackle env clear cache EXAMPLE # one service only
unshackle env clear temp
+1
View File
@@ -38,5 +38,6 @@ Where the file lives, how unshackle discovers it, and how to edit it:
| [Key vaults](vaults.md) | `key_vaults`, `vault_timeout` |
| [External API keys](misc.md#external-api-keys) | `omdb_api_key`, `tmdb_api_key`, `tvdb_api_key`, `tvdb_pin`, `tvdb_order`, `simkl_client_id`, `metadata_providers`, `anilist_title_language`, `disable_metadata`, `decrypt_labs_api_key`, `ipinfo_api_key` |
| [Caching & updates](misc.md#caching-updates) | `title_cache_enabled`, `title_cache_time`, `title_cache_max_retention`, `update_checks`, `update_check_interval` |
| [Appearance](misc.md#appearance) | `theme` |
| [Logging, privacy & debug](misc.md#logging-privacy-debug) | `redact_paths`, `debug`, `debug_keys`, `debug_requests`, `set_terminal_bg` |
| [Deprecated & removed](misc.md#deprecated-removed-keys) | `curl_impersonate`, `downloader`, `scene_naming` |
+8
View File
@@ -141,6 +141,14 @@ calls.
---
## Appearance { #appearance }
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `theme` | str | `catppuccin-mocha` | Named colour theme for all CLI output: banner, logs, progress bars, and help screens. One of `catppuccin-mocha` (aliases `default`, `catppuccin`, `mocha`), `dracula`, `nord`, `gruvbox`, `one-dark` (alias `onedark`), `tokyo-night` (alias `tokyonight`), `monokai`, `flexoki`, `solarized-dark` (alias `solarized`). Case-insensitive; underscores work in place of hyphens. Unknown names fall back to the default with a warning. Preview them all with `unshackle env theme`. |
---
## Logging, privacy & debug { #logging-privacy-debug }
| Key | Type | Default | Description |
+24 -4
View File
@@ -82,11 +82,22 @@ keep auth tokens in localStorage rather than in HTTP cookies need. Extraction is
Definitions of remote unshackle service servers, used by the `--remote` mode. Each entry is
named by you (pick it with `--server`, or omit that flag when only one is configured) and gives
the server's `url` (required), an optional `api_key` sent as `X-Secret-Key`, an optional
`server_cdm` boolean, and an optional `services` sub-dict of per-service local overrides such
as `title_map`. In `--remote` mode unshackle turns the server's service list into synthetic CLI
the server's `url` (required), an optional `api_key`, an optional `auth_headers` list, an
optional `server_cdm` boolean, and an optional `services` sub-dict of per-service local
overrides such as `title_map`.
`auth_headers` lists extra header names to send the API key in, tried before the defaults
`X-Secret-Key` and `X-Api-Key`, which are always appended as fallbacks. unshackle sends the
first name; if the server answers `401`, it retries the same request with the next name, and
keeps the one that works for the rest of the session. Names you list keep your spelling and are
not repeated in the fallbacks, so `auth_headers: ["Authorization", "x-secret-key"]` is tried as
`Authorization`, `x-secret-key`, `X-Api-Key`.
In `--remote` mode unshackle turns the server's service list into synthetic CLI
commands that run against it, falling back to the tags in that `services` sub-dict when the
list cannot be fetched. See [remote sessions](../../dev/rest-api/remote-sessions.md) for the
list cannot be fetched. Each synthetic command carries the server-side service's options and
documentation, so `unshackle dl --remote <TAG> -h` shows the same help text as it does on the
server. See [remote sessions](../../dev/rest-api/remote-sessions.md) for the
full setup.
## `serve`
@@ -117,6 +128,13 @@ Each entry under `users` is keyed by that user's API key and may set its own `se
`username` used as the log label for that key (defaults to a truncated form of the key). A
user with no `playready_devices` key gets no PlayReady access at all, not the global list.
`server_cdm` decides whether the server runs the CDM licensing for that key. It is `false`
unless the entry sets it, so a remote client configured with `server_cdm: true` is told to
license with its own local CDM instead, and a client that asks anyway gets a `FORBIDDEN`
error. Because a download job always licenses with the server's CDM, a key without
`server_cdm` also cannot submit or retry `/api/download` jobs. Keys that have no `users`
entry, such as `api_secret`, keep server CDM access.
```yaml
serve:
api_secret: change-me
@@ -128,6 +146,8 @@ serve:
users:
a1b2c3d4: # this user's API key
services: [EXAMPLE1] # may only use EXAMPLE1
e5f6a7b8:
server_cdm: true # this key may have the server do the licensing
```
!!! note "`dl` keys inside `serve`"
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "unshackle"
version = "5.3.0"
version = "5.4.0"
description = "Modular Movie, TV, and Music Archival Software."
authors = [{ name = "unshackle team" }]
requires-python = ">=3.11,<3.15"
@@ -69,6 +69,7 @@ dependencies = [
"jsonpath-ng>=1.8.0",
"mutagen>=1.47.0,<2",
"defusedxml>=0.7.1",
"rich-click>=1.9.8",
]
[project.urls]
+59
View File
@@ -85,6 +85,65 @@ def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: p
assert "no such session" in caplog.text
@responses.activate
def test_401_falls_back_to_next_auth_header(client: RemoteClient) -> None:
seen: list[tuple[str | None, str | None]] = []
def cb(request):
seen.append((request.headers.get("X-Secret-Key"), request.headers.get("X-Api-Key")))
if request.headers.get("X-Api-Key") == "secret-xyz":
return (200, {}, json.dumps({"status": "ok"}))
return (401, {}, json.dumps({"message": "Secret Key is Invalid."}))
responses.add_callback(responses.GET, "http://srv:8786/api/services", callback=cb)
assert client.get("/api/services") == {"status": "ok"}
assert seen == [("secret-xyz", None), (None, "secret-xyz")]
# the winning header is sticky: no second attempt on the next request
seen.clear()
assert client.get("/api/services") == {"status": "ok"}
assert seen == [(None, "secret-xyz")]
@responses.activate
def test_non_401_error_does_not_fall_back(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
responses.GET,
"http://srv:8786/api/services",
json={"error_code": "FORBIDDEN", "message": "nope"},
status=403,
)
with caplog.at_level("ERROR"), pytest.raises(SystemExit):
client.get("/api/services")
assert len(responses.calls) == 1
assert client.session.headers.get("X-Secret-Key") == "secret-xyz"
@responses.activate
def test_401_on_every_header_exits(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
responses.GET,
"http://srv:8786/api/services",
json={"error_code": "UNAUTHORIZED", "message": "Secret Key is Invalid."},
status=401,
)
with caplog.at_level("ERROR"), pytest.raises(SystemExit):
client.get("/api/services")
assert len(responses.calls) == 2
assert "Secret Key is Invalid." in caplog.text
@responses.activate
def test_single_configured_auth_header_does_not_retry() -> None:
c = RemoteClient(server_url="http://srv:8786", api_key="k", auth_headers=["X-Api-Key"])
responses.add(responses.GET, "http://srv:8786/api/services", json={"message": "nope"}, status=401)
with pytest.raises(SystemExit):
c.get("/api/services")
assert len(responses.calls) == 1
assert c.session.headers.get("X-Api-Key") == "k"
@responses.activate
def test_connection_error_raises_systemexit(client: RemoteClient) -> None:
import requests
+37
View File
@@ -49,6 +49,43 @@ def multi_remote_services(monkeypatch: pytest.MonkeyPatch) -> None:
)
def test_resolve_server_default_auth_headers(single_remote_service) -> None:
_, _, services = resolve_server("primary")
assert services["_auth_headers"] == ["X-Secret-Key", "X-Api-Key"]
def test_resolve_server_custom_auth_headers_extend_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core import remote_service as rs
monkeypatch.setattr(
rs.config, "remote_services", {"p": {"url": "https://p:8080", "auth_headers": ["Authorization"]}}
)
_, _, services = resolve_server("p")
assert services["_auth_headers"] == ["Authorization", "X-Secret-Key", "X-Api-Key"]
def test_resolve_server_auth_headers_dedup_is_case_insensitive(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core import remote_service as rs
monkeypatch.setattr(
rs.config,
"remote_services",
{"p": {"url": "https://p:8080", "auth_headers": ["Authorization", "x-secret-key"]}},
)
_, _, services = resolve_server("p")
assert services["_auth_headers"] == ["Authorization", "x-secret-key", "X-Api-Key"]
@pytest.mark.parametrize("bad", ["X-Api-Key", [], [""], ["X-Api-Key", 3]])
def test_resolve_server_bad_auth_headers_raises(monkeypatch: pytest.MonkeyPatch, bad: object) -> None:
from unshackle.core import remote_service as rs
monkeypatch.setattr(rs.config, "remote_services", {"p": {"url": "https://p:8080", "auth_headers": bad}})
with pytest.raises(click.ClickException) as exc:
resolve_server("p")
assert "auth_headers" in str(exc.value.message)
def test_resolve_server_no_config_raises_click(empty_remote_services) -> None:
with pytest.raises(click.ClickException) as exc:
resolve_server(None)
+60 -1
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import re
import pytest
from click.testing import CliRunner
@@ -50,7 +52,9 @@ def test_serve_api_only_with_no_widevine_rejected(runner: CliRunner, monkeypatch
result = runner.invoke(serve, ["--api-only", "--no-widevine", "--no-key"])
assert result.exit_code != 0
assert "Cannot use --api-only" in (result.output or str(result.exception))
# strip ANSI: rich-click forces color under GITHUB_ACTIONS and styles --flags mid-sentence
output = re.sub(r"\x1b\[[0-9;]*m", "", result.output or str(result.exception))
assert "Cannot use --api-only" in output
def test_serve_no_key_without_api_secret_does_not_require_secret(
@@ -69,6 +73,61 @@ def test_serve_no_key_without_api_secret_does_not_require_secret(
assert result.exit_code == 0, result.output
async def test_api_only_accepts_serve_users_keys(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, aiohttp_client
) -> None:
"""In api-only keyed mode the accepted keys are api_secret plus every `serve.users` key."""
from aiohttp import web
captured: dict = {}
def capture_app(app, **kwargs):
captured["app"] = app
monkeypatch.setattr(web, "run_app", capture_app)
from unshackle.core.config import config as cfg
monkeypatch.setattr(
cfg,
"serve",
{"api_secret": "master-key", "users": {"user-key": {"username": "alice", "services": ["EXAMPLE"]}}},
)
result = runner.invoke(serve, ["--api-only", "--remote-only"])
assert result.exit_code == 0, result.output
app = captured["app"]
assert set(app["config"]["users"]) == {"master-key", "user-key"}
assert app["config"]["users"]["user-key"]["username"] == "alice"
client = await aiohttp_client(app)
# an unrouted path still passes through the auth middleware first
assert (await client.get("/api/unknown", headers={"X-Secret-Key": "user-key"})).status == 404
assert (await client.get("/api/unknown", headers={"X-Secret-Key": "master-key"})).status == 404
assert (await client.get("/api/unknown", headers={"X-Secret-Key": "nope"})).status == 401
async def test_api_only_coerces_non_str_user_keys(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, aiohttp_client
) -> None:
"""A yaml users key that parses as int must still authenticate (compare_digest needs str)."""
from aiohttp import web
captured: dict = {}
monkeypatch.setattr(web, "run_app", lambda app, **kwargs: captured.update(app=app))
from unshackle.core.config import config as cfg
monkeypatch.setattr(cfg, "serve", {"api_secret": "master-key", "users": {123456: {"username": "bob"}}})
result = runner.invoke(serve, ["--api-only", "--remote-only"])
assert result.exit_code == 0, result.output
assert "123456" in captured["app"]["config"]["users"]
client = await aiohttp_client(captured["app"])
assert (await client.get("/api/unknown", headers={"X-Secret-Key": "123456"})).status == 404
assert (await client.get("/api/unknown", headers={"X-Secret-Key": "master-key"})).status == 404
def test_serve_without_no_key_requires_api_secret(runner: CliRunner, monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.config import config as cfg
+56
View File
@@ -0,0 +1,56 @@
"""Only keys that opt in may have the server run the CDM licensing."""
from types import SimpleNamespace
import pytest
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
pytestmark = pytest.mark.unit
USERS = {
"tier1key": {"username": "tier1"},
"tier3key": {"username": "tier3", "server_cdm": True},
}
ENTITLEMENTS = [
("tier3key", True),
("tier1key", False),
("adminsecret", True), # no users entry, e.g. api_secret
(None, True),
]
@pytest.fixture
def serve_users(monkeypatch):
monkeypatch.setattr(handlers.config, "serve", {"users": USERS}, raising=False)
monkeypatch.setattr(handlers, "request_secret_key", lambda request: request.headers.get("X-Secret-Key"))
def _request(key):
return SimpleNamespace(headers={"X-Secret-Key": key} if key else {})
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
def test_server_cdm_allowed(serve_users, key, allowed):
assert handlers.server_cdm_allowed(_request(key)) is allowed
def test_no_request_allows(serve_users):
assert handlers.server_cdm_allowed(None) is True
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
def test_download_gate_follows_entitlement(serve_users, key, allowed):
# A download job licenses with the server CDM, so submission obeys the same gate.
if allowed:
handlers.enforce_download_gates({}, _request(key))
else:
with pytest.raises(APIError) as ei:
handlers.enforce_download_gates({}, _request(key))
assert ei.value.error_code == APIErrorCode.FORBIDDEN
def test_download_gate_without_request(serve_users):
handlers.enforce_download_gates({})
+16 -6
View File
@@ -30,6 +30,7 @@ import yaml
from click.core import ParameterSource
from langcodes import Language, tag_is_valid
from pymediainfo import MediaInfo
from rich import box
from rich.console import Group
from rich.padding import Padding
from rich.panel import Panel
@@ -1404,7 +1405,7 @@ class dl:
self.service_anime = bool(getattr(service, "ANIME", False))
self.service_daily = bool(getattr(service, "DAILY", False))
self.server_cdm = getattr(service, "_server_cdm", False)
self._remote_service = service if self.server_cdm else None
self._remote_service = service if hasattr(service, "_server_cdm") else None
start_time = time.time()
lang, lang_excl = partition_exclusions(lang)
@@ -1766,7 +1767,7 @@ class dl:
# Note: Headers are not mapped to actual title indices
# Format display name
display_name = ((t.name[:30].rstrip() + "…") if len(t.name) > 30 else t.name) if t.name else None
display_name = ((t.name[:30].rstrip() + "...") if len(t.name) > 30 else t.name) if t.name else None
# Apply indentation only for multiple seasons
prefix = " " if multiple_seasons else ""
@@ -2350,7 +2351,10 @@ class dl:
if music_collection_mode:
raise click.ClickException("Music collections require grouped audio downloads.")
base_selection = (v_lang, a_lang, s_lang, range_)
for i, title in enumerate(titles):
v_lang, a_lang, s_lang, range_ = base_selection
if isinstance(title, Episode) and latest_episode and latest_episode_id:
# If --latest-episode is set, only process the latest episode
if f"{title.season}x{title.number}" != latest_episode_id:
@@ -2571,7 +2575,7 @@ class dl:
exact_match=exact_lang,
)
title.tracks.sort_subtitles(
by_language=resolve_sort_langs([*subtitle_priority, *s_lang], title.language),
by_language=resolve_sort_langs([*subtitle_priority, *(s_lang or [])], title.language),
type_priority=config.subtitle.get("type_priority"),
group_by=config.subtitle.get("group_by"),
exact_match=exact_lang,
@@ -2579,7 +2583,12 @@ class dl:
if list_:
available_tracks, _ = title.tracks.tree()
console.print(Padding(Panel(available_tracks, title="Available Tracks"), (0, 5)))
console.print(
Padding(
Panel(available_tracks, title="Available Tracks", box=box.SQUARE, border_style="bright_black"),
(0, 5),
)
)
continue
# Determine which tracks to keep
@@ -4163,7 +4172,7 @@ class dl:
Carries no session/cookies/dl-flags. Region (country code) is stored only when the
export used ``--proxy``, as an import geofence. Each track records only the licensed
DRM system; content keys live once under the track's ``keys``. ``drm`` may be None
(DRM-free track) or a DRM system without ``to_dict``/``content_keys`` (e.g. ClearKey) —
(DRM-free track) or a DRM system without ``to_dict``/``content_keys`` (e.g. ClearKey) -
the track, manifest, chapter and attachment info is still exported.
"""
with self.EXPORT_LOCK:
@@ -4253,7 +4262,8 @@ class dl:
if not drm:
return
server_cdm = getattr(self, "server_cdm", False)
svc_for_cdm = getattr(self, "_remote_service", None)
server_cdm = getattr(svc_for_cdm, "_server_cdm", getattr(self, "server_cdm", False))
if server_cdm:
if not drm.content_keys:
+105
View File
@@ -188,6 +188,111 @@ def check() -> None:
console.print(Padding(" ".join(summary_parts), (1, 2)))
@env.command()
def theme() -> None:
"""Preview the available CLI themes."""
import math
from rich import box
from rich.color import Color, blend_rgb
from rich.console import Group
from rich.panel import Panel
from rich.rule import Rule
from rich.style import Style
from rich.text import Text
from unshackle.core.themes import ALIASES, DEFAULT_THEME, PALETTES, resolve_palette
active = resolve_palette(config.theme) or PALETTES[DEFAULT_THEME]
for name, palette in PALETTES.items():
text, text2, gray, guide = palette["text"], palette["text2"], palette["gray"], palette["bright_black"]
header = Text(name, style=palette["pink"])
if palette == active:
header.append(" (active)", style=palette["green"])
aliases = sorted(alias for alias, target in ALIASES.items() if target == name)
if aliases:
header.append(f" aliases: {', '.join(aliases)}", style=f"dim {gray}")
swatch = Text()
for role in ("red", "green", "yellow", "blue", "pink", "cyan", "text", "gray"):
swatch.append("██ ", style=palette[role])
docstring = Text()
docstring.append("Service docstrings render like this, ", style=text)
docstring.append("with secondary detail lines like this.", style=text2)
separator = Text("─" * 60, style=palette["dark_gray"])
options: list[Text] = []
rows = (
("-q, ", "--quality ", "TEXT ", "Video quality to download", " [default: best]", f"dim {gray}"),
(
"-r, ",
"--range ",
"[SDR|HDR10|DV] ",
"Video color range",
" [env: RANGE]",
f"dim {palette['yellow']}",
),
)
for short, long_opt, metavar, help_text, extra, extra_style in rows:
row = Text()
row.append(short, style=palette["green"])
row.append(long_opt, style=text)
row.append(metavar, style=palette["yellow"])
row.append(f" {help_text}", style=text)
row.append(extra, style=extra_style)
options.extend((row, separator))
listing = Tree(Text("1 season, S1(1)", style=text), guide_style=guide)
episode = listing.add(Text.assemble(("1. ", palette["blue"]), ("Pilot", text)), guide_style=guide)
track_rows = (
("VID", "H.264 | 1920x1080 @ 4523 kb/s"),
("AUD", "AAC 2.0 | en @ 192 kb/s"),
("SUB", "WebVTT | en (SDH)"),
)
for kind, desc in track_rows:
episode.add(Text.assemble((kind, palette["pink"]), (" | ", guide), (desc, text)), guide_style=guide)
tracks = Panel(listing, title="Available Tracks", box=box.SQUARE, border_style=guide, expand=False)
logs = []
log_rows = (
("INFO", palette["green"], "Downloading 3 tracks"),
("WARNING", palette["yellow"], "Subtitle cues overlapped, fixed 2"),
("ERROR", palette["red"], "License request denied (403)"),
)
for level, level_style, message in log_rows:
line = Text()
line.append("18:00:01 ", style=gray)
line.append(f"{level:<8} ", style=level_style)
line.append(message, style=text if level != "ERROR" else palette["red"])
logs.append(line)
progress = Text()
progress.append("Pilot ", style=text)
progress.append("━" * 24, style=palette["green"])
progress.append("╸", style=palette["green"])
progress.append("━" * 14, style=guide)
progress.append(" 62%", style=palette["yellow"])
progress.append(" 12.4 MB/s", style=palette["cyan"])
progress.append(" 0:00:42", style=text2)
# one frozen frame of GradientPulseBarColumn's dark_gray-to-pink cosine sweep
lo = Color.parse(palette["dark_gray"]).triplet
hi = Color.parse(palette["pink"]).triplet
assert lo and hi
lut = [Style(color=Color.from_triplet(blend_rgb(lo, hi, i / 31))) for i in range(32)]
pulse = Text("Muxing ", style=text)
for i in range(39):
fade = (math.cos((i - 8) * math.tau / 40.0) + 1) / 2
pulse.append("━", style=lut[int(fade * 31)])
block = Group(header, swatch, Text(), docstring, *options, tracks, *logs, Text(), progress, pulse)
console.print(Padding(block, (1, 2, 1, 2)))
console.print(Rule(style=guide, characters="─"))
console.print()
@env.command()
def info() -> None:
"""Displays information about the current environment."""
+53 -22
View File
@@ -1,5 +1,6 @@
import logging
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Optional
@@ -243,6 +244,36 @@ def add(file: Path, service: str, vaults: list[str]) -> None:
log.info("Done!")
def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logger) -> Optional[tuple[str, str]]:
"""Return the (service, key) of the first service table in a vault holding the KID."""
def probe(svc: str) -> Optional[tuple[str, str]]:
try:
key = vault.get_key(kid, svc)
except Exception as e:
log.debug(f"{vault} [{svc}]: lookup error ({e})")
return None
if key and key.count("0") != len(key):
return svc, key
return None
if len(services) == 1:
return probe(services[0])
with ThreadPoolExecutor(max_workers=8) as pool:
futures = [pool.submit(probe, svc) for svc in services]
try:
for future in as_completed(futures):
found = future.result()
if found:
return found
finally:
for future in futures:
future.cancel()
return None
@kv.command()
@click.argument("kid", type=str)
@click.option("-s", "--service", type=str, default=None, help="Limit search to a specific service tag.")
@@ -254,8 +285,10 @@ def search(kid: str, service: Optional[str], vault_name: Optional[str]) -> None:
Search configured Key Vault(s) for a KID and report any matching KEY.
KID must be 32 hex characters (no dashes). If --service is omitted, every
service table in each vault is scanned. If --vault is omitted, every
vault in the config is searched.
service table in each vault is scanned; vaults that cannot list their
tables are probed with every locally installed service tag instead, so
passing --service is much faster. If --vault is omitted, every vault in
the config is searched.
"""
log = logging.getLogger("kv")
@@ -274,8 +307,9 @@ def search(kid: str, service: Optional[str], vault_name: Optional[str]) -> None:
service_tag = Services.get_tag(service) if service else None
hit: Optional[tuple[str, str, str]] = None
hits: list[tuple[str, str, str]] = []
for vault in vaults_:
probed = False
if service_tag:
services_to_check: list[str] = [service_tag]
else:
@@ -285,28 +319,25 @@ def search(kid: str, service: Optional[str], vault_name: Optional[str]) -> None:
log.debug(f"{vault}: get_services() failed ({e})")
services_to_check = []
if not services_to_check:
log.warning(f"{vault}: cannot search without a service (remote vault requires --service). Skipping.")
continue
services_to_check = list(Services.get_tags())
probed = True
log.debug(f"{vault}: cannot list tables, probing {len(services_to_check)} local service tag(s)")
for svc in services_to_check:
try:
key = vault.get_key(kid_norm, svc)
except Exception as e:
log.debug(f"{vault} [{svc}]: lookup error ({e})")
continue
if key and key.count("0") != len(key):
hit = (vault.name, svc, key)
break
if hit:
break
found = search_vault(vault, kid_norm, services_to_check, log)
if found:
svc_hit, key_hit = found
hits.append((vault.name, f"{svc_hit}?" if probed else svc_hit, key_hit))
if hit:
vname, svc, key = hit
tree = Tree(Text.assemble((svc, "cyan"), (f"({vname})", "text"), overflow="fold"))
tree.add(f"[text2]{kid_norm}:{key}")
console.print(Padding(tree, (1, 5)))
else:
if not hits:
log.info(f"KID {kid_norm} not found in {len(vaults_)} vault(s).")
return
for svc in dict.fromkeys(svc for _, svc, _ in hits):
tree = Tree(Text.assemble((svc, "cyan"), overflow="fold"))
for vname, hit_svc, key in hits:
if hit_svc == svc:
tree.add(f"[text2]{kid_norm}:{key} from {vname}")
console.print(Padding(tree, (1, 5)))
@kv.command()
+17 -4
View File
@@ -8,6 +8,7 @@ from aiohttp import web
from unshackle.core import binaries
from unshackle.core.api import cors_middleware, setup_routes, setup_swagger
from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.handlers import request_secret_key
from unshackle.core.config import config
from unshackle.core.constants import context_settings
from unshackle.core.downloaders import format_speed, parse_speed_limit, set_speed_limit
@@ -130,11 +131,11 @@ def serve(
config.serve["playready_devices"].extend(list(config.directories.prds.glob("*.prd")))
@web.middleware
async def api_key_authentication(request: web.Request, handler) -> web.Response:
async def api_key_authentication(request: web.Request, handler) -> web.StreamResponse:
"""Authenticate API requests using X-Secret-Key header."""
if request.path == "/api/health":
return await handler(request)
secret_key = request.headers.get("X-Secret-Key")
secret_key = request_secret_key(request)
if not secret_key:
return web.json_response({"status": 401, "message": "Secret Key is Empty."}, status=401)
# Constant-time compare against every configured key so a valid key can't be
@@ -159,6 +160,10 @@ def serve(
if global_services:
log.info(f"Global service allowlist: {', '.join(global_services)}")
users = config.serve.get("users", {})
if isinstance(users, dict):
# yaml keys can parse as int; hmac.compare_digest and allowlist lookups need str
users = {str(k): v for k, v in users.items()}
config.serve["users"] = users
for user_key, user_cfg in users.items() if isinstance(users, dict) else []:
user_services = user_cfg.get("services") if isinstance(user_cfg, dict) else None
if user_services:
@@ -172,7 +177,10 @@ def serve(
app["config"] = {"users": {}}
else:
app = web.Application(middlewares=[cors_middleware, api_key_authentication, compression_middleware])
app["config"] = {"users": {api_secret: {"devices": [], "username": "api_user"}}}
api_users: dict = {api_secret: {"devices": [], "username": "api_user"}}
if isinstance(users, dict):
api_users.update(users)
app["config"] = {"users": api_users}
app["debug_api"] = debug_api
# Start session cleanup loop for remote-dl sessions
@@ -238,9 +246,14 @@ def serve(
def create_serve_authentication(serve_playready_flag: bool):
@web.middleware
async def serve_authentication(request: web.Request, handler) -> web.Response:
async def serve_authentication(request: web.Request, handler) -> web.StreamResponse:
secret_key = request_secret_key(request)
if serve_playready_flag and request.path in ("/playready", "/playready/"):
response = await handler(request)
elif secret_key and not request.headers.get("X-Secret-Key"):
if not any(hmac.compare_digest(secret_key, k) for k in request.app["config"]["users"]):
return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401)
response = await handler(request)
else:
response = await pywidevine_serve.authentication(request, handler)
+5 -1
View File
@@ -3,7 +3,11 @@ import os
from pathlib import Path
from typing import Callable, Optional
__version__ = "5.3.0"
from rich_click.patch import patch as _patch_click_help
_patch_click_help()
__version__ = "5.4.0"
_PKG = Path(__file__).parent.parent
# Framework code only. Services are user-swappable, so they are not part of the identity.
+5 -2
View File
@@ -25,10 +25,13 @@ def safe_inflate(data: bytes, max_size: int = MAX_INFLATE_BYTES) -> bytes:
@web.middleware
async def compression_middleware(request: web.Request, handler) -> web.Response:
async def compression_middleware(request: web.Request, handler) -> web.StreamResponse:
"""Compress JSON responses with gzip when the client supports it."""
response = await handler(request)
if not isinstance(response, web.Response):
return response
accept_encoding = request.headers.get("Accept-Encoding", "")
if "gzip" not in accept_encoding:
return response
@@ -37,7 +40,7 @@ async def compression_middleware(request: web.Request, handler) -> web.Response:
return response
body = response.body
if body is None or len(body) < 256:
if not isinstance(body, (bytes, bytearray)) or len(body) < 256:
return response
from unshackle.core.config import config
+55
View File
@@ -623,6 +623,7 @@ class DownloadQueueManager:
self._job_temp_files: Dict[str, Dict[str, str]] = {}
self._workers_started = False
self._shutdown_event = asyncio.Event()
self._subscribers: Dict[str, List[asyncio.Queue]] = {}
log.info(
f"Initialized download queue manager: max_concurrent={max_concurrent_downloads}, retention_hours={job_retention_hours}"
@@ -655,6 +656,48 @@ class DownloadQueueManager:
"""List all jobs."""
return list(self._jobs.values())
def subscribe(self, job_id: str) -> asyncio.Queue:
"""Register a listener for a job's events, returning the queue it receives them on."""
queue: asyncio.Queue = asyncio.Queue(maxsize=100)
self._subscribers.setdefault(job_id, []).append(queue)
return queue
def unsubscribe(self, job_id: str, queue: asyncio.Queue) -> None:
"""Drop a listener registered by subscribe()."""
queues = self._subscribers.get(job_id)
if not queues:
return
with suppress(ValueError):
queues.remove(queue)
if not queues:
del self._subscribers[job_id]
def _publish(self, job: DownloadJob, event: str) -> None:
"""Fan an event carrying the job's full detail dict out to every listener."""
queues = self._subscribers.get(job.job_id)
if not queues:
return
payload = {"event": event, "data": job.to_dict(include_full_details=True)}
for queue in queues:
self._put(queue, payload)
def _publish_terminal(self, job: DownloadJob) -> None:
"""Publish a job's final state, then close every listener's stream."""
self._publish(job, job.status.value)
for queue in self._subscribers.pop(job.job_id, []):
self._put(queue, None)
@staticmethod
def _put(queue: asyncio.Queue, item: Optional[Dict[str, Any]]) -> None:
"""Enqueue an item, discarding the oldest when a slow listener has filled the queue."""
try:
queue.put_nowait(item)
except asyncio.QueueFull:
with suppress(asyncio.QueueEmpty):
queue.get_nowait()
with suppress(asyncio.QueueFull):
queue.put_nowait(item)
def cancel_job(self, job_id: str) -> bool:
"""Cancel a job if it's queued or downloading."""
job = self._jobs.get(job_id)
@@ -666,6 +709,7 @@ class DownloadQueueManager:
job.cancel_event.set() # Signal cancellation
job.completed_time = datetime.now()
record_job_history(job) # queued jobs never reach a worker, so persist here
self._publish_terminal(job)
log.info(f"Cancelled queued job {sanitize_log(job_id)}")
return True
elif job.status == JobStatus.DOWNLOADING:
@@ -763,6 +807,11 @@ class DownloadQueueManager:
log.info("Shutting down download queue manager")
self._shutdown_event.set()
for queues in list(self._subscribers.values()):
for queue in queues:
self._put(queue, None)
self._subscribers.clear()
# Cancel all active downloads
for task in self._active_downloads.values():
task.cancel()
@@ -819,6 +868,7 @@ class DownloadQueueManager:
# Start processing the job
job.status = JobStatus.DOWNLOADING
job.started_time = datetime.now()
self._publish(job, "status")
log.info(f"Worker {worker_name} starting job {job.job_id}")
@@ -838,6 +888,7 @@ class DownloadQueueManager:
finally:
job.completed_time = datetime.now()
record_job_history(job)
self._publish_terminal(job)
if job.job_id in self._active_downloads:
del self._active_downloads[job.job_id]
@@ -913,6 +964,7 @@ class DownloadQueueManager:
stdout_bytes = b""
stderr_bytes = b""
last_published: Optional[Dict[str, Any]] = None
try:
while True:
@@ -957,6 +1009,9 @@ class DownloadQueueManager:
if new_progress != job.progress:
job.progress = new_progress
log.info(f"Job {job.job_id} progress updated: {job.progress}%")
if progress_data != last_published:
last_published = progress_data
self._publish(job, "progress")
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
log.debug(f"Could not read progress for job {job.job_id}: {e}")
+5 -2
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import logging
import os
import sys
import traceback
from pathlib import Path
@@ -20,9 +21,11 @@ def _read_payload(path: Path) -> Dict[str, Any]:
def _write_result(path: Path, payload: Dict[str, Any]) -> None:
# Atomic replace: the parent polls this file while it is being rewritten.
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
json.dump(payload, handle)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(payload), encoding="utf-8")
os.replace(tmp, path)
def main(argv: list[str]) -> int:
+124 -6
View File
@@ -263,7 +263,7 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
key_set: Optional[set[str]] = None
if request:
secret_key = request.headers.get("X-Secret-Key")
secret_key = request_secret_key(request)
if secret_key:
users = config.serve.get("users", {})
user_config = users.get(secret_key, {})
@@ -283,9 +283,47 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
return list(result)
def server_cdm_allowed(request: Optional[web.Request] = None) -> bool:
"""Whether the calling key may have the server run the CDM licensing.
Configured keys opt in with ``server_cdm: true``; keys absent from
``serve.users`` (the admin secret) keep full access.
"""
if not request:
return True
secret_key = request_secret_key(request)
user_config = config.serve.get("users", {}).get(secret_key)
if user_config is None:
return True
return bool(user_config.get("server_cdm", False))
JOB_EVENTS_ROUTE = "/api/download/jobs/{job_id}/events"
CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, X-Secret-Key, Authorization",
"Access-Control-Max-Age": "3600",
}
def request_secret_key(request: web.Request) -> Optional[str]:
"""The caller's key: the X-Secret-Key header, or on the events route the secret_key
query param (EventSource cannot send headers)."""
key = request.headers.get("X-Secret-Key")
if not key:
resource = request.match_info.route.resource
if resource is not None and resource.canonical == JOB_EVENTS_ROUTE:
key = request.query.get("secret_key")
return key
def caller_key(request: Optional[web.Request] = None) -> str:
"""The authenticating X-Secret-Key for a request, or 'anonymous' when unauthenticated."""
return request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
"""The authenticating key for a request, or 'anonymous' when unauthenticated."""
if not request:
return "anonymous"
return request_secret_key(request) or "anonymous"
def owns_job(job: Any, request: Optional[web.Request] = None) -> bool:
@@ -1011,7 +1049,7 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
return None
def enforce_download_gates(params: Dict[str, Any]) -> None:
def enforce_download_gates(params: Dict[str, Any], request: Optional[web.Request] = None) -> None:
"""Enforce serve-config gates on per-job cdm overrides and client-supplied credentials.
A per-request `cdm` selects a server-side device, so it is gated here rather than honoured
@@ -1020,7 +1058,15 @@ def enforce_download_gates(params: Dict[str, Any]) -> None:
A per-request `credential` (or `credentials` map) authenticates the job with client-supplied
secrets instead of the server-side credentials. Gate it behind `serve.allow_job_credentials`
(default off) so a default deployment stays locked to its own credentials; mirrors the CDM gate.
A download job licenses DRM in-process with the server's own CDM, so a key without
``server_cdm`` cannot submit or retry jobs.
"""
if not server_cdm_allowed(request):
raise APIError(
APIErrorCode.FORBIDDEN,
"Download jobs license with the server CDM, which is not enabled for this key.",
)
requested_cdm = params.get("cdm")
if requested_cdm:
allowed = (config.serve or {}).get("cdm_overrides")
@@ -1064,7 +1110,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
details={"service": normalized_service, "title_id": title_id},
)
enforce_download_gates(data)
enforce_download_gates(data, request)
try:
# Load service module to extract service-specific parameter defaults
@@ -1214,6 +1260,71 @@ async def get_download_job_handler(job_id: str, request: Optional[web.Request] =
)
async def download_job_events_handler(job_id: str, request: web.Request) -> web.StreamResponse:
"""Stream a download job's progress to the caller as Server-Sent Events."""
import json
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
manager = get_download_manager()
job = manager.get_job(job_id)
if not job or not owns_job(job, request):
raise APIError(
APIErrorCode.JOB_NOT_FOUND,
"Job not found",
details={"job_id": job_id},
)
response = web.StreamResponse(
headers={
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
# Stops nginx from buffering the stream.
"X-Accel-Buffering": "no",
**CORS_HEADERS,
}
)
await response.prepare(request)
async def send(event: str, data: Dict[str, Any]) -> None:
payload = json.dumps(data, separators=(",", ":"), default=str)
await response.write(f"event: {event}\ndata: {payload}\n\n".encode())
queue: Optional[asyncio.Queue] = None
get_task: Optional[asyncio.Task] = None
try:
await send("snapshot", job.to_dict(include_full_details=True))
if job.status not in TERMINAL_STATUSES:
queue = manager.subscribe(job_id)
if queue is None or job.status in TERMINAL_STATUSES:
await send(job.status.value, job.to_dict(include_full_details=True))
return response
while True:
if get_task is None:
get_task = asyncio.create_task(queue.get())
done, _ = await asyncio.wait({get_task}, timeout=15)
if not done:
await response.write(b": keep-alive\n\n")
continue
item = get_task.result()
get_task = None
if item is None:
break
await send(item["event"], item["data"])
except (ConnectionResetError, asyncio.CancelledError):
log.debug(f"SSE client disconnected from job {sanitize_log(job_id)}")
finally:
if get_task is not None:
get_task.cancel()
if queue is not None:
manager.unsubscribe(job_id, queue)
return response
async def cancel_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
"""Handle cancel/remove download job request."""
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
@@ -1308,7 +1419,7 @@ async def retry_download_job_handler(job_id: str, request: Optional[web.Request]
f"Invalid or unavailable service: {job.service}",
details={"service": job.service},
)
enforce_download_gates(job.parameters)
enforce_download_gates(job.parameters, request)
await manager.start_workers()
@@ -2034,6 +2145,7 @@ async def session_tracks_handler(
"manifests": manifests,
"session_headers": session_headers,
"session_cookies": session_cookies,
"server_cdm": server_cdm_allowed(request),
"server_cdm_type": server_cdm_type,
}
)
@@ -2654,6 +2766,12 @@ async def session_license_handler(
drm_type = data.get("drm_type", "widevine")
mode = data.get("mode", "proxy")
if mode == "server_cdm" and not server_cdm_allowed(request):
raise APIError(
APIErrorCode.FORBIDDEN,
"Server CDM licensing is not enabled for this key. Use a local CDM (proxy mode).",
)
if mode == "server_cdm" and track_ids:
from unshackle.core.config import config as app_config
+48 -8
View File
@@ -11,6 +11,8 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
from unshackle.core import __code_hash__, __version__
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
from unshackle.core.api.handlers import (
CORS_HEADERS,
JOB_EVENTS_ROUTE,
cancel_download_job_handler,
clear_cache_handler,
clear_finished_download_jobs_handler,
@@ -18,6 +20,7 @@ from unshackle.core.api.handlers import (
delete_history_handler,
download_handler,
download_history_handler,
download_job_events_handler,
env_check_handler,
get_allowed_services,
get_download_job_handler,
@@ -56,26 +59,22 @@ async def cors_middleware(
else:
response = await handler(request)
# Add CORS headers
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Secret-Key, Authorization"
response.headers["Access-Control-Max-Age"] = "3600"
response.headers.update(CORS_HEADERS)
return response
log = logging.getLogger("api")
# Route handler signature: takes the request, returns a response.
Handler = Callable[[web.Request], Awaitable[web.Response]]
# Route handler signature: takes the request, returns a response (streamed or complete).
Handler = Callable[[web.Request], Awaitable[web.StreamResponse]]
def api_handler(handler: Handler) -> Handler:
"""Wrap a route handler so any raised APIError becomes a structured error response."""
@functools.wraps(handler)
async def wrapper(request: web.Request) -> web.Response:
async def wrapper(request: web.Request) -> web.StreamResponse:
try:
return await handler(request)
except APIError as e:
@@ -956,6 +955,46 @@ async def download_job_detail(request: web.Request) -> web.Response:
return await get_download_job_handler(job_id, request)
@api_handler
async def download_job_events(request: web.Request) -> web.StreamResponse:
"""
Stream download job events.
---
summary: Stream download job events
description: >
Server-Sent Events stream of a job's progress. Emits a `snapshot` event, then
`progress` and `status` events, and closes after the terminal `completed`, `failed`
or `cancelled` event. Every event carries the same full job object that
GET /api/download/jobs/{job_id} returns. A browser EventSource can authenticate with
the `secret_key` query parameter instead of the X-Secret-Key header; when both are
sent the header is used.
parameters:
- name: job_id
in: path
required: true
schema:
type: string
- name: secret_key
in: query
required: false
schema:
type: string
responses:
'200':
description: Event stream
content:
text/event-stream:
schema:
type: string
'404':
description: Job not found
'500':
description: Server error
"""
job_id = request.match_info["job_id"]
return await download_job_events_handler(job_id, request)
@api_handler
async def cancel_download_job(request: web.Request) -> web.Response:
"""
@@ -1801,6 +1840,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
("GET", "/api/download/jobs", download_jobs, False),
("POST", "/api/download/jobs/clear-finished", clear_finished_download_jobs, False),
("GET", "/api/download/jobs/{job_id}", download_job_detail, False),
("GET", JOB_EVENTS_ROUTE, download_job_events, False),
("DELETE", "/api/download/jobs/{job_id}", cancel_download_job, False),
("POST", "/api/download/jobs/{job_id}/retry", retry_download_job, False),
("POST", "/api/download/jobs/{job_id}/priority", prioritize_download_job, False),
+5 -6
View File
@@ -23,12 +23,12 @@ def load_command(path: Path) -> object:
try:
module = import_module_by_path(path)
except Exception as e:
raise RuntimeError(f"{path.stem}: failed to import — {type(e).__name__}: {e} ({path})") from e
raise RuntimeError(f"{path.stem}: failed to import - {type(e).__name__}: {e} ({path})") from e
try:
return getattr(module, path.stem)
except AttributeError as e:
raise RuntimeError(
f"{path.stem}: no object named '{path.stem}' found in {path} — it must match the filename"
f"{path.stem}: no object named '{path.stem}' found in {path} - it must match the filename"
) from e
@@ -74,10 +74,9 @@ class Commands(click.Group):
if not module:
raise click.ClickException(f"Unable to find command by the name '{name}'")
if hasattr(module, "cli"):
return module.cli
return module
cmd = module.cli if hasattr(module, "cli") else module
cmd.name = name
return cmd
# Hide direct access to commands from quick import form, they shouldn't be accessed directly
+1
View File
@@ -110,6 +110,7 @@ class Config:
self.decryption_map = {}
self.decryption = decryption_cfg or "shaka"
self.theme: str = kwargs.get("theme") or "default"
self.set_terminal_bg: bool = kwargs.get("set_terminal_bg", False)
self.tag: str = kwargs.get("tag") or ""
self.tag_group_name: bool = kwargs.get("tag_group_name", True)
+11 -19
View File
@@ -21,6 +21,7 @@ from rich.text import Text, TextType
from rich.theme import Theme
from unshackle.core.config import config
from unshackle.core.themes import DEFAULT_THEME, PALETTES, apply_help_theme, resolve_palette
class ComfyLogRenderer(LogRender):
@@ -317,25 +318,16 @@ class ComfyConsole(Console):
live.start()
catppuccin_mocha = {
# Colors based on "CatppuccinMocha" from Gogh themes
"bg": "rgb(30,30,46)",
"text": "rgb(205,214,244)",
"text2": "rgb(162,169,193)", # slightly darker
"black": "rgb(69,71,90)",
"bright_black": "rgb(88,91,112)",
"red": "rgb(243,139,168)",
"green": "rgb(166,227,161)",
"yellow": "rgb(249,226,175)",
"blue": "rgb(137,180,250)",
"pink": "rgb(245,194,231)",
"cyan": "rgb(148,226,213)",
"gray": "rgb(166,173,200)",
"bright_gray": "rgb(186,194,222)",
"dark_gray": "rgb(54,54,84)",
}
primary_scheme = catppuccin_mocha
primary_scheme = resolve_palette(config.theme)
if primary_scheme is None:
logging.getLogger("console").warning(
"Unknown theme %r, falling back to %s (available: %s)",
config.theme,
DEFAULT_THEME,
", ".join(PALETTES),
)
primary_scheme = dict(PALETTES[DEFAULT_THEME])
apply_help_theme(primary_scheme)
primary_scheme["none"] = primary_scheme["text"]
primary_scheme["grey23"] = primary_scheme["black"]
primary_scheme["magenta"] = primary_scheme["pink"]
+57 -13
View File
@@ -349,20 +349,16 @@ class DASH:
if period_count > 1:
log.debug(f"Multi-period manifest detected with {period_count} content periods")
stored_period: Optional[Element] = track.data["dash"].get("period")
for period_idx, content_period in enumerate(content_periods):
# Find the matching representation in this period
matched_rep = None
matched_as = None
for as_ in content_period.findall("AdaptationSet"):
if DASH.is_trick_mode(as_):
continue
for rep in as_.findall("Representation"):
if rep.get("id") == rep_id:
matched_rep = rep
matched_as = as_
break
if matched_rep is not None:
break
if content_period is stored_period:
matched_as, matched_rep = adaptation_set, representation
else:
matched_as, matched_rep = DASH.resolve_representation(content_period, rep_id, adaptation_set) or (
None,
None,
)
if matched_rep is None or matched_as is None:
period_id = content_period.get("id", period_idx)
@@ -934,6 +930,54 @@ class DASH:
for prop in essential_props + supplemental_props
)
@staticmethod
def adaptation_set_key(adaptation_set: Element) -> tuple[Optional[str], ...]:
"""Identity of an AdaptationSet, used to re-find its counterpart in another Period."""
return tuple(
adaptation_set.get(attr)
for attr in ("contentType", "mimeType", "lang", "audioTrackId", "audioTrackSubtype", "id")
)
@staticmethod
def resolve_representation(
period: Element, rep_id: Optional[str], adaptation_set: Element
) -> Optional[tuple[Element, Element]]:
"""
Find the (AdaptationSet, Representation) in another Period matching rep_id.
Representation ids are only unique within an AdaptationSet, so the set matching
`adaptation_set`'s identity wins over an earlier sibling that reuses the same id
for different content (e.g. audio description vs dialog).
"""
as_key = DASH.adaptation_set_key(adaptation_set)
def candidates(within: Element) -> list[tuple[Element, Element]]:
found = []
for as_ in within.findall("AdaptationSet"):
if DASH.is_trick_mode(as_) or DASH.adaptation_set_key(as_) != as_key:
continue
for rep in as_.findall("Representation"):
if rep.get("id") == rep_id:
found.append((as_, rep))
break
return found
matches = candidates(period)
if matches:
parent = adaptation_set.getparent()
siblings = [as_ for as_, _ in candidates(parent)] if parent is not None else []
ordinal = siblings.index(adaptation_set) if adaptation_set in siblings else 0
return matches[min(ordinal, len(matches) - 1)]
for as_ in period.findall("AdaptationSet"):
if DASH.is_trick_mode(as_):
continue
for rep in as_.findall("Representation"):
if rep.get("id") == rep_id:
return as_, rep
return None
@staticmethod
def is_descriptive(adaptation_set: Element) -> bool:
"""Check if contents of Adaptation Set is Descriptive."""
+2 -1
View File
@@ -14,6 +14,7 @@ from io import BytesIO
from typing import Any, Optional
# RenderableType is rich's union of "things that can be printed to a console".
from rich import box
from rich.console import Group, RenderableType
from rich.padding import Padding
from rich.panel import Panel
@@ -145,7 +146,7 @@ def render_track_panel(rows: list[TrackRow], total: int) -> Panel:
detail.append(" | ")
detail.append("Hi-Res", style="gold1")
node.add(detail, guide_style="bright_black")
return Panel(tree, title="Available Tracks")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
def render_album_header(
+3 -2
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
from typing import Any, Optional
from rich import box
from rich.console import Group, RenderableType
from rich.markup import escape
from rich.panel import Panel
@@ -112,7 +113,7 @@ class MusicRenderer:
suffix = "s" if hidden != 1 else ""
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
return Panel(tree, title="Available Tracks")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
def render_plan_header(self, plan: MusicDownloadPlan) -> Optional[Table]:
title = plan.title
@@ -174,7 +175,7 @@ class MusicRenderer:
suffix = "s" if hidden != 1 else ""
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
return Panel(tree, title="Available Tracks")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
@staticmethod
def _metadata_grid() -> Table:
+60 -13
View File
@@ -37,6 +37,8 @@ log = logging.getLogger("remote_service")
SENSITIVE_DATA_KEYS = ("credential", "credentials", "password", "token", "api_key")
DEFAULT_AUTH_HEADERS = ["X-Secret-Key", "X-Api-Key"]
def redact_secrets(text: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Mask URL userinfo and any request-payload secrets before the text is logged."""
@@ -47,9 +49,11 @@ def redact_secrets(text: str, data: Optional[Dict[str, Any]] = None) -> str:
class RemoteClient:
"""HTTP client for the unshackle serve API."""
def __init__(self, server_url: str, api_key: str) -> None:
def __init__(self, server_url: str, api_key: str, auth_headers: Optional[list[str]] = None) -> None:
self.server_url = server_url.rstrip("/")
self.api_key = api_key
self.auth_headers = list(auth_headers) if auth_headers else list(DEFAULT_AUTH_HEADERS)
self._auth_header_index = 0
self._session: Optional[requests.Session] = None
@property
@@ -60,20 +64,35 @@ class RemoteClient:
self._session = requests.Session()
self._session.headers["User-Agent"] = f"unshackle/{__version__}"
if self.api_key:
self._session.headers["X-Secret-Key"] = self.api_key
self._session.headers[self.auth_headers[self._auth_header_index]] = self.api_key
return self._session
def _next_auth_header(self) -> bool:
"""Move the api key onto the next candidate header. False once they are exhausted."""
if not self.api_key or self._auth_header_index + 1 >= len(self.auth_headers):
return False
session = self.session
session.headers.pop(self.auth_headers[self._auth_header_index], None)
self._auth_header_index += 1
session.headers[self.auth_headers[self._auth_header_index]] = self.api_key
return True
def _request(self, method: str, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
url = f"{self.server_url}{endpoint}"
try:
resp = getattr(self.session, method)(url, json=data, timeout=120 if method == "post" else 30)
except requests.ConnectionError:
server_url = safe_display_url(self.server_url)
log.error(f"Could not connect to remote server at {server_url}. Is it running? (unshackle serve)")
raise SystemExit(1)
except requests.Timeout:
log.error(f"Request to remote server timed out: {endpoint}")
raise SystemExit(1)
while True:
try:
resp = getattr(self.session, method)(url, json=data, timeout=120 if method == "post" else 30)
except requests.ConnectionError:
server_url = safe_display_url(self.server_url)
log.error(f"Could not connect to remote server at {server_url}. Is it running? (unshackle serve)")
raise SystemExit(1)
except requests.Timeout:
log.error(f"Request to remote server timed out: {endpoint}")
raise SystemExit(1)
# servers differ on which header carries the key, so retry the rest before giving up
if resp.status_code == 401 and self._next_auth_header():
continue
break
result = resp.json()
if resp.status_code >= 400:
error_msg = redact_secrets(str(result.get("message", resp.text)), data)
@@ -319,8 +338,31 @@ def _build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Un
return title
def _resolve_auth_headers(svc: dict, server_name: str) -> list[str]:
"""Configured header names first, then the defaults as fallbacks."""
auth_headers = svc.get("auth_headers")
if auth_headers is None:
return list(DEFAULT_AUTH_HEADERS)
if (
not isinstance(auth_headers, list)
or not auth_headers
or not all(isinstance(h, str) and h.strip() for h in auth_headers)
):
raise click.ClickException(
f"Remote service '{server_name}': 'auth_headers' must be a list of header names, e.g.\n\n"
' auth_headers: ["Authorization"]'
)
resolved = [h.strip() for h in auth_headers]
seen = {h.lower() for h in resolved}
resolved.extend(h for h in DEFAULT_AUTH_HEADERS if h.lower() not in seen)
return resolved
def resolve_server(server_name: Optional[str]) -> tuple[str, str, dict]:
"""Resolve server URL, API key, and per-service config from remote_services."""
"""Resolve server URL, API key, and per-service config from remote_services.
The per-service config carries the ``_auth_headers`` candidate list for RemoteClient.
"""
remote_services = config.remote_services
if not remote_services:
raise click.ClickException(
@@ -338,6 +380,7 @@ def resolve_server(server_name: Optional[str]) -> tuple[str, str, dict]:
raise click.ClickException(f"Remote service '{server_name}' not found. Available: {available}")
services = svc.get("services", {})
services["_server_cdm"] = svc.get("server_cdm", False)
services["_auth_headers"] = _resolve_auth_headers(svc, server_name)
return svc["url"], svc.get("api_key", ""), services
if len(remote_services) == 1:
@@ -345,6 +388,7 @@ def resolve_server(server_name: Optional[str]) -> tuple[str, str, dict]:
log.info(f"Using remote service: {name}")
services = svc.get("services", {})
services["_server_cdm"] = svc.get("server_cdm", False)
services["_auth_headers"] = _resolve_auth_headers(svc, name)
return svc["url"], svc.get("api_key", ""), services
available = ", ".join(remote_services.keys())
@@ -415,7 +459,7 @@ class RemoteService:
self.service_tag = service_tag
self.title_id = title_id
self.client = RemoteClient(server_url, api_key)
self.client = RemoteClient(server_url, api_key, services_config.get("_auth_headers"))
self.ctx = ctx
self._service_params = service_params or {}
self.log = logging.getLogger(service_tag)
@@ -618,6 +662,9 @@ class RemoteService:
_resolve_manifest_data(tracks, result.get("manifests", []))
if self._server_cdm and not result.get("server_cdm", True):
self._server_cdm = False
self.log.warning("Server CDM licensing is not enabled for this key, using the local CDM")
self._server_cdm_type = result.get("server_cdm_type", "widevine")
self._tracks_by_title[title_id] = tracks
+34 -10
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import inspect
import logging
import re
from pathlib import Path
@@ -17,7 +18,7 @@ log = logging.getLogger("services")
_raw = config.directories.services
if not isinstance(_raw, list):
_raw = [_raw]
# resolve in config order — priority IS list order: the first source to define a tag is the source,
# resolve in config order - priority IS list order: the first source to define a tag is the source,
# later sources (local or repo) with the same tag are shadowed. List local last to make it a fallback.
_service_dirs: list[Path] = []
DIRTY_REPOS: list[str] = []
@@ -26,7 +27,7 @@ for _entry in _raw:
try:
_resolved = resolve_service_repo(_entry)
except DirtyServiceRepo as e:
# local edits in the clone — record it and let check_load_errors() exit cleanly
# local edits in the clone - record it and let check_load_errors() exit cleanly
DIRTY_REPOS.append(redact_path(str(e.path)))
_resolved = None
if _resolved:
@@ -59,12 +60,12 @@ def load_service(path: Path) -> object:
try:
module = import_module_by_path(path)
except Exception as e:
raise RuntimeError(f"{tag}: failed to import — {type(e).__name__}: {e} ({path})") from e
raise RuntimeError(f"{tag}: failed to import - {type(e).__name__}: {e} ({path})") from e
try:
return getattr(module, tag)
except AttributeError as e:
raise RuntimeError(
f"{tag}: no class named '{tag}' found in {path} — the class name must match the directory name"
f"{tag}: no class named '{tag}' found in {path} - the class name must match the directory name"
) from e
@@ -101,12 +102,12 @@ def check_load_errors() -> None:
is rendered once by Click, without a traceback and without cascading through
every command that imports this module. Duplicate services (a tag also served by an
earlier, higher-priority source, which is ignored) are summarised here; the full
list — naming the path used and the duplicate ignored — is debug-only.
list - naming the path used and the duplicate ignored - is debug-only.
"""
if DIRTY_REPOS:
joined = "\n".join(f" - {p}" for p in DIRTY_REPOS)
raise click.ClickException(
"Service repo has local changes — refusing to refresh so your edits are not lost.\n"
"Service repo has local changes - refusing to refresh so your edits are not lost.\n"
"Commit and push them to the upstream repo (or revert them), then retry:\n" + joined
)
global _SUMMARY_LOGGED
@@ -191,10 +192,28 @@ class Services(click.Group):
raise click.ClickException(f"{e}. Available Services: {', '.join(available_services)}")
if hasattr(service, "cli"):
return service.cli
cli = service.cli
cli.name = tag
doc = service.__doc__
if doc and doc.strip() and cli.help in (None, "", doc):
cli.help = Services._docstring_help(doc)
return cli
raise click.ClickException(f"Service '{tag}' has no 'cli' method configured.")
@staticmethod
def _docstring_help(doc: str) -> str:
"""Format a service docstring for Click help, one \\b per paragraph so Click keeps the layout.
The first paragraph stays unprefixed: it is the summary line, and a \\b there
renders as a stray blank line and empties click's derived short help.
"""
doc = inspect.cleandoc(doc)
if "\b" in doc:
return doc
first, *rest = doc.split("\n\n")
return "\n\n".join([first] + [f"\b\n{p}" for p in rest])
@staticmethod
def _fetch_remote_services(ctx: click.Context) -> list[dict] | None:
"""Fetch the service list from the remote server (cached per process)."""
@@ -204,11 +223,13 @@ class Services(click.Group):
from unshackle.core.remote_service import RemoteClient, resolve_server
server_name = ctx.params.get("server")
server_url, api_key, _ = resolve_server(server_name)
client = RemoteClient(server_url, api_key)
server_url, api_key, services_config = resolve_server(server_name)
client = RemoteClient(server_url, api_key, services_config.get("_auth_headers"))
result = client.get("/api/services")
Services._remote_services_cache = result.get("services", [])
return Services._remote_services_cache
except click.ClickException:
raise
except Exception:
return None
@@ -217,9 +238,12 @@ class Services(click.Group):
"""Create a Click command for a remote service with server-provided options."""
svc_info = Services._fetch_remote_service_info(tag, ctx)
short_help = svc_info.get("url") if svc_info else None
help_text = svc_info.get("help") if svc_info else None
if help_text:
help_text = Services._docstring_help(help_text)
cli_params = svc_info.get("cli_params") if svc_info else None
@click.command(name=tag, short_help=short_help)
@click.command(name=tag, short_help=short_help, help=help_text)
@click.argument("title", type=str)
@click.pass_context
def remote_cli(ctx: click.Context, title: str, **kwargs: object) -> object:
+231
View File
@@ -0,0 +1,231 @@
"""
Named CLI color themes.
Each palette maps the same role keys to colors: `text`/`text2` for body copy, `pink` for the
brand accent, the six ANSI hues, and the gray ramp used for rules and dim details. The active
palette drives both the rich Console theme (banner, logs, progress) and the click help screens,
so a single `theme` config value restyles the whole CLI.
"""
from __future__ import annotations
from rich_click import RichHelpConfiguration
DEFAULT_THEME = "catppuccin-mocha"
PALETTES: dict[str, dict[str, str]] = {
# Colors based on "CatppuccinMocha" from Gogh themes
"catppuccin-mocha": {
"bg": "rgb(30,30,46)",
"text": "rgb(205,214,244)",
"text2": "rgb(162,169,193)", # slightly darker
"black": "rgb(69,71,90)",
"bright_black": "rgb(88,91,112)",
"red": "rgb(243,139,168)",
"green": "rgb(166,227,161)",
"yellow": "rgb(249,226,175)",
"blue": "rgb(137,180,250)",
"pink": "rgb(245,194,231)",
"cyan": "rgb(148,226,213)",
"gray": "rgb(166,173,200)",
"bright_gray": "rgb(186,194,222)",
"dark_gray": "rgb(54,54,84)",
},
# draculatheme.com spec; purple stands in for blue, comment for the dim grays
"dracula": {
"bg": "#282a36",
"text": "#f8f8f2",
"text2": "#b8bfd8",
"black": "#21222c",
"bright_black": "#6272a4",
"red": "#ff5555",
"green": "#50fa7b",
"yellow": "#f1fa8c",
"blue": "#bd93f9",
"pink": "#ff79c6",
"cyan": "#8be9fd",
"gray": "#6272a4",
"bright_gray": "#e9e9f4",
"dark_gray": "#44475a",
},
# nordtheme.com: polar night / snow storm / frost / aurora
"nord": {
"bg": "#2e3440",
"text": "#d8dee9",
"text2": "#9aa4b8",
"black": "#3b4252",
"bright_black": "#4c566a",
"red": "#bf616a",
"green": "#a3be8c",
"yellow": "#ebcb8b",
"blue": "#81a1c1",
"pink": "#b48ead",
"cyan": "#88c0d0",
"gray": "#616e88",
"bright_gray": "#e5e9f0",
"dark_gray": "#434c5e",
},
# github.com/morhetz/gruvbox dark, bright variants
"gruvbox": {
"bg": "#282828",
"text": "#ebdbb2",
"text2": "#bdae93",
"black": "#504945",
"bright_black": "#665c54",
"red": "#fb4934",
"green": "#b8bb26",
"yellow": "#fabd2f",
"blue": "#83a598",
"pink": "#d3869b",
"cyan": "#8ec07c",
"gray": "#928374",
"bright_gray": "#d5c4a1",
"dark_gray": "#3c3836",
},
# Atom One Dark syntax palette
"one-dark": {
"bg": "#282c34",
"text": "#abb2bf",
"text2": "#818896",
"black": "#3b4048",
"bright_black": "#5c6370",
"red": "#e06c75",
"green": "#98c379",
"yellow": "#e5c07b",
"blue": "#61afef",
"pink": "#c678dd",
"cyan": "#56b6c2",
"gray": "#5c6370",
"bright_gray": "#c8ccd4",
"dark_gray": "#3e4451",
},
# github.com/enkia/tokyo-night-vscode-theme, night variant
"tokyo-night": {
"bg": "#1a1b26",
"text": "#c0caf5",
"text2": "#a9b1d6",
"black": "#15161e",
"bright_black": "#414868",
"red": "#f7768e",
"green": "#9ece6a",
"yellow": "#e0af68",
"blue": "#7aa2f7",
"pink": "#bb9af7",
"cyan": "#7dcfff",
"gray": "#565f89",
"bright_gray": "#a9b1d6",
"dark_gray": "#292e42",
},
# classic Monokai; purple stands in for pink, 66d9ef doubles as blue
"monokai": {
"bg": "#272822",
"text": "#f8f8f2",
"text2": "#cfcfc2",
"black": "#2e2e2e",
"bright_black": "#75715e",
"red": "#f92672",
"green": "#a6e22e",
"yellow": "#e6db74",
"blue": "#66d9ef",
"pink": "#ae81ff",
"cyan": "#a1efe4",
"gray": "#a59f85",
"bright_gray": "#cfcfc2",
"dark_gray": "#3e3d32",
},
# flexoki.com dark, 400-level accents
"flexoki": {
"bg": "#100f0f",
"text": "#cecdc3",
"text2": "#878580",
"black": "#282726",
"bright_black": "#403e3c",
"red": "#d14d41",
"green": "#879a39",
"yellow": "#d0a215",
"blue": "#4385be",
"pink": "#ce5d97",
"cyan": "#3aa99f",
"gray": "#6f6e69",
"bright_gray": "#b7b5ac",
"dark_gray": "#343331",
},
# ethanschoonover.com/solarized dark; magenta stands in for pink
"solarized-dark": {
"bg": "#002b36",
"text": "#839496",
"text2": "#586e75",
"black": "#073642",
"bright_black": "#586e75",
"red": "#dc322f",
"green": "#859900",
"yellow": "#b58900",
"blue": "#268bd2",
"pink": "#d33682",
"cyan": "#2aa198",
"gray": "#657b83",
"bright_gray": "#93a1a1",
"dark_gray": "#073642",
},
}
ALIASES = {
"default": DEFAULT_THEME,
"catppuccin": DEFAULT_THEME,
"mocha": DEFAULT_THEME,
"onedark": "one-dark",
"tokyonight": "tokyo-night",
"solarized": "solarized-dark",
}
def resolve_palette(name: object) -> dict[str, str] | None:
"""Look up a palette by theme name or alias, case-insensitively.
Takes any YAML scalar since config values are unvalidated; non-strings never match.
Returns a copy: console.py extends the active palette in place, and that must
not pollute the master definitions.
"""
key = str(name or "").strip().lower().replace("_", "-")
palette = PALETTES.get(ALIASES.get(key, key))
return dict(palette) if palette else None
def build_help_config(palette: dict[str, str]) -> RichHelpConfiguration:
"""Build the rich-click help styling for a palette."""
return RichHelpConfiguration(
style_option=palette["text"],
style_switch=palette["green"],
style_argument=palette["cyan"],
style_command=palette["pink"],
style_metavar=palette["yellow"],
style_metavar_separator=f"dim {palette['gray']}",
style_usage=palette["yellow"],
style_usage_command=palette["text"],
style_helptext_first_line=palette["text"],
style_helptext=palette["text2"],
style_option_help=palette["text"],
style_command_help=palette["text"],
style_option_default=f"dim {palette['gray']}",
style_option_envvar=f"dim {palette['yellow']}",
style_required_short=palette["red"],
style_required_long=f"dim {palette['red']}",
style_errors_suggestion=palette["text2"],
style_aborted=palette["red"],
style_options_panel_box=None,
style_options_panel_border=palette["pink"],
style_options_panel_title_style=palette["pink"],
style_commands_panel_box=None,
style_commands_panel_border=palette["pink"],
style_commands_panel_title_style=palette["pink"],
style_errors_panel_box="SQUARE",
style_errors_panel_border=palette["red"],
style_options_table_box="HORIZONTALS",
style_options_table_show_lines=True,
style_options_table_border_style=palette["dark_gray"],
)
def apply_help_theme(palette: dict[str, str]) -> None:
"""Point the patched click help renderer at this palette (read at render time)."""
build_help_config(palette).dump_to_globals()
+3
View File
@@ -291,6 +291,9 @@ class Subtitle(Track):
Subtitle.filter_unwanted_cues(caption_set)
subtitle_text = pycaption.WebVTTWriter().write(caption_set)
self.path.write_text(subtitle_text, encoding="utf8")
except pycaption.exceptions.CaptionReadNoCaptions:
# some renditions carry headers but no cues; write them out rather than fail the download
self.path.write_text(text, encoding="utf8")
except pycaption.exceptions.CaptionReadSyntaxError:
# If first attempt fails, try more aggressive sanitization
text = Subtitle.sanitize_webvtt(text)
+9 -11
View File
@@ -278,24 +278,22 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
data = track.data["dash"]
manifest = data["manifest"]
rep_id = data.get("representation_id") or data["representation"].get("id")
adaptation_set = data["adaptation_set"]
representation = data["representation"]
rep_id = data.get("representation_id") or representation.get("id")
filtered_period_ids = data.get("filtered_period_ids", [])
stored_period = data.get("period")
track_url = track.url if isinstance(track.url, str) else track.url[0]
content_periods = [p for p in manifest.findall("Period") if DASH._is_content_period(p, filtered_period_ids)]
raw_segments: list[tuple[str, Optional[str]]] = []
for period in content_periods:
matched_rep = matched_as = None
for as_ in period.findall("AdaptationSet"):
if DASH.is_trick_mode(as_):
continue
for rep in as_.findall("Representation"):
if rep.get("id") == rep_id:
matched_rep, matched_as = rep, as_
break
if matched_rep is not None:
break
# rep ids are only unique within an AdaptationSet, so resolve like DASH.download_track
if period is stored_period:
matched_as, matched_rep = adaptation_set, representation
else:
matched_as, matched_rep = DASH.resolve_representation(period, rep_id, adaptation_set) or (None, None)
if matched_rep is None or matched_as is None:
continue
Generated
+17 -1
View File
@@ -1828,6 +1828,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/14/25/b208c5683343959b670dc001595f2f3737e051da617f66c31f7c4fa93abc/rich-14.3.3-py3-none-any.whl", hash = "sha256:793431c1f8619afa7d3b52b2cdec859562b950ea0d4b6b505397612db8d5362d", size = 310458, upload-time = "2026-02-19T17:23:13.732Z" },
]
[[package]]
name = "rich-click"
version = "1.9.8"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "rich" },
]
sdist = { url = "https://files.pythonhosted.org/packages/f7/ea/21e4867ea0ef881ffd4c0550fc21a061435e50d6324bcd034396633cbc18/rich_click-1.9.8.tar.gz", hash = "sha256:4008f921da88b5d91646c134ec881c1500e5a6b3f093e90e8f29400e09608371", size = 75363, upload-time = "2026-05-28T19:54:59.144Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/6d/97/a87901aef6b7e7e4a34c6dd6cc17dca8594a592ef9d9dd765fca2b7facf7/rich_click-1.9.8-py3-none-any.whl", hash = "sha256:12873865396e6927835d4eabb1cc3996edcd65b7ac9b2391a29eca4f335a2f93", size = 72189, upload-time = "2026-05-28T19:54:57.867Z" },
]
[[package]]
name = "rlaphoenix-m3u8"
version = "3.4.0"
@@ -2120,7 +2134,7 @@ wheels = [
[[package]]
name = "unshackle"
version = "5.3.0"
version = "5.4.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
@@ -2157,6 +2171,7 @@ dependencies = [
{ name = "pyyaml" },
{ name = "requests", extra = ["socks"] },
{ name = "rich" },
{ name = "rich-click" },
{ name = "rlaphoenix-m3u8" },
{ name = "rnet" },
{ name = "ruamel-yaml" },
@@ -2224,6 +2239,7 @@ requires-dist = [
{ name = "pyyaml", specifier = ">=6.0.1,<7" },
{ name = "requests", extras = ["socks"], specifier = ">=2.32.5,<3" },
{ name = "rich", specifier = ">=13.7.1,<15" },
{ name = "rich-click", specifier = ">=1.9.8" },
{ name = "rlaphoenix-m3u8", specifier = ">=3.4.0,<4" },
{ name = "rnet", specifier = ">=2.4.2" },
{ name = "ruamel-yaml", specifier = ">=0.18.6,<0.19" },