mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
Compare commits
3
Commits
d12a943d96
...
d4abcb51d9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4abcb51d9 | ||
|
|
bd64f3a8c4 | ||
|
|
7b927934e0 |
@@ -127,7 +127,7 @@ while the server restarts.
|
||||
| `TRACK_NOT_FOUND` | 404 | A referenced track ID is not present in the remote session. |
|
||||
| `CONFLICT` | 409 | The target resource is in a state that disallows the action (retrying a running job, prioritising a non-queued job, clearing cache during an active download). |
|
||||
| `SERVER_DRAINING` | 409 | The server is about to restart and starts no new remote session or download job. Open work continues. Retryable after the restart. A `dl --remote` client waits for the restart and opens a new remote session. |
|
||||
| `SERVICE_ERROR` | 422 | The streaming service's API returned an error, or the service does not support the requested operation. |
|
||||
| `SERVICE_ERROR` | 422 | The streaming service's API returned an error, or the service does not support the requested operation, or the service code exited (`sys.exit`). |
|
||||
| `DRM_ERROR` | 422 | DRM or license acquisition failed. |
|
||||
| `RATE_LIMITED` | 429 | The streaming service is rate-limiting requests. Retryable. |
|
||||
|
||||
|
||||
@@ -62,10 +62,11 @@ remote_services:
|
||||
url: "https://my-box.example:8786"
|
||||
api_key: "your-api-key"
|
||||
# Optional: let the server's CDM do the licensing instead of a local CDM
|
||||
server_cdm: false
|
||||
# Optional: per-service config overrides applied locally (title_map, cdm, etc.)
|
||||
server_cdm: true
|
||||
# Optional: per-service config overrides applied locally (title_map, cdm, server_cdm, etc.)
|
||||
services:
|
||||
EXAMPLE:
|
||||
server_cdm: false # this service licenses with your local CDM
|
||||
title_map:
|
||||
"0ABCDEF": "The Show (Renamed Locally)"
|
||||
```
|
||||
@@ -74,8 +75,8 @@ remote_services:
|
||||
|---|---|---|
|
||||
| `url` | yes | Base URL of the `unshackle serve` instance (no trailing slash needed) |
|
||||
| `api_key` | no | Sent as the `X-Secret-Key` header on every request |
|
||||
| `server_cdm` | no | When `true`, DRM keys are resolved by the server's CDM rather than a local device (default `false`) |
|
||||
| `services` | no | Per-service local config overrides, keyed by service tag |
|
||||
| `server_cdm` | no | `true` asks for the server's CDM, `false` uses your local device; unset follows the API key's server CDM grant |
|
||||
| `services` | no | Per-service local config overrides, keyed by service tag in any case; a `server_cdm` here replaces the server entry's value for that service |
|
||||
|
||||
!!! warning "Port default"
|
||||
The `unshackle serve` default port is **`8786`** (not `8080`). Use the port
|
||||
@@ -267,16 +268,17 @@ hood the client walks a remote session through its lifecycle.
|
||||
|
||||
There are two ways DRM keys get resolved, chosen by the client's `server_cdm` flag.
|
||||
|
||||
=== "Proxied CDM (default)"
|
||||
=== "Proxied CDM (server_cdm: false)"
|
||||
|
||||
Your **local CDM** builds the license challenge. The client sends that challenge
|
||||
to `POST /api/session/{id}/license`, the server forwards it to the service, and
|
||||
the raw license bytes come back for your local CDM to parse.
|
||||
|
||||
- Keeps your CDM local. The server only relays the license request.
|
||||
- Used when `server_cdm` is `false` (the default).
|
||||
- Also used for a run with `dl --cdm <name>`, and for a service whose own entry in
|
||||
your `cdm` config named the loaded device. In each case the client sends
|
||||
- Used when `server_cdm` is `false`, or when it is unset and the API key has no server
|
||||
CDM for the service.
|
||||
- Also used for a run with `dl --cdm <name>`, and, when `server_cdm` is unset, for a
|
||||
service whose own entry in your `cdm` config named the loaded device. In each case the client sends
|
||||
`server_cdm: false` when it creates the remote session, and the server builds the
|
||||
service on your device even when the API key has the server CDM.
|
||||
- A service option that the service lists in `SERVER_DEVICE_OPTIONS` keeps the server
|
||||
|
||||
@@ -312,17 +312,18 @@ Language-tag remapping and the rule engine behind the `{lang_tag}` filename vari
|
||||
| Condition | Meaning |
|
||||
|-----------|---------|
|
||||
| `audio` | At least one audio language matches. |
|
||||
| `audio_contain_all` | Every listed language must be present in the audio. |
|
||||
| `subs_contain` | At least one subtitle language matches. |
|
||||
| `subs_contain_all` | Every listed language must be present. |
|
||||
| `subs_contain_all` | Every listed language must be present in the subtitles. |
|
||||
| `dual` / `multi` / `dubbed` | `true` matches when that filename variable is set, `false` when it is not. |
|
||||
|
||||
Each language condition takes one language tag or a list of them. A list matches when **any**
|
||||
entry matches, except `subs_contain_all`, which needs them all. An entry that is not a valid
|
||||
language tag (for example `japanese`) never matches. A tag with a region matches only that
|
||||
variant, so `audio: es-419` does not match `es-ES` audio. `dual`, `multi` and `dubbed` take a bare
|
||||
`true` or `false`, not a quoted string. unshackle skips a rule with a condition name it does
|
||||
not know, or with any other value in a boolean condition. It logs a warning in each of these
|
||||
cases and tries the next rule.
|
||||
entry matches, except `audio_contain_all` and `subs_contain_all`, which need them all. An empty
|
||||
list never matches. An entry that is not a valid language tag (for example `japanese`) never
|
||||
matches. A tag with a region matches only that variant, so `audio: es-419` does not match
|
||||
`es-ES` audio. `dual`, `multi` and `dubbed` take a bare `true` or `false`, not a quoted string.
|
||||
unshackle skips a rule with a condition name it does not know, or with any other value in a
|
||||
boolean condition. It logs a warning in each of these cases and tries the next rule.
|
||||
|
||||
`dual`, `multi` and `dubbed` carry the same meaning as the
|
||||
[filename variables of those names](#dual_multi_mode). Pair one with a language to name a
|
||||
@@ -343,6 +344,24 @@ language_tags:
|
||||
tag: "THAIDUAL"
|
||||
```
|
||||
|
||||
unshackle examines the rules in order, so put a rule that needs more languages before a rule that
|
||||
needs fewer. Here, a release with both French dubs gets `VF2`, not `VFQ`:
|
||||
|
||||
```yaml
|
||||
language_tags:
|
||||
rules:
|
||||
- audio_contain_all: [fr-FR, fr-CA]
|
||||
tag: "VF2"
|
||||
- audio: fr-CA
|
||||
tag: "VFQ"
|
||||
- audio: fr-FR
|
||||
tag: "VFF"
|
||||
```
|
||||
|
||||
!!! tip "Give regional tags in an `_all` list"
|
||||
A tag without a region also matches a regional track, so one `fr-CA` track satisfies both
|
||||
entries of `[fr, fr-CA]`. Use `[fr-FR, fr-CA]` to require two different tracks.
|
||||
|
||||
!!! note "Put `{lang_tag}` where you want the name"
|
||||
These rules fill `{lang_tag}`. To use your own name in place of the fixed text, keep
|
||||
`{lang_tag?}` in the template and leave out `{dual?}`, `{multi?}` and `{dubbed?}`.
|
||||
|
||||
@@ -17,8 +17,10 @@ Over `--remote`, an override also makes your device license the remote session,
|
||||
CDM. A per-service entry does the same when it names a device without a quality: a device name,
|
||||
a `widevine` or `playready` sub-entry, or a profile or `default` sub-entry. A per-service entry
|
||||
that selects only by quality, or only for a different profile, loads no device when the run
|
||||
starts. unshackle then shows a warning, and the server decides who licenses the remote session.
|
||||
With only the top-level `default` entry, the server CDM licenses when the API key has it. See
|
||||
starts. When `server_cdm` is unset, unshackle then shows a warning, and the server decides who
|
||||
licenses the remote session.
|
||||
With only the top-level `default` entry, the server CDM licenses when the API key has it. Set
|
||||
`server_cdm: true` on the server entry to keep a per-service entry for local runs only. See
|
||||
[`remote_services`](services.md#remote_services).
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -89,16 +89,35 @@ Definitions of remote unshackle service servers, used by the `--remote` mode. Ea
|
||||
named by you (pick it with `--server`, or do not write that flag when you configure only one) and gives
|
||||
the server's `url` (required), an optional `api_key`, an optional `auth_headers` list, an
|
||||
optional `server_cdm` boolean, an optional `timeout` in seconds, and an optional `services` sub-dict of per-service local
|
||||
overrides such as `title_map`.
|
||||
overrides such as `title_map`, keyed by service tag in any case. A `server_cdm` in a `services` entry replaces the `server_cdm` of
|
||||
the server entry for that service.
|
||||
|
||||
Leave `server_cdm` unset and the client follows the server: it uses the server CDM for each
|
||||
service the API key has it on, and the local CDM for the others. `true` asks for the server CDM
|
||||
and falls back to the local CDM when the server refuses; `false` always uses the local CDM.
|
||||
`dl --cdm <name>` on a remote run has the same effect as `false` for that run: the device you
|
||||
name licenses the remote session. A [`cdm`](drm.md#cdm) entry for the service has the same
|
||||
effect for that service when it names the device that unshackle loaded. Both take priority over
|
||||
`server_cdm: true`. Remove the entry to use the server CDM for that service. The `default`
|
||||
entry does not count.
|
||||
name licenses the remote session, and it takes priority over `server_cdm: true`. When
|
||||
`server_cdm` is unset, a [`cdm`](drm.md#cdm) entry for the service has the same effect for that
|
||||
service when it names the device that unshackle loaded. The `default` entry does not count.
|
||||
With `server_cdm: true`, the server CDM licenses the remote session, and the device of the entry
|
||||
licenses only when the server refuses. Thus the entry applies to local runs and the server CDM
|
||||
applies to remote runs:
|
||||
|
||||
```yaml
|
||||
cdm:
|
||||
EXAMPLE1: my_device # local runs of EXAMPLE1
|
||||
|
||||
remote_services:
|
||||
my_server:
|
||||
url: https://example.com
|
||||
server_cdm: true # remote runs of EXAMPLE1 use the server CDM
|
||||
services:
|
||||
EXAMPLE2:
|
||||
server_cdm: false # remote runs of EXAMPLE2 use your own device
|
||||
```
|
||||
|
||||
When the server refuses the server CDM for a service whose `cdm` entry loaded the device,
|
||||
unshackle logs the fallback to that device as info, not as a warning.
|
||||
|
||||
The server has the last word. When it keeps the server CDM for a remote session that your
|
||||
device was to license, unshackle shows a warning. This occurs with a server that does not read
|
||||
@@ -180,8 +199,8 @@ an API key without `server_cdm` for that service also cannot submit or retry `/a
|
||||
jobs. Keys that have no `users` entry, such as `api_secret`, keep server CDM access.
|
||||
|
||||
A remote client that picks its own device licenses the remote session with that device. It picks
|
||||
with `dl --cdm`, with a `cdm` entry for the service, or with `server_cdm: false` in its
|
||||
`remote_services` entry. The server CDM makes no licence for that remote session, with or without
|
||||
with `dl --cdm`, with `server_cdm: false` in its `remote_services` entry or in the `services`
|
||||
entry for the service, or with a `cdm` entry for the service when `server_cdm` is unset. The server CDM makes no licence for that remote session, with or without
|
||||
a limit. A service option that runs the remote session on the server's device, such as a
|
||||
server-identity flag, keeps the server CDM.
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ language_tags:
|
||||
rules:
|
||||
- audio: no
|
||||
tag: NORDIC
|
||||
- audio_contain_all: [no, da]
|
||||
tag: NORDIC2
|
||||
update_checks: no
|
||||
"""
|
||||
|
||||
@@ -57,6 +59,10 @@ def test_a_no_rule_tags_a_norwegian_track(tmp_path: Path) -> None:
|
||||
assert evaluate_language_tag(rules, [Language.get("no")], []) == "NORDIC"
|
||||
|
||||
|
||||
def test_a_no_entry_survives_in_an_audio_contain_all_list(tmp_path: Path) -> None:
|
||||
assert _load(tmp_path).language_tags["rules"][1]["audio_contain_all"] == ["no", "da"]
|
||||
|
||||
|
||||
def test_tag_rules_keep_their_own_booleans(tmp_path: Path) -> None:
|
||||
"""tag_rules matches text and warns about a bare bool itself."""
|
||||
path = tmp_path / "unshackle.yaml"
|
||||
|
||||
@@ -31,6 +31,23 @@ def test_subs_contain_all_needs_every_entry() -> None:
|
||||
assert evaluate_language_tag(rules, JA, EN_ES) == ""
|
||||
|
||||
|
||||
def test_audio_contain_all_tags_a_release_with_every_listed_language() -> None:
|
||||
rules = [
|
||||
{"audio_contain_all": ["fr-FR", "fr-CA"], "tag": "VF2"},
|
||||
{"audio": "fr-CA", "tag": "VFQ"},
|
||||
{"audio": "fr-FR", "tag": "VFF"},
|
||||
]
|
||||
fr_fr, fr_ca, en = Language.get("fr-FR"), Language.get("fr-CA"), Language.get("en-US")
|
||||
assert evaluate_language_tag(rules, [en, fr_fr, fr_ca], []) == "VF2"
|
||||
assert evaluate_language_tag(rules, [en, fr_ca], []) == "VFQ"
|
||||
assert evaluate_language_tag(rules, [en, fr_fr], []) == "VFF"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("condition", ["audio_contain_all", "subs_contain_all"])
|
||||
def test_an_empty_contain_all_list_matches_nothing(condition) -> None:
|
||||
assert evaluate_language_tag([{condition: [], "tag": "ALL"}], JA, EN_ES) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["japanese", 1, [["ja"]], {"ja": 1}])
|
||||
def test_an_invalid_rule_value_is_no_match_not_a_crash(bad, caplog) -> None:
|
||||
rules = [{"audio": bad, "tag": "BAD"}, {"audio": "ja", "tag": "OK"}]
|
||||
|
||||
@@ -121,3 +121,11 @@ def test_overdue_staged_service_applies_while_busy(service_dir: Path, monkeypatc
|
||||
assert services.apply_pending(busy={"FOO"}) == ["FOO"]
|
||||
assert services.MODULES["FOO"].VERSION == 2
|
||||
assert services.PENDING == set() and "FOO" not in services.PENDING_SINCE
|
||||
|
||||
|
||||
def test_service_that_exits_on_import_fails_its_reload_only(service_dir: Path):
|
||||
"""A service calling sys.exit at import time is a load error, not a stop of the process."""
|
||||
(service_dir / "FOO" / "__init__.py").write_text("import sys\nsys.exit(1)\n")
|
||||
os.utime(service_dir / "FOO" / "__init__.py", (time.time() + 9, time.time() + 9))
|
||||
services.reload_services(["FOO"])
|
||||
assert services.LOAD_ERRORS and services.LOAD_ERRORS[-1].startswith("FOO: failed to import - SystemExit")
|
||||
|
||||
@@ -216,3 +216,9 @@ async def test_outer_middleware_never_answers_5xx(aiohttp_client) -> None:
|
||||
resp = await client.get("/subapp")
|
||||
assert resp.status == 422 and (await resp.json())["message"] == "device error"
|
||||
assert (await client.get("/missing")).status == 404
|
||||
|
||||
|
||||
def test_categorize_system_exit_is_a_service_error() -> None:
|
||||
err = categorize_exception(SystemExit(1), {"service": "EXAMPLE"})
|
||||
assert err.error_code == APIErrorCode.SERVICE_ERROR
|
||||
assert err.message == "Service EXAMPLE exited"
|
||||
|
||||
@@ -4,8 +4,10 @@ The directory holds only what the client sent, goes back to the client when it l
|
||||
itself, and is always removed when the request ends.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import types
|
||||
import zlib
|
||||
|
||||
import click
|
||||
@@ -123,6 +125,17 @@ async def test_cache_dir_removed_on_error(seen, tmp_path):
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_answers_a_service_sys_exit_with_an_error(seen, tmp_path, monkeypatch):
|
||||
def search(self):
|
||||
raise SystemExit(1)
|
||||
|
||||
monkeypatch.setattr(_CacheService, "search", search)
|
||||
response = await handlers.search_handler({"service": "EXAMPLE", "query": "q"})
|
||||
assert json.loads(response.body)["error_code"] == "SERVICE_ERROR"
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_client_cache_still_removes_the_dir(seen, tmp_path):
|
||||
data = {"service": "EXAMPLE", "query": "q", "cache": {"tokens": 1}}
|
||||
@@ -192,3 +205,24 @@ async def test_list_tracks_service_sees_dl_params(seen):
|
||||
async def test_search_service_gets_no_dl_params(seen):
|
||||
await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
|
||||
assert "a_lang" not in seen["parent_params"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_samples_answers_a_service_exit_in_decrypts_samples(monkeypatch):
|
||||
class Service:
|
||||
def decrypts_samples(self, track):
|
||||
raise SystemExit(1)
|
||||
|
||||
session = types.SimpleNamespace(
|
||||
tracks={"t": object()}, service_instance=Service(), service_tag="EXAMPLE", lock=asyncio.Lock()
|
||||
)
|
||||
|
||||
async def get_session(session_id, request=None):
|
||||
return session
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", get_session)
|
||||
monkeypatch.setattr(handlers, "require_authenticated", lambda s: None)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
with pytest.raises(handlers.APIError) as e:
|
||||
await handlers.session_samples_handler("sid", "t", "1", b"")
|
||||
assert e.value.error_code.value == "SERVICE_ERROR"
|
||||
|
||||
@@ -175,6 +175,41 @@ async def test_heartbeat_keeps_slow_request_alive(aiohttp_client, monkeypatch: p
|
||||
assert resp.status == 200 and body["status"] == "error" and body["error_code"] == "SERVICE_ERROR"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("delay", [0, 0.2])
|
||||
async def test_heartbeat_answers_a_service_exit_and_keeps_serving(
|
||||
aiohttp_client, monkeypatch: pytest.MonkeyPatch, delay: float
|
||||
) -> None:
|
||||
"""A SystemExit inside the heartbeat task becomes a SERVICE_ERROR instead of stopping the event loop."""
|
||||
monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.05)
|
||||
|
||||
@heartbeat
|
||||
async def exits(request: web.Request) -> web.Response:
|
||||
await asyncio.sleep(delay)
|
||||
raise SystemExit(1)
|
||||
|
||||
app = web.Application()
|
||||
app["debug_api"] = False
|
||||
app.router.add_get("/exits", api_handler(exits))
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
for _ in range(2):
|
||||
resp = await client.get("/exits")
|
||||
assert json.loads(await resp.text())["error_code"] == "SERVICE_ERROR"
|
||||
|
||||
|
||||
async def test_unguarded_route_answers_a_service_exit(aiohttp_client) -> None:
|
||||
async def exits(request: web.Request) -> web.Response:
|
||||
raise SystemExit(1)
|
||||
|
||||
app = web.Application(middlewares=[routes.no_5xx_middleware])
|
||||
app.router.add_get("/exits", exits)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
for _ in range(2):
|
||||
resp = await client.get("/exits")
|
||||
assert resp.status == 422 and (await resp.json())["error_code"] == "SERVICE_ERROR"
|
||||
|
||||
|
||||
async def test_heartbeat_late_error_counts_as_rejected(aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Stats count a late failure by its real status and the bytes the stream sent (with framing), not as an empty 200."""
|
||||
from unshackle.core.api.stats import stats, stats_middleware
|
||||
|
||||
@@ -698,11 +698,20 @@ def test_the_client_declines_the_server_cdm_when_the_user_picked_a_device(server
|
||||
|
||||
|
||||
def test_a_device_loaded_from_the_services_cdm_entry_declines_the_server_cdm():
|
||||
svc, data = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
|
||||
svc, data = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
|
||||
assert data["server_cdm"] is False
|
||||
assert svc._server_cdm is False
|
||||
|
||||
|
||||
def test_server_cdm_true_outranks_the_services_cdm_entry(caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
svc, data = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
|
||||
assert "server_cdm" not in data
|
||||
assert data["cdm_relay"] is True
|
||||
assert svc._server_cdm is True
|
||||
assert not caplog.text
|
||||
|
||||
|
||||
def test_cdm_over_an_existing_cdm_entry_declines_without_a_warning(caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
_, data = sent_create(True, "my_device", cdm_map={"EXAMPLE1": {">=1080": "other"}})
|
||||
@@ -721,12 +730,19 @@ def test_a_device_loaded_from_the_default_cdm_entry_does_not_decline(caplog):
|
||||
@pytest.mark.parametrize("local_cdm", [SimpleNamespace(is_playready=False), None])
|
||||
def test_a_cdm_entry_that_did_not_load_the_device_warns_and_does_not_decline(local_cdm, caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
svc, data = sent_create(True, local_cdm=local_cdm, cdm_map={"example1": {">=1080": "my_device"}})
|
||||
svc, data = sent_create(None, local_cdm=local_cdm, cdm_map={"example1": {">=1080": "my_device"}})
|
||||
assert "server_cdm" not in data
|
||||
assert svc._server_cdm is True
|
||||
assert svc._server_cdm is None
|
||||
assert "cdm entry for EXAMPLE1" in caplog.text
|
||||
|
||||
|
||||
def test_server_cdm_true_does_not_warn_about_a_cdm_entry_that_loaded_no_device(caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
_, data = sent_create(True, cdm_map={"example1": {">=1080": "my_device"}})
|
||||
assert "server_cdm" not in data
|
||||
assert not caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry", "profile", "names"),
|
||||
[
|
||||
@@ -751,8 +767,8 @@ def test_a_client_with_no_device_does_not_decline():
|
||||
|
||||
def created(answer):
|
||||
"""Run ``authenticate()`` to its end for a device the service's cdm entry loaded."""
|
||||
svc, _ = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
|
||||
svc._server_cdm = True
|
||||
svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
|
||||
svc._server_cdm = None
|
||||
svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer})
|
||||
svc.close = svc.start_keepalive = lambda: None
|
||||
svc.authenticate()
|
||||
@@ -808,3 +824,64 @@ def test_a_declined_server_cdm_that_the_server_keeps_is_reported(max_height, cap
|
||||
with caplog.at_level(logging.WARNING):
|
||||
svc.adopt_session_cdm(True, max_height)
|
||||
assert "your own device is not used" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("cdm_entry", "level"), [(True, logging.INFO), (False, logging.WARNING)])
|
||||
def test_a_refused_server_cdm_warns_only_when_no_cdm_entry_loaded_the_fallback(cdm_entry, level, caplog):
|
||||
svc = remote(SimpleNamespace(is_playready=False), {})
|
||||
svc.service_tag = "EXAMPLE1"
|
||||
svc.ctx.obj.cdm_entry = cdm_entry
|
||||
with caplog.at_level(logging.INFO):
|
||||
svc.adopt_session_cdm(False, None)
|
||||
assert svc._server_cdm is False
|
||||
[record] = [r for r in caplog.records if "falling back to the local CDM" in r.getMessage()]
|
||||
assert record.levelno == level
|
||||
|
||||
|
||||
@pytest.mark.parametrize("apply_overrides", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
("server_level", "service_entry", "expected"),
|
||||
[
|
||||
(True, {"server_cdm": False}, False),
|
||||
(False, {"server_cdm": True}, True),
|
||||
(True, {}, True),
|
||||
(None, {}, None),
|
||||
],
|
||||
)
|
||||
def test_a_per_service_server_cdm_overrides_the_server_entry(
|
||||
server_level, service_entry, expected, apply_overrides, monkeypatch
|
||||
):
|
||||
import unshackle.core.remote_service as remote_mod
|
||||
|
||||
live = {"EXAMPLE1": {**service_entry, "title_map": {"a": "b"}}, "_server_cdm": server_level}
|
||||
monkeypatch.setattr(remote_mod, "resolve_server", lambda name: ("http://127.0.0.1:1", "", live))
|
||||
monkeypatch.setattr(remote_mod, "remote_service_list", lambda name: [])
|
||||
monkeypatch.setattr(handlers.config, "services", {})
|
||||
name = RemoteService.__name__
|
||||
try:
|
||||
svc = remote_mod.make_remote_service(
|
||||
SimpleNamespace(obj=None), None, "EXAMPLE1", "t1", {}, apply_overrides=apply_overrides
|
||||
)
|
||||
finally:
|
||||
RemoteService.__name__ = name # the constructor renames the class
|
||||
assert svc._server_cdm is expected
|
||||
assert handlers.config.services.get("EXAMPLE1") == ({"title_map": {"a": "b"}} if apply_overrides else None)
|
||||
assert live["EXAMPLE1"] == {**service_entry, "title_map": {"a": "b"}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("config_key", "tag"), [("example1", "EXAMPLE1"), ("EXAMPLE1", "example1")])
|
||||
def test_a_per_service_entry_matches_the_tag_in_any_case(config_key, tag, monkeypatch):
|
||||
import unshackle.core.remote_service as remote_mod
|
||||
|
||||
live = {config_key: {"server_cdm": False, "title_map": {"a": "b"}}, "_server_cdm": True}
|
||||
monkeypatch.setattr(remote_mod, "resolve_server", lambda name: ("http://127.0.0.1:1", "", live))
|
||||
monkeypatch.setattr(remote_mod, "remote_service_list", lambda name: [{"tag": "EXAMPLE1", "anonymous_search": True}])
|
||||
monkeypatch.setattr(handlers.config, "services", {})
|
||||
name = RemoteService.__name__
|
||||
try:
|
||||
svc = remote_mod.make_remote_service(SimpleNamespace(obj=None), None, tag, "t1", {})
|
||||
finally:
|
||||
RemoteService.__name__ = name # the constructor renames the class
|
||||
assert svc._server_cdm is False
|
||||
assert svc._anonymous_search is True
|
||||
assert handlers.config.services == {tag: {"title_map": {"a": "b"}}}
|
||||
|
||||
@@ -179,7 +179,7 @@ def build_error_response(
|
||||
|
||||
|
||||
def categorize_exception(
|
||||
exc: Exception,
|
||||
exc: BaseException,
|
||||
context: dict[str, Any] | None = None,
|
||||
) -> APIError:
|
||||
"""
|
||||
@@ -196,6 +196,14 @@ def categorize_exception(
|
||||
APIError with appropriate error code and details
|
||||
"""
|
||||
context = context or {}
|
||||
if isinstance(exc, SystemExit):
|
||||
exited = f"Service {context['service']} exited" if context.get("service") else "Service exited"
|
||||
return APIError(
|
||||
error_code=APIErrorCode.SERVICE_ERROR,
|
||||
message=redact_secrets(getattr(exc, "message", None)) or exited,
|
||||
details={**context, "reason": "service_exit"},
|
||||
retryable=False,
|
||||
)
|
||||
root = exc.__cause__ or exc
|
||||
exc_str = f"{exc} {root}".lower()
|
||||
exc_type = type(root).__name__
|
||||
@@ -296,7 +304,7 @@ def categorize_exception(
|
||||
|
||||
|
||||
def handle_api_exception(
|
||||
exc: Exception,
|
||||
exc: BaseException,
|
||||
context: dict[str, Any] | None = None,
|
||||
debug_mode: bool = False,
|
||||
extra_debug_info: dict[str, Any] | None = None,
|
||||
|
||||
@@ -15,7 +15,7 @@ from datetime import date as date_
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, cast
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, cast
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
@@ -1088,6 +1088,8 @@ def live_licence_refusal(session: Any, track: Any) -> Optional[APIError]:
|
||||
|
||||
|
||||
_account_counters: Dict[str, int] = {}
|
||||
# the event loop holds only weak references to tasks, so a running login task needs a strong one
|
||||
_auth_tasks: Set["asyncio.Task[None]"] = set()
|
||||
|
||||
|
||||
def validate_server_accounts() -> Dict[str, Any]:
|
||||
@@ -1885,6 +1887,14 @@ async def search_handler(data: Dict[str, Any], request: Optional[web.Request] =
|
||||
try:
|
||||
results = await asyncio.to_thread(run_service_search, data, normalized_service, query, request, request_cache)
|
||||
return request_cache.json_response({"results": results, "count": len(results)})
|
||||
except APIError:
|
||||
raise
|
||||
except (Exception, SystemExit) as e:
|
||||
log.exception("Error searching")
|
||||
debug_mode = request.app.get("debug_api", False) if request else False
|
||||
return handle_api_exception(
|
||||
e, context={"operation": "search", "service": normalized_service}, debug_mode=debug_mode
|
||||
)
|
||||
finally:
|
||||
request_cache.cleanup()
|
||||
|
||||
@@ -3987,7 +3997,9 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
|
||||
if store.peek(session_id) is not session:
|
||||
SessionStore.cleanup_cache_dir(session_cache_tag)
|
||||
|
||||
asyncio.create_task(run_auth())
|
||||
auth_task = asyncio.create_task(run_auth())
|
||||
_auth_tasks.add(auth_task)
|
||||
auth_task.add_done_callback(_auth_tasks.discard)
|
||||
|
||||
return web.json_response(
|
||||
{
|
||||
@@ -4173,7 +4185,7 @@ async def session_tracks_handler(
|
||||
try:
|
||||
chapters = await asyncio.to_thread(service_instance.get_chapters, title)
|
||||
session.chapters_by_title[str(title_id)] = chapters if chapters else []
|
||||
except (NotImplementedError, Exception):
|
||||
except (Exception, SystemExit):
|
||||
session.chapters_by_title[str(title_id)] = []
|
||||
|
||||
video_tracks = sorted(tracks.videos, key=lambda t: t.bitrate or 0, reverse=True)
|
||||
@@ -5271,14 +5283,14 @@ async def session_samples_handler(
|
||||
details={"track_id": track_id, "session_id": session_id},
|
||||
)
|
||||
service = session.service_instance
|
||||
if not service.decrypts_samples(track):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"The service does not decrypt the samples of track {track_id}")
|
||||
if not server_cdm_allowed(request, session.service_tag):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN, f"This API key may not decrypt {session.service_tag} samples on the server"
|
||||
)
|
||||
|
||||
def run() -> web.Response:
|
||||
if not service.decrypts_samples(track):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"The service does not decrypt the samples of track {track_id}")
|
||||
decrypter = service.get_sample_decrypter(track, index)
|
||||
if isinstance(decrypter, (bytes, bytearray)):
|
||||
return web.json_response({"key": bytes(decrypter).hex()})
|
||||
|
||||
@@ -11,7 +11,13 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
|
||||
|
||||
from unshackle.core import __code_hash__, __version__
|
||||
from unshackle.core import services as services_module
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
|
||||
from unshackle.core.api.errors import (
|
||||
APIError,
|
||||
APIErrorCode,
|
||||
build_error_response,
|
||||
categorize_exception,
|
||||
handle_api_exception,
|
||||
)
|
||||
from unshackle.core.api.handlers import (
|
||||
CORS_HEADERS,
|
||||
DASHBOARD_EVENTS_ROUTE,
|
||||
@@ -104,12 +110,13 @@ async def no_5xx_middleware(
|
||||
"""Answer an uncaught exception or any unsent 5xx (a CDM subapplication's own) as a 422; see errors.py."""
|
||||
try:
|
||||
response = await handler(request)
|
||||
except Exception as e:
|
||||
except (Exception, SystemExit) as e:
|
||||
if isinstance(e, web.HTTPException) and e.status < 500:
|
||||
raise
|
||||
# the exception text can hold a caller's key, so the answer gets a generic message
|
||||
log.exception(f"Unhandled error in {sanitize_log(request.path)}")
|
||||
response = build_error_response(APIError(APIErrorCode.INTERNAL_ERROR, "Internal server error"))
|
||||
error = categorize_exception(e) if isinstance(e, SystemExit) else None
|
||||
response = build_error_response(error or APIError(APIErrorCode.INTERNAL_ERROR, "Internal server error"))
|
||||
if response.status >= 500 and not response.prepared:
|
||||
response.set_status(APIError.default_http_status(APIErrorCode.INTERNAL_ERROR))
|
||||
return response
|
||||
@@ -147,9 +154,17 @@ def heartbeat(handler: Handler) -> Handler:
|
||||
work continues if the client disconnects, so the remote session state stays complete.
|
||||
"""
|
||||
|
||||
async def guarded(request: web.Request) -> web.StreamResponse:
|
||||
# a SystemExit leaving any task is re-raised into the event loop, so it must stop inside the task
|
||||
try:
|
||||
return await handler(request)
|
||||
except SystemExit as e:
|
||||
log.exception(f"Service exited in {sanitize_log(request.path)}")
|
||||
raise categorize_exception(e) from e
|
||||
|
||||
@functools.wraps(handler)
|
||||
async def wrapper(request: web.Request) -> web.StreamResponse:
|
||||
task = asyncio.ensure_future(handler(request))
|
||||
task = asyncio.ensure_future(guarded(request))
|
||||
done, _ = await asyncio.wait({task}, timeout=HEARTBEAT_INTERVAL)
|
||||
if done:
|
||||
return task.result()
|
||||
|
||||
@@ -30,6 +30,7 @@ LANGUAGE_KEYS = frozenset(
|
||||
"default_language",
|
||||
"video",
|
||||
"audio",
|
||||
"audio_contain_all",
|
||||
"subtitle",
|
||||
"subs_contain",
|
||||
"subs_contain_all",
|
||||
|
||||
@@ -897,12 +897,17 @@ def make_remote_service(
|
||||
``apply_overrides`` False keeps the per-service ``remote_services.<name>.services`` overrides out of this
|
||||
process's global config.
|
||||
"""
|
||||
url, api_key, services_config = resolve_server(server_name)
|
||||
url, api_key, live = resolve_server(server_name)
|
||||
own = ci_get(live, service_tag)
|
||||
# resolve_server hands back the live config dict; concurrent requests for other tags must not share it
|
||||
services_config = dict(services_config)
|
||||
if not apply_overrides:
|
||||
services_config.pop(service_tag, None)
|
||||
info = next((s for s in remote_service_list(server_name) or [] if s.get("tag") == service_tag), {})
|
||||
tag = service_tag.lower()
|
||||
services_config = {k: v for k, v in live.items() if not (isinstance(k, str) and k.lower() == tag)}
|
||||
if isinstance(own, dict) and "server_cdm" in own:
|
||||
own = dict(own)
|
||||
services_config["_server_cdm"] = own.pop("server_cdm")
|
||||
if apply_overrides and own is not None:
|
||||
services_config[service_tag] = own
|
||||
info = next((s for s in remote_service_list(server_name) or [] if str(s.get("tag", "")).lower() == tag), {})
|
||||
services_config["_server_accounts"] = info.get("server_accounts")
|
||||
services_config["_client_config"] = info.get("client_config")
|
||||
services_config["_anonymous_search"] = info.get("anonymous_search")
|
||||
@@ -1387,8 +1392,8 @@ class RemoteService:
|
||||
# sent with the server CDM too: a capped server hands the tracks above its cap to this device
|
||||
cdm = self.local_cdm
|
||||
cdm_name = self.ctx.parent and self.ctx.parent.params.get("cdm_name")
|
||||
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and self._server_cdm is not False
|
||||
if not (cdm_entry or cdm_name or self._server_cdm is False) and ci_get(config.cdm, self.service_tag):
|
||||
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and self._server_cdm is None
|
||||
if not (cdm_entry or cdm_name or self._server_cdm is not None) and ci_get(config.cdm, self.service_tag):
|
||||
self.log.warning(
|
||||
f"The cdm entry for {self.service_tag} did not load a device for this remote session, "
|
||||
"so the server decides who licenses it"
|
||||
@@ -1471,6 +1476,17 @@ class RemoteService:
|
||||
"""True for a remote session on the server's device whose API key cannot read the server vault."""
|
||||
return getattr(self, "_local_vaults_only", False)
|
||||
|
||||
def report_local_fallback(self) -> None:
|
||||
"""Say the local CDM licenses because the server CDM is not granted.
|
||||
|
||||
Only info when the service's own cdm entry loaded that device, since the entry is the configured fallback.
|
||||
"""
|
||||
log = self.log.info if getattr(self.ctx.obj, "cdm_entry", False) else self.log.warning
|
||||
log(
|
||||
f"{self.service_tag} is not available for server CDM licensing with this API key, "
|
||||
"falling back to the local CDM"
|
||||
)
|
||||
|
||||
def adopt_session_cdm(self, server_cdm: bool, max_height: Optional[int]) -> None:
|
||||
"""Take the server's choice of who licenses this remote session, and say why when a cap made it.
|
||||
|
||||
@@ -1486,10 +1502,7 @@ class RemoteService:
|
||||
self.log.warning("The server CDM licenses this remote session, so your own device is not used")
|
||||
return
|
||||
if self._server_cdm and not server_cdm and max_height is None:
|
||||
self.log.warning(
|
||||
f"{self.service_tag} is not available for server CDM licensing with this API key, "
|
||||
"falling back to the local CDM"
|
||||
)
|
||||
self.report_local_fallback()
|
||||
self._server_cdm = server_cdm
|
||||
if max_height is None:
|
||||
return
|
||||
@@ -1840,10 +1853,7 @@ class RemoteService:
|
||||
self._server_cdm = server_cdm
|
||||
elif self._server_cdm and not server_cdm:
|
||||
self._server_cdm = False
|
||||
self.log.warning(
|
||||
f"{self.service_tag} is not available for server CDM licensing with this API key, "
|
||||
"falling back to the local CDM"
|
||||
)
|
||||
self.report_local_fallback()
|
||||
self._server_cdm_type = result.get("server_cdm_type", "widevine")
|
||||
self._sample_decrypt_tracks.update(result.get("sample_decrypt_tracks") or [])
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def load_service(path: Path) -> object:
|
||||
tag = path.parent.stem
|
||||
try:
|
||||
module = import_module_by_path(path)
|
||||
except Exception as e:
|
||||
except (Exception, SystemExit) as e:
|
||||
hint = compiled_import_hint(e.name, path) if isinstance(e, ModuleNotFoundError) and e.name else ""
|
||||
raise RuntimeError(f"{tag}: failed to import - {type(e).__name__}: {e}{hint} ({path.name})") from e
|
||||
try:
|
||||
|
||||
@@ -14,7 +14,13 @@ log = logging.getLogger(__name__)
|
||||
|
||||
# Conditions that test a filename variable of the same name rather than a language.
|
||||
STATE_CONDITIONS = ("dual", "multi", "dubbed")
|
||||
LANGUAGE_CONDITIONS = ("audio", "subs_contain", "subs_contain_all")
|
||||
# Each language condition: whether it tests the subtitles, and whether any or all of its entries must match.
|
||||
LANGUAGE_CONDITIONS = {
|
||||
"audio": (False, any),
|
||||
"audio_contain_all": (False, all),
|
||||
"subs_contain": (True, any),
|
||||
"subs_contain_all": (True, all),
|
||||
}
|
||||
|
||||
|
||||
def evaluate_language_tag(
|
||||
@@ -73,23 +79,13 @@ def rule_matches(
|
||||
|
||||
has_condition = False
|
||||
|
||||
audio_lang = rule.get("audio")
|
||||
if audio_lang is not None:
|
||||
has_condition = True
|
||||
if not any(_matches(lang, audio_languages) for lang in _as_list(audio_lang)):
|
||||
return False
|
||||
|
||||
subs_contain = rule.get("subs_contain")
|
||||
if subs_contain is not None:
|
||||
has_condition = True
|
||||
if not any(_matches(lang, subtitle_languages) for lang in _as_list(subs_contain)):
|
||||
return False
|
||||
|
||||
subs_contain_all = rule.get("subs_contain_all")
|
||||
if subs_contain_all is not None:
|
||||
has_condition = True
|
||||
for lang in _as_list(subs_contain_all):
|
||||
if not _matches(lang, subtitle_languages):
|
||||
for name, (subs, quantifier) in LANGUAGE_CONDITIONS.items():
|
||||
wanted = rule.get(name)
|
||||
if wanted is not None:
|
||||
has_condition = True
|
||||
wanted_langs = _as_list(wanted)
|
||||
languages = subtitle_languages if subs else audio_languages
|
||||
if not wanted_langs or not quantifier(_matches(lang, languages) for lang in wanted_langs):
|
||||
return False
|
||||
|
||||
for name in STATE_CONDITIONS:
|
||||
|
||||
Reference in New Issue
Block a user