refactor(core): one TitleSource base for Service, remote and import

This commit is contained in:
imSp4rky
2026-11-25 21:46:55 -07:00
parent 9febbb20c5
commit 92e8abbdbc
21 changed files with 619 additions and 470 deletions
+1 -7
View File
@@ -101,16 +101,10 @@ Declared at class level to configure framework behaviour:
| `VAULT_TAG` | `Optional[str]` | Overrides the key-vault namespace so sibling services can share one vault. Default `None` (use the service's own tag). | | `VAULT_TAG` | `Optional[str]` | Overrides the key-vault namespace so sibling services can share one vault. Default `None` (use the service's own tag). |
| `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Auth methods accepted (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. | | `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Auth methods accepted (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. |
| `ANONYMOUS_SEARCH` | `bool` | Set `True` when `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. | | `ANONYMOUS_SEARCH` | `bool` | Set `True` when `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. |
| `NO_SUBTITLES` | `bool` | Set `True` on a service with no subtitle tracks to skip subtitle handling entirely. | | `NO_SUBTITLES` | `bool` | Set `True` on a service with no subtitle tracks to skip subtitle handling entirely. Default `False`. |
| `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | | `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. |
| `DAILY` | `bool` | Set `True` when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own `daily` flag overrides it. | | `DAILY` | `bool` | Set `True` when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own `daily` flag overrides it. |
!!! note "`NO_SUBTITLES` is a convention, not a base-class attribute"
`dl.py` uses `hasattr` to find `NO_SUBTITLES`, and the `Service` base class
deliberately does **not** declare it, so it only exists if your service
defines it. Setting `NO_SUBTITLES = True` is what makes the pipeline skip
subtitle work for services that never carry subtitles. Leave it off otherwise.
`GEOFENCE` drives an automatic proxy: on startup, if you did not pass an `GEOFENCE` drives an automatic proxy: on startup, if you did not pass an
explicit `--proxy`, the base class does a live IP check and, if your region is explicit `--proxy`, the base class does a live IP check and, if your region is
blocked, fetches a proxy to `GEOFENCE[0]` from your configured proxy providers. blocked, fetches a proxy to `GEOFENCE[0]` from your configured proxy providers.
+6 -2
View File
@@ -1,8 +1,11 @@
# Service API # Service API
Auto-generated reference for the [`Service`][unshackle.core.service.Service] base class that every Auto-generated reference for the [`Service`][unshackle.core.service.Service] base class that every
service plugin subclasses. See [Creating a Service](../../dev/creating-a-service.md) for a guided service plugin subclasses. `Service` is one of three title sources: the remote client and the import are
walkthrough and [Service Architecture](../../dev/service-architecture.md) for the wider object model. the other two. The licence callbacks, the sample decrypter and the event hooks come from the shared base,
`unshackle.core.title_source.TitleSource`, and this page shows them on `Service`. See
[Creating a Service](../../dev/creating-a-service.md) for a guided walkthrough and
[Service Architecture](../../dev/service-architecture.md) for the wider object model.
::: unshackle.core.service ::: unshackle.core.service
options: options:
@@ -10,3 +13,4 @@ walkthrough and [Service Architecture](../../dev/service-architecture.md) for th
show_source: true show_source: true
members_order: source members_order: source
heading_level: 2 heading_level: 2
inherited_members: true
+1 -1
View File
@@ -151,7 +151,7 @@ ignore = ["UP042"]
# names in __all__ are intentionally not defined statically. # names in __all__ are intentionally not defined statically.
"unshackle/core/binaries.py" = ["F822"] "unshackle/core/binaries.py" = ["F822"]
# Optional hooks with a no-op default: a service or vault overrides only the ones it needs. # Optional hooks with a no-op default: a service or vault overrides only the ones it needs.
"unshackle/core/service.py" = ["B027"] "unshackle/core/title_source.py" = ["B027"]
"unshackle/core/vault.py" = ["B027"] "unshackle/core/vault.py" = ["B027"]
[tool.isort] [tool.isort]
@@ -1,19 +0,0 @@
"""ImportService and RemoteService stand in for a Service in dl, so they have every method dl calls on one."""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from unshackle.commands import dl as dl_module
from unshackle.core.import_service import ImportService
from unshackle.core.remote_service import RemoteService
@pytest.mark.parametrize("cls", [ImportService, RemoteService])
def test_stand_in_service_has_every_method_dl_calls(cls: type) -> None:
called = set(re.findall(r"\bservice\.(\w+)\(", Path(dl_module.__file__).read_text(encoding="utf-8")))
assert called
assert sorted(name for name in called if not hasattr(cls, name)) == []
+172
View File
@@ -0,0 +1,172 @@
"""Each title source states how its content keys reach dl, what its caches file it under, and whose login it saves."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
from uuid import UUID
import pytest
import requests
from tests.core.test_export import crit_export, import_ctx
from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_kind_only_selection import FakeService
from tests.remote.key_source import MemoryKeySource, remote_keys
from unshackle.commands import dl as dl_module
from unshackle.core.drm import PlayReady, Widevine
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.import_service import ImportService
from unshackle.core.service import Service
from unshackle.core.title_cacher import get_account_hash
from unshackle.core.title_source import CacheIdentity, KeyArrival
KIDS = [UUID(int=1).hex, UUID(int=2).hex]
class ExampleService(Service):
def get_titles(self) -> Any: ...
def get_tracks(self, title: Any) -> Any: ...
def get_chapters(self, title: Any) -> Any: ...
def service(**attrs: Any) -> ExampleService:
"""An ExampleService with only ``attrs`` set, as ``Service.__init__`` needs a config and a network."""
svc = object.__new__(ExampleService)
svc.__dict__.update(attrs)
return svc
def an_import(tmp_path: Path) -> ImportService:
return ImportService(import_ctx(), "EXAMPLE", "movie-1", str(crit_export(tmp_path / "export.json")))
def test_a_service_licenses_through_its_callbacks_and_has_no_key_source() -> None:
svc = service()
assert (svc.key_arrival, svc.key_source) == (KeyArrival.CALLBACK, None)
@pytest.mark.parametrize(("server_cdm", "arrival"), [(True, KeyArrival.SERVER), (False, KeyArrival.CALLBACK)])
def test_a_remote_session_follows_the_server_cdm_and_is_its_own_key_source(
server_cdm: bool, arrival: KeyArrival
) -> None:
"""Without the server CDM the challenge relay licenses, but the server vault still answers through the session."""
remote = remote_keys(server_cdm=server_cdm)
assert (remote.key_arrival, remote.key_source) == (arrival, remote)
def test_an_import_takes_the_keys_from_the_export(tmp_path: Path) -> None:
imported = an_import(tmp_path)
assert (imported.key_arrival, imported.key_source) == (KeyArrival.EXPORT, imported)
@pytest.mark.parametrize("attr", ["title", "title_id"])
def test_a_service_is_cached_under_the_title_id_it_keeps(attr: str) -> None:
svc = service(**{attr: "show-1", "title_cache": "cacher", "current_region": "gb"})
assert svc.cache_identity() == CacheIdentity("cacher", "show-1", "gb", get_account_hash(None))
def test_a_service_with_no_title_id_has_none_to_cache_under() -> None:
assert service().cache_identity().title_id is None
def test_a_remote_session_and_an_import_have_no_title_cache(tmp_path: Path) -> None:
remote = remote_keys()
remote.title_id = "show-1"
assert remote.cache_identity() == CacheIdentity(None, "show-1", None, None)
assert an_import(tmp_path).cache_identity() == CacheIdentity(None, "movie-1", None, None)
def test_only_a_service_saves_its_login_cookies(tmp_path: Path) -> None:
session = requests.Session()
assert service(session=session).login_cookies is session.cookies
assert remote_keys().login_cookies is None
assert an_import(tmp_path).login_cookies is None
def test_the_source_defaults_leave_a_track_alone() -> None:
"""A source that defines no hooks, sample decrypter or licence callback gets the no-op base."""
svc = service(log=logging.getLogger("test"))
assert not svc.decrypts_samples(None) # type: ignore[arg-type]
assert svc.get_widevine_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
assert svc.get_playready_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
with pytest.raises(NotImplementedError):
svc.get_sample_decrypter(None, 1) # type: ignore[arg-type]
svc.close()
def test_a_playready_stub_names_every_kid() -> None:
stub = drm_stub("playready", KIDS)
assert isinstance(stub, PlayReady)
assert [kid.hex for kid in stub.kids] == KIDS
@pytest.mark.parametrize("drm_type", ["widevine", "other"])
def test_any_other_stub_is_widevine_and_names_every_kid(drm_type: str) -> None:
stub = drm_stub(drm_type, KIDS)
assert isinstance(stub, Widevine)
assert [kid.hex for kid in stub.pssh.key_ids] == KIDS
class KeyedSource(FakeService):
"""A harness source that states its key arrival and records what dl does with it at the end of a run."""
def __init__(self, arrival: KeyArrival, cookies: Any = None) -> None:
super().__init__({1: {}})
self.arrival = arrival
self.cookies = cookies
self.keys = MemoryKeySource()
self.keys.key_arrival = arrival
self.closed = 0
@property
def key_arrival(self) -> KeyArrival:
return self.arrival
@property
def key_source(self) -> Any:
return None if self.arrival is KeyArrival.CALLBACK else self.keys
@property
def login_cookies(self) -> Any:
return self.cookies
def close(self) -> None:
self.closed += 1
@pytest.mark.parametrize(
("arrival", "line"),
[
(KeyArrival.EXPORT, "Using keys from the export; no CDM required"),
(KeyArrival.SERVER, "Using server CDM (Widevine); no local CDM required"),
],
)
def test_dl_licenses_with_no_cdm_of_its_own_when_the_keys_arrive_from_the_source(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, arrival: KeyArrival, line: str
) -> None:
lines: list[str] = []
monkeypatch.setattr(logging.getLogger("test_kind_only"), "info", lambda msg, *a, **k: lines.append(msg))
saved: list[Any] = []
monkeypatch.setattr(dl_module.login, "save_cookies", lambda *a: saved.append(a))
source = KeyedSource(arrival)
assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
assert line in lines
assert (source.closed, saved) == (1, [])
def test_dl_saves_the_login_cookies_of_a_service(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
jar = requests.cookies.RequestsCookieJar()
saved: list[Any] = []
monkeypatch.setattr(dl_module.login, "get_cookie_path", lambda *a: tmp_path / "cookies.txt")
monkeypatch.setattr(dl_module.login, "get_cookie_jar", lambda *a: None)
monkeypatch.setattr(dl_module.login, "save_cookies", lambda path, cookies: saved.append(cookies))
source = KeyedSource(KeyArrival.CALLBACK, cookies=jar)
assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
assert saved == [jar]
assert source.closed == 1
@@ -11,16 +11,15 @@ from __future__ import annotations
import inspect import inspect
import logging import logging
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any
import pytest import pytest
import requests
from unshackle.commands.dl import dl from unshackle.commands.dl import dl
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.service import Service from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Episode, Series from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -42,17 +41,18 @@ class Harness(dl):
return None return None
class FakeService: class FakeService(TitleSource):
"""One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle, ``ko`` Korean audio.""" """One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle, ``ko`` Korean audio."""
def __init__(self, episodes: dict[int, dict[str, bool]]) -> None: def __init__(self, episodes: dict[int, dict[str, bool]]) -> None:
self.episodes = episodes self.episodes = episodes
self.session = None self.session = None
self.ctx = None
def authenticate(self, cookies: Any = None, credential: Any = None) -> None: def authenticate(self, cookies: Any = None, credential: Any = None) -> None:
pass pass
def get_titles_cached(self) -> Series: def get_titles(self) -> Series:
return Series( return Series(
Episode(id_=f"show-s01-e{n:03}", service=FakeService, title="Show", season=1, number=n, language="en") Episode(id_=f"show-s01-e{n:03}", service=FakeService, title="Show", season=1, number=n, language="en")
for n in self.episodes for n in self.episodes
@@ -124,10 +124,8 @@ def run(
kwargs.update(flags) kwargs.update(flags)
caplog.set_level(logging.WARNING, logger="test_kind_only") caplog.set_level(logging.WARNING, logger="test_kind_only")
service = service or FakeService(episodes) service = service or FakeService(episodes)
if to_end:
service.session = requests.Session()
try: try:
cmd.result(cast(Service, service), **kwargs) cmd.result(service, **kwargs)
except Selected as sel: except Selected as sel:
return sel.ids return sel.ids
except SystemExit as exc: except SystemExit as exc:
+2 -1
View File
@@ -5,6 +5,7 @@ from typing import Any
from uuid import UUID from uuid import UUID
from unshackle.core.remote_service import RemoteService, ServerVault from unshackle.core.remote_service import RemoteService, ServerVault
from unshackle.core.title_source import KeyArrival
def remote_keys( def remote_keys(
@@ -31,7 +32,7 @@ class MemoryKeySource:
A ``licence`` of None hands the track to this machine, as a capped server does. A ``licence`` of None hands the track to this machine, as a capped server does.
""" """
server_cdm = True key_arrival = KeyArrival.SERVER
server_cdm_type = "widevine" server_cdm_type = "widevine"
server_vault: Any = None server_vault: Any = None
@@ -1,10 +1,4 @@
"""Contract tests for the RemoteService adapter. """RemoteService licence callbacks that must not touch the remote session."""
RemoteService copies the Service interface but does not inherit from it. When a
method is added to the base Service and wired into dl.py, nothing forces it onto
the adapter, so it can go missing here until a real download calls it. These
tests pin the methods dl.py depends on so a gap fails in CI, not on the devbox.
"""
from __future__ import annotations from __future__ import annotations
@@ -14,30 +8,6 @@ from unshackle.core.remote_service import RemoteService
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
SERVICE_CONTRACT = (
"authenticate",
"get_titles",
"get_titles_cached",
"get_tracks",
"get_chapters",
"get_widevine_license",
"get_playready_license",
"get_clearkey_license",
"get_widevine_service_certificate",
"resolve_server_keys",
"on_segment_downloaded",
"on_track_downloaded",
"on_track_decrypted",
"on_track_repacked",
"on_track_multiplex",
"close",
)
@pytest.mark.parametrize("name", SERVICE_CONTRACT)
def test_remote_service_implements_contract(name: str) -> None:
assert callable(getattr(RemoteService, name, None)), f"RemoteService is missing {name}()"
def test_get_clearkey_license_returns_none() -> None: def test_get_clearkey_license_returns_none() -> None:
# Regression: clearkey uses no CDM, so the adapter returns None and the # Regression: clearkey uses no CDM, so the adapter returns None and the
@@ -647,7 +647,7 @@ def _remote_service(parent_params: dict, service_params: dict) -> RemoteService:
svc._server_accounts = {"global": True} svc._server_accounts = {"global": True}
svc._server_cdm = True svc._server_cdm = True
svc._service_params = service_params svc._service_params = service_params
svc._session = requests.Session() svc.session = requests.Session()
svc.log = logging.getLogger("test") svc.log = logging.getLogger("test")
svc.client = SimpleNamespace(post=post, server_url="https://server.example") svc.client = SimpleNamespace(post=post, server_url="https://server.example")
return svc return svc
@@ -671,8 +671,8 @@ def test_the_client_session_downloads_through_the_proxy_it_sends(
svc = _remote_service({"no_proxy": no_proxy, "proxy": "http://proxy.example:8080"}, {}) svc = _remote_service({"no_proxy": no_proxy, "proxy": "http://proxy.example:8080"}, {})
with pytest.raises(_SentCreate) as exc: with pytest.raises(_SentCreate) as exc:
svc.authenticate() svc.authenticate()
assert dict(svc._session.proxies) == expected assert dict(svc.session.proxies) == expected
assert svc._session.trust_env is no_proxy # a proxied session ignores HTTP(S)_PROXY assert svc.session.trust_env is no_proxy # a proxied session ignores HTTP(S)_PROXY
assert exc.value.args[0].get("proxy") == (None if no_proxy else "http://proxy.example:8080") assert exc.value.args[0].get("proxy") == (None if no_proxy else "http://proxy.example:8080")
@@ -17,6 +17,7 @@ from tests.remote.sessions import session_entry
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.drm import BlowfishStripe from unshackle.core.drm import BlowfishStripe
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.remote_service import RemoteService from unshackle.core.remote_service import RemoteService
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -286,7 +287,7 @@ def test_resolve_server_keys_names_only_the_manifest_kids():
widevine = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID])) widevine = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]))
assert resolve([widevine]).kids == [KID] assert resolve([widevine]).kids == [KID]
playready = RemoteService.create_drm_stub("playready", [KID.hex]) playready = drm_stub("playready", [KID.hex])
assert resolve([playready], "playready").kids == [KID] assert resolve([playready], "playready").kids == [KID]
+3 -2
View File
@@ -25,6 +25,7 @@ from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.drm import Widevine, key_resolution from unshackle.core.drm import Widevine, key_resolution
from unshackle.core.remote_service import RemoteService from unshackle.core.remote_service import RemoteService
from unshackle.core.title_source import KeyArrival
from unshackle.core.vaults import Vaults from unshackle.core.vaults import Vaults
from unshackle.vaults.SQLite import SQLite from unshackle.vaults.SQLite import SQLite
@@ -134,7 +135,7 @@ def decrypt(
assert vaults.get_key(VAULTED) == (OTHER_KEY, local) assert vaults.get_key(VAULTED) == (OTHER_KEY, local)
pushed: list = [] pushed: list = []
source = SimpleNamespace( source = SimpleNamespace(
server_cdm=False, key_arrival=KeyArrival.CALLBACK,
server_vault=SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track))), server_vault=SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track))),
) )
keys = resolver(vaults, tag="EXAMPLE", source=source) keys = resolver(vaults, tag="EXAMPLE", source=source)
@@ -306,7 +307,7 @@ def test_cdm_only_declines_the_server_cdm_and_its_vault(monkeypatch, tmp_path) -
try: try:
svc.authenticate() svc.authenticate()
assert svc.posts[0]["server_cdm"] is False assert svc.posts[0]["server_cdm"] is False
assert (svc.server_cdm, svc._server_vault) == (False, False) assert (svc.key_arrival, svc._server_vault) == (KeyArrival.CALLBACK, False)
svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[]))) svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[])))
assert len(svc.posts) == 1 assert len(svc.posts) == 1
finally: finally:
+3 -3
View File
@@ -125,7 +125,7 @@ def test_remote_get_tracks_scopes_server_cookies():
_title_alias={}, _title_alias={},
_sample_decrypt_tracks=set(), _sample_decrypt_tracks=set(),
_server_cdm=None, _server_cdm=None,
_session=requests.Session(), session=requests.Session(),
_session_id="s", _session_id="s",
service_tag="EXAMPLE", service_tag="EXAMPLE",
log=logging.getLogger("test"), log=logging.getLogger("test"),
@@ -133,9 +133,9 @@ def test_remote_get_tracks_scopes_server_cookies():
drain_server_logs=lambda: None, drain_server_logs=lambda: None,
) )
service.get_tracks(SimpleNamespace(id="t1")) service.get_tracks(SimpleNamespace(id="t1"))
cdn = service._session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4")) cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
assert "Cookie" not in cdn.headers assert "Cookie" not in cdn.headers
assert service._session.cookies.get("sid", domain=".example.com") == "secret" assert service.session.cookies.get("sid", domain=".example.com") == "secret"
def test_server_login_strips_auth(): def test_server_login_strips_auth():
+21 -37
View File
@@ -79,10 +79,10 @@ from unshackle.core.proxies.resolve import (
split_proxy_query, split_proxy_query,
) )
from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options
from unshackle.core.service import Service, grow_session_pool from unshackle.core.service import grow_session_pool
from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.services import ROUTING_PARAMS, Services
from unshackle.core.temp import with_task_temp from unshackle.core.temp import with_task_temp
from unshackle.core.title_cacher import get_account_hash from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Movie, Movies, Series, Song, Title_T from unshackle.core.titles import Movie, Movies, Series, Song, Title_T
from unshackle.core.titles.episode import Episode from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -134,7 +134,7 @@ from unshackle.core.vaults import Vaults, load_config_vaults
if TYPE_CHECKING: if TYPE_CHECKING:
import pysubs2 import pysubs2
from unshackle.core.remote_service import ServerKeySource from unshackle.core.title_source import ServerKeySource
class SkippedTitle(TypedDict): class SkippedTitle(TypedDict):
@@ -252,7 +252,7 @@ def apply_enrich(title: Title_T, name: str | None, year: int | None, language: L
def load_tracks( def load_tracks(
service: Service, service: TitleSource,
title: Title_T, title: Title_T,
*, *,
name: str | None = None, name: str | None = None,
@@ -1124,6 +1124,7 @@ class dl:
export_snapshots: dict[str, dict[str, Any] | None] export_snapshots: dict[str, dict[str, Any] | None]
keys: ContentKeyResolver keys: ContentKeyResolver
_remote_service: ServerKeySource | None = None _remote_service: ServerKeySource | None = None
export_service: TitleSource | None = None
typed_params: frozenset[str] = frozenset() typed_params: frozenset[str] = frozenset()
def __init__( def __init__(
@@ -1451,7 +1452,7 @@ class dl:
@with_task_temp @with_task_temp
def result( def result(
self, self,
service: Service, service: TitleSource,
quality: list[int], quality: list[int],
vcodec: list[Video.Codec], vcodec: list[Video.Codec],
acodec: list[Audio.Codec], acodec: list[Audio.Codec],
@@ -1537,14 +1538,12 @@ class dl:
config.sample = sample config.sample = sample
self.tmdb_searched = False self.tmdb_searched = False
self.search_source = None self.search_source = None
self.service_anime = bool(getattr(service, "ANIME", False)) self.service_anime = service.ANIME
self.service_daily = bool(getattr(service, "DAILY", False)) self.service_daily = service.DAILY
from unshackle.core.import_service import SERVER_KEY_SOURCES, ImportService
# a remote session sends --cdm to the server, which can hand it the tracks above its cap # a remote session sends --cdm to the server, which can hand it the tracks above its cap
if self.cdm_override and isinstance(service, ImportService): if self.cdm_override and service.key_arrival is KeyArrival.EXPORT:
self.log.warning("--cdm is ignored: an import uses the keys in the export") self.log.warning("--cdm is ignored: an import uses the keys in the export")
self._remote_service = service if isinstance(service, SERVER_KEY_SOURCES) else None self._remote_service = service.key_source
start_time = time.time() start_time = time.time()
lang, lang_excl = partition_exclusions(lang) lang, lang_excl = partition_exclusions(lang)
@@ -1560,7 +1559,7 @@ class dl:
video_excl = inherited_exclusions(v_lang, v_lang_excl, lang_excl) video_excl = inherited_exclusions(v_lang, v_lang_excl, lang_excl)
audio_excl = inherited_exclusions(a_lang, a_lang_excl, lang_excl) audio_excl = inherited_exclusions(a_lang, a_lang_excl, lang_excl)
ctx = getattr(service, "ctx", None) ctx = service.ctx
parent_params = ctx.parent.params if ctx and ctx.parent else None parent_params = ctx.parent.params if ctx and ctx.parent else None
if parent_params is not None: if parent_params is not None:
# services read the raw ctx params, they must never see a '-xx' token # services read the raw ctx params, they must never see a '-xx' token
@@ -1728,14 +1727,7 @@ class dl:
level="INFO", operation="get_titles", service=self.service, context={"titles": titles_info} level="INFO", operation="get_titles", service=self.service, context={"titles": titles_info}
) )
title_cacher = service.title_cache if hasattr(service, "title_cache") else None title_cacher, cache_title_id, cache_region, cache_account_hash = service.cache_identity()
cache_title_id = None
if hasattr(service, "title"):
cache_title_id = service.title
elif hasattr(service, "title_id"):
cache_title_id = service.title_id
cache_region = service.current_region if hasattr(service, "current_region") else None
cache_account_hash = get_account_hash(service.credential) if hasattr(service, "credential") else None
enrich_lang: Language | None = None enrich_lang: Language | None = None
enrich_title: str | None = None enrich_title: str | None = None
@@ -2223,7 +2215,7 @@ class dl:
elif proxy_download: elif proxy_download:
console.log(f"Using a separate proxy for downloads: {mask_proxy(proxy_download)}") console.log(f"Using a separate proxy for downloads: {mask_proxy(proxy_download)}")
outcome = selection.select(title, bool(getattr(service, "NO_SUBTITLES", False))) outcome = selection.select(title, service.NO_SUBTITLES)
if isinstance(outcome, Skip): if isinstance(outcome, Skip):
skip_title(title, outcome.reason, outcome.kind_only) skip_title(title, outcome.reason, outcome.kind_only)
continue continue
@@ -2266,12 +2258,10 @@ class dl:
download_table.add_row(selected_tracks) download_table.add_row(selected_tracks)
server_cdm_type = None server_cdm_type = None
if self._remote_service and self._remote_service.server_cdm: if self._remote_service and self._remote_service.key_arrival.needs_no_cdm:
server_cdm_type = self._remote_service.server_cdm_type server_cdm_type = self._remote_service.server_cdm_type
self.cdm = cdm_type_stub(server_cdm_type) self.cdm = cdm_type_stub(server_cdm_type)
from unshackle.core.import_service import ImportService if self._remote_service.key_arrival is KeyArrival.EXPORT:
if isinstance(self._remote_service, ImportService):
self.log.info("Using keys from the export; no CDM required") self.log.info("Using keys from the export; no CDM required")
else: else:
self.log.info(f"Using server CDM ({server_cdm_type.title()}); no local CDM required") self.log.info(f"Using server CDM ({server_cdm_type.title()}); no local CDM required")
@@ -2554,12 +2544,7 @@ class dl:
if has_decrypted: if has_decrypted:
self.log.info("Decrypted tracks") self.log.info("Decrypted tracks")
if ( if not no_subs and not service.NO_SUBTITLES and not video_only and not no_video:
not no_subs
and not (hasattr(service, "NO_SUBTITLES") and service.NO_SUBTITLES)
and not video_only
and not no_video
):
for video_track_n, video_track in enumerate(title.tracks.videos): for video_track_n, video_track in enumerate(title.tracks.videos):
has_manifest_cc = bool(getattr(video_track, "closed_captions", None)) has_manifest_cc = bool(getattr(video_track, "closed_captions", None))
has_eia_cc = ( has_eia_cc = (
@@ -2764,13 +2749,12 @@ class dl:
if progress_sink: if progress_sink:
progress_sink({"output_files": [str(p) for p in self.completed_files]}) progress_sink({"output_files": [str(p) for p in self.completed_files]})
if not hasattr(service, "close"): if service.login_cookies is not None:
cookie_file = login.get_cookie_path(self.service, self.profile) cookie_file = login.get_cookie_path(self.service, self.profile)
if cookie_file: if cookie_file:
login.save_cookies(cookie_file, service.session.cookies) login.save_cookies(cookie_file, service.login_cookies)
self.keys.wait_vault_writes() self.keys.wait_vault_writes()
if hasattr(service, "close"):
service.close() service.close()
if post_script_folders and post_script_sample: if post_script_folders and post_script_sample:
@@ -3072,7 +3056,7 @@ class dl:
doc.generator.setdefault("app", "unshackle") doc.generator.setdefault("app", "unshackle")
doc.generator.setdefault("version", __version__) doc.generator.setdefault("version", __version__)
if not doc.region and getattr(self, "proxy_requested", False): if not doc.region and getattr(self, "proxy_requested", False):
doc.region = getattr(getattr(self, "export_service", None), "current_region", None) or "" doc.region = (self.export_service and self.export_service.current_region) or ""
entry = doc.get(str(title.id)) entry = doc.get(str(title.id))
if entry is None: if entry is None:
@@ -3194,7 +3178,7 @@ class dl:
manifest_type = next( manifest_type = next(
(t.descriptor.name.lower() for t in all_tracks if t.descriptor != Video.Descriptor.URL), "" (t.descriptor.name.lower() for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
) )
session = getattr(getattr(self, "export_service", None), "session", None) session = self.export_service.session if self.export_service else None
# mediaexport drops Cookie and Authorization itself, on write and on read # mediaexport drops Cookie and Authorization itself, on write and on read
headers = dict(getattr(session, "headers", None) or {}) headers = dict(getattr(session, "headers", None) or {})
manifests = ( manifests = (
@@ -3310,7 +3294,7 @@ class dl:
return [":x: Download Failed...", f" {line}"] return [":x: Download Failed...", f" {line}"]
def start_key_resolution( def start_key_resolution(
self, service: Service, *, cdm_only: bool, vaults_only: bool, best_available: bool, export: Path | None self, service: TitleSource, *, cdm_only: bool, vaults_only: bool, best_available: bool, export: Path | None
) -> None: ) -> None:
"""Build the run's content-key resolution and make its verified decrypt the decrypt hook.""" """Build the run's content-key resolution and make its verified decrypt the decrypt hook."""
self.keys = ContentKeyResolver( self.keys = ContentKeyResolver(
+3 -4
View File
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta from datetime import datetime, timedelta
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, Any, cast from typing import TYPE_CHECKING, Any
from unshackle.core.api.events import bus, publish_service_event from unshackle.core.api.events import bus, publish_service_event
from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.sanitize import sanitize_log
@@ -23,7 +23,7 @@ from unshackle.core.credential import Credential
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.service import Service from unshackle.core.title_source import TitleSource
log = logging.getLogger("download_manager") log = logging.getLogger("download_manager")
@@ -434,8 +434,7 @@ def perform_download(
from unshackle.core.remote_service import make_remote_service from unshackle.core.remote_service import make_remote_service
service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj) service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj)
# RemoteService duck-types Service for dl.result() service_instance: TitleSource = make_remote_service(service_ctx, remote, service, title_id, params)
service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params))
else: else:
service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS) service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS)
+22
View File
@@ -105,6 +105,28 @@ def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | Non
return Widevine(pssh=pssh, kid=tag_kid or kid, **extra_params) return Widevine(pssh=pssh, kid=tag_kid or kid, **extra_params)
def drm_stub(drm_type: str, kid_hexes: list[str]) -> Widevine | PlayReady:
"""A PlayReady (``drm_type`` ``playready``) or else Widevine DRM that names ``kid_hexes``, to hold content keys got without its PSSH.
The PSSH is built here, so it is for display only: the caller already has the content keys.
"""
from unshackle.core.drm.playready import PlayReady
from unshackle.core.drm.widevine import Widevine
kids = [UUID(hex=k) for k in kid_hexes]
if drm_type != "playready":
# no kid: the stub names several KIDs, and the first is not the track's own
return Widevine(pssh=WV_PSSH.new(system_id=WIDEVINE_ID, key_ids=[*kids]))
wrm_header = (
'<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0">'
"<DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO>"
f"<KID>{base64.b64encode(kids[0].bytes_le).decode()}</KID></DATA></WRMHEADER>"
)
drm = PlayReady.from_pssh_b64(base64.b64encode(wrm_header.encode("utf-16-le")).decode())
drm.kids.extend(kid for kid in kids if kid not in drm.kids)
return drm
def tag_key_id(value: Any) -> UUID | None: def tag_key_id(value: Any) -> UUID | None:
"""The KID of an EXT-X-KEY KEYID or KID attribute, or None when it is absent, a placeholder or not a KID.""" """The KID of an EXT-X-KEY KEYID or KID attribute, or None when it is absent, a placeholder or not a KID."""
try: try:
+5 -5
View File
@@ -36,7 +36,7 @@ from unshackle.core.drm import (
real_kids, real_kids,
verify, verify,
) )
from unshackle.core.service import Service from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Title_T from unshackle.core.titles import Title_T
from unshackle.core.tracks import Video from unshackle.core.tracks import Video
from unshackle.core.utilities import declared_kwargs, log_event from unshackle.core.utilities import declared_kwargs, log_event
@@ -46,7 +46,7 @@ from unshackle.core.vault import Vault
from unshackle.core.vaults import Vaults from unshackle.core.vaults import Vaults
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.remote_service import ServerKeySource from unshackle.core.title_source import ServerKeySource
from unshackle.core.utilities import DebugLogger from unshackle.core.utilities import DebugLogger
@@ -90,7 +90,7 @@ class ContentKeyResolver:
self, self,
vaults: Vaults, vaults: Vaults,
cdms: CdmChooser, cdms: CdmChooser,
service: Service, service: TitleSource,
tag: str, tag: str,
source: ServerKeySource | None = None, source: ServerKeySource | None = None,
cdm_only: bool = False, cdm_only: bool = False,
@@ -274,7 +274,7 @@ class ContentKeyResolver:
def passes_left(done: int) -> bool: def passes_left(done: int) -> bool:
"""One pass per source that can still answer: every loaded vault, the server's vaults as """One pass per source that can still answer: every loaded vault, the server's vaults as
one source that walks them itself over --remote, and one for the CDM.""" one source that walks them itself over --remote, and one for the CDM."""
remote = 1 if self.source and self.source.server_cdm else 0 remote = 1 if self.source and self.source.key_arrival.needs_no_cdm else 0
return done < len(self.vaults) + remote + 1 return done < len(self.vaults) + remote + 1
try: try:
@@ -832,7 +832,7 @@ class ContentKeyResolver:
if not drm: if not drm:
return return
remote = self.source remote = self.source
server_cdm = bool(remote and remote.server_cdm) server_cdm = bool(remote and remote.key_arrival.needs_no_cdm)
licensed_locally = bool(remote and remote.licenses_locally(track)) licensed_locally = bool(remote and remote.licenses_locally(track))
if server_cdm and not licensed_locally: if server_cdm and not licensed_locally:
+17 -41
View File
@@ -18,10 +18,12 @@ from unshackle.core.config import config
from unshackle.core.constants import AnyTrack from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.drm import ClearKey, MonaLisa, real_kids from unshackle.core.drm import ClearKey, MonaLisa, real_kids
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.remote_service import RemoteService, ServerKeySource, resolve_proxy_arg, segment_uri_filter from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter
from unshackle.core.session import failure_response, utf8_text from unshackle.core.session import failure_response, utf8_text
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment from unshackle.core.tracks.attachment import Attachment
@@ -218,19 +220,14 @@ def int_or_none(value: Any) -> int | None:
return None return None
class ImportService: class ImportService(TitleSource):
"""Reconstructs a download from an export JSON. """Reconstructs a download from an export JSON.
ImportService does not authenticate and does not license. It rebuilds the tracks from ImportService does not authenticate and does not license. It rebuilds the tracks from
the export and injects the keys directly. It is a ``ServerKeySource``, so dl takes the keys the export and injects the keys directly. It is its own ``key_source``, so dl takes the keys
from the tracks and licenses nothing itself. from the tracks and licenses nothing itself.
""" """
ALIASES: tuple[str, ...] = ()
GEOFENCE: tuple[str, ...] = ()
GEOBLOCK: tuple[str, ...] = ()
NO_SUBTITLES: bool = False
server_cdm = True
local_cdm = None local_cdm = None
def __init__(self, ctx: click.Context, service_tag: str, title: str, import_file: str | None) -> None: def __init__(self, ctx: click.Context, service_tag: str, title: str, import_file: str | None) -> None:
@@ -239,9 +236,6 @@ class ImportService:
self.title_id = title self.title_id = title
self.ctx = ctx self.ctx = ctx
self.log = logging.getLogger(service_tag) self.log = logging.getLogger(service_tag)
self.credential: Credential | None = None
self.current_region: str | None = None
self.title_cache = None
if not import_file: if not import_file:
raise click.ClickException("No export file was provided to import from.") raise click.ClickException("No export file was provided to import from.")
@@ -354,6 +348,16 @@ class ImportService:
def title(self) -> str: def title(self) -> str:
return self.title_id return self.title_id
@property
def key_arrival(self) -> KeyArrival:
"""``EXPORT``: the keys come in the export file, and nothing licenses."""
return KeyArrival.EXPORT
@property
def key_source(self) -> ImportService:
"""This import, which puts the exported keys on the tracks."""
return self
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None: def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
self.credential = credential self.credential = credential
@@ -682,7 +686,7 @@ class ImportService:
stub_kids = list(keys) or sorted(row_kids or []) stub_kids = list(keys) or sorted(row_kids or [])
if drm_obj is None and stub_kids: if drm_obj is None and stub_kids:
drm_type = (drm_dicts[0].get("system", "Widevine").lower()) if drm_dicts else "widevine" drm_type = (drm_dicts[0].get("system", "Widevine").lower()) if drm_dicts else "widevine"
drm_obj = RemoteService.create_drm_stub(drm_type, stub_kids) drm_obj = drm_stub(drm_type, stub_kids)
if drm_obj is None: if drm_obj is None:
return None return None
@@ -745,7 +749,7 @@ class ImportService:
if isinstance(drm_obj, (ClearKey, MonaLisa)): if isinstance(drm_obj, (ClearKey, MonaLisa)):
continue continue
else: else:
drm_obj = RemoteService.create_drm_stub(system, [kid.hex for kid in (declared or pool)]) drm_obj = drm_stub(system, [kid.hex for kid in (declared or pool)])
for kid, key in keys.items(): for kid, key in keys.items():
drm_obj.content_keys[kid] = key drm_obj.content_keys[kid] = key
track.drm = [drm_obj] track.drm = [drm_obj]
@@ -823,9 +827,6 @@ class ImportService:
] ]
) )
def get_widevine_service_certificate(self, **_: Any) -> str | None:
return None
def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None: def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
raise self.missing_key(track) raise self.missing_key(track)
@@ -850,33 +851,8 @@ class ImportService:
APIErrorCode.DRM_ERROR, APIErrorCode.DRM_ERROR,
) )
def decrypts_samples(self, track: AnyTrack) -> bool:
return False
def get_sample_decrypter(self, track: AnyTrack, entry: int) -> bytes:
raise NotImplementedError("An import does not decrypt samples")
def on_segment_downloaded(self, track: AnyTrack, segment: Any) -> None:
pass
def on_track_downloaded(self, track: AnyTrack) -> None:
pass
def on_track_decrypted(self, track: AnyTrack, drm: Any, segment: Any = None) -> None:
pass
def on_track_repacked(self, track: AnyTrack) -> None:
pass
def on_track_multiplex(self, track: AnyTrack) -> None:
pass
def close(self) -> None: def close(self) -> None:
try: try:
self.session.close() self.session.close()
except Exception: except Exception:
pass pass
SERVER_KEY_SOURCES: tuple[type[ServerKeySource], ...] = (RemoteService, ImportService)
"""The services dl takes content keys from before ``prepare_drm``; mypy checks each against ServerKeySource."""
+25 -134
View File
@@ -1,7 +1,7 @@
"""Remote service adapter for unshackle. """Remote service adapter for unshackle.
Implements the Service interface by proxying authenticate, get_titles, A ``TitleSource`` that relays authenticate, get_titles, get_tracks,
get_tracks, get_chapters, and license methods to a remote unshackle server. get_chapters, and license methods to a remote unshackle server.
Everything else (track selection, download, decrypt, mux) runs locally. Everything else (track selection, download, decrypt, mux) runs locally.
""" """
@@ -24,7 +24,6 @@ from threading import Lock, local
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
Protocol,
TypeVar, TypeVar,
cast, cast,
) )
@@ -46,6 +45,7 @@ from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.dl_options import remote_dl_params from unshackle.core.dl_options import remote_dl_params
from unshackle.core.drm import cbcs, real_kids from unshackle.core.drm import cbcs, real_kids
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.launch import launch_keys from unshackle.core.launch import launch_keys
from unshackle.core.manifests.snapshot import match_track, restore from unshackle.core.manifests.snapshot import match_track, restore
from unshackle.core.proxies.resolve import is_loopback from unshackle.core.proxies.resolve import is_loopback
@@ -82,6 +82,7 @@ from unshackle.core.remote_protocol import (
) )
from unshackle.core.search_result import SearchResult from unshackle.core.search_result import SearchResult
from unshackle.core.session import MAX_BACKOFF from unshackle.core.session import MAX_BACKOFF
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Title_T, Titles_T, remap_titles from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.titles.episode import Episode, Series from unshackle.core.titles.episode import Episode, Series
from unshackle.core.titles.movie import Movies from unshackle.core.titles.movie import Movies
@@ -795,43 +796,6 @@ def cache_key_filter(service_tag: str, profile: str | None) -> Callable[[str], b
return relevant return relevant
class ServerKeySource(Protocol):
"""A service whose content keys dl gets before ``prepare_drm``: a remote session or an import."""
@property
def server_cdm(self) -> bool:
"""True when the keys come from the server CDM or the export, so dl licenses with no CDM of its own."""
@property
def server_cdm_type(self) -> str:
"""``widevine`` or ``playready``: the DRM system the keys came from."""
@property
def local_cdm(self) -> Any:
"""The CDM of this machine for a track ``licenses_locally`` names, or None."""
def resolve_server_keys(self, title: Title_T) -> None:
"""Put the content keys the server or the export holds on the tracks of ``title``."""
def licenses_locally(self, track: AnyTrack) -> bool:
"""True when this machine's own CDM licenses ``track`` instead of the server."""
def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""The content keys the server licenses for ``drm`` of ``track``, or None when it hands ``track`` to this machine's CDM.
Call it only for a track ``licenses_locally`` does not name; after None, it names the track. ``kid`` is
the KID the answer must hold. A failed request returns no keys. A refusal this machine cannot take over
raises ClickException.
"""
def vault_source(self, kid: UUID, key: str) -> Vault | None:
"""The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check."""
@property
def server_vault(self) -> ServerVault | None:
"""The server's vaults, which take the content keys a decrypt proved, or None."""
class ServerVault(Vault): class ServerVault(Vault):
"""The server's vaults as one source for the client, which reports bad pairs to it and pushes proven ones. """The server's vaults as one source for the client, which reports bad pairs to it and pushes proven ones.
@@ -882,19 +846,12 @@ class ServerVault(Vault):
self.service.report_bad_key(UUID(str(kid)), key) self.service.report_bad_key(UUID(str(kid)), key)
class RemoteService: class RemoteService(TitleSource):
"""Service adapter that proxies to a remote unshackle server. """The title source of a remote unshackle server: it relays titles, tracks, chapters and licences to it.
Implements the same interface dl.py's result() expects without It is not a Service, so it runs none of the proxy and geofence setup of ``Service.__init__``.
subclassing Service (avoids proxy/geofence setup in __init__).
""" """
ALIASES: tuple[str, ...] = ()
GEOFENCE: tuple[str, ...] = ()
GEOBLOCK: tuple[str, ...] = ()
NO_SUBTITLES: bool = False
ANIME: bool = False
DAILY: bool = False
server_cdm_type: str = "widevine" server_cdm_type: str = "widevine"
channel: Channel | None = None channel: Channel | None = None
@@ -919,9 +876,6 @@ class RemoteService:
self.ctx = ctx self.ctx = ctx
self._service_params = service_params or {} self._service_params = service_params or {}
self.log = logging.getLogger(service_tag) self.log = logging.getLogger(service_tag)
self.credential: Credential | None = None
self.current_region: str | None = None
self.title_cache = None
self._titles: Titles_T | None = None self._titles: Titles_T | None = None
self._tracks_by_title: dict[str, Tracks] = {} self._tracks_by_title: dict[str, Tracks] = {}
self._chapters_by_title: dict[str, list] = {} self._chapters_by_title: dict[str, list] = {}
@@ -942,9 +896,9 @@ class RemoteService:
self._title_alias: dict[str, str] = {} self._title_alias: dict[str, str] = {}
self._track_alias: dict[str, str] = {} self._track_alias: dict[str, str] = {}
self._session = requests.Session() self.session = requests.Session()
self._session.headers.update(config.headers) self.session.headers.update(config.headers)
self._session.mount( self.session.mount(
"https://", "https://",
HTTPAdapter( HTTPAdapter(
max_retries=Retry( max_retries=Retry(
@@ -957,7 +911,7 @@ class RemoteService:
pool_block=True, pool_block=True,
), ),
) )
self._session.mount("http://", self._session.adapters["https://"]) self.session.mount("http://", self.session.adapters["https://"])
svc_config = services_config.get(service_tag, {}) svc_config = services_config.get(service_tag, {})
self._server_cdm: bool | None = services_config.get("_server_cdm") self._server_cdm: bool | None = services_config.get("_server_cdm")
@@ -999,10 +953,6 @@ class RemoteService:
existing[key] = value existing[key] = value
config.services[self.service_tag] = existing config.services[self.service_tag] = existing
@property
def session(self) -> requests.Session:
return self._session
@property @property
def title(self) -> str: def title(self) -> str:
return self.title_id return self.title_id
@@ -1091,7 +1041,7 @@ class RemoteService:
try: try:
from unshackle.core.utils.ip_info import get_ip_info from unshackle.core.utils.ip_info import get_ip_info
ip_info = get_ip_info(self._session, cached=True) ip_info = get_ip_info(self.session, cached=True)
if ip_info and ip_info.get("country"): if ip_info and ip_info.get("country"):
client_region = ip_info["country"].lower() client_region = ip_info["country"].lower()
except Exception: except Exception:
@@ -1124,8 +1074,8 @@ class RemoteService:
self.require_reachable_proxy(create_data.get("proxy")) self.require_reachable_proxy(create_data.get("proxy"))
local_proxy = None if no_proxy else proxy if local else proxy or create_data.get("proxy") local_proxy = None if no_proxy else proxy if local else proxy or create_data.get("proxy")
if local_proxy: if local_proxy:
self._session.proxies["all"] = local_proxy self.session.proxies["all"] = local_proxy
run_proxy.pin(self._session) run_proxy.pin(self.session)
if not no_proxy and not proxy and client_region: if not no_proxy and not proxy and client_region:
create_data["client_region"] = client_region create_data["client_region"] = client_region
@@ -1480,8 +1430,8 @@ class RemoteService:
session_fields = cast(TracksReply, result) session_fields = cast(TracksReply, result)
for k, v in session_fields.get("session_headers", {}).items(): for k, v in session_fields.get("session_headers", {}).items():
if k.lower() not in ("host", "content-length", "content-type"): if k.lower() not in ("host", "content-length", "content-type"):
self._session.headers[k] = v self.session.headers[k] = v
apply_session_cookies(self._session, result) apply_session_cookies(self.session, result)
restore(tracks, result) restore(tracks, result)
apply_service_track_data(tracks, result) apply_service_track_data(tracks, result)
@@ -1624,7 +1574,7 @@ class RemoteService:
named = {kid.hex for drm in track.drm or [] for kid in real_kids(drm)} & track_keys.keys() named = {kid.hex for drm in track.drm or [] for kid in real_kids(drm)} & track_keys.keys()
track_drm_type = drm_types_by_track.get(server_id, server_drm_type) track_drm_type = drm_types_by_track.get(server_id, server_drm_type)
drm_obj = self.create_drm_stub(track_drm_type, sorted(named) or list(track_keys)) drm_obj = drm_stub(track_drm_type, sorted(named) or list(track_keys))
for kid_hex, key_hex in track_keys.items(): for kid_hex, key_hex in track_keys.items():
drm_obj.content_keys[UUID(hex=kid_hex)] = key_hex drm_obj.content_keys[UUID(hex=kid_hex)] = key_hex
track.drm = [drm_obj] track.drm = [drm_obj]
@@ -1700,9 +1650,14 @@ class RemoteService:
self.log.info(f"{why}; licensing track {track_log_label(track)} with your own {drm_class} device") self.log.info(f"{why}; licensing track {track_log_label(track)} with your own {drm_class} device")
@property @property
def server_cdm(self) -> bool: def key_arrival(self) -> KeyArrival:
"""True when the server CDM licenses this remote session, so dl licenses with no CDM of its own.""" """``SERVER`` when the server CDM licenses this remote session, else ``CALLBACK``: the challenge relay."""
return bool(self._server_cdm) return KeyArrival.SERVER if self._server_cdm else KeyArrival.CALLBACK
@property
def key_source(self) -> RemoteService:
"""This remote session: the server CDM, the server vault or this machine's CDM give the keys."""
return self
def licenses_locally(self, track: AnyTrack) -> bool: def licenses_locally(self, track: AnyTrack) -> bool:
"""True when the server handed ``track`` to this machine's own CDM to license.""" """True when the server handed ``track`` to this machine's own CDM to license."""
@@ -1734,52 +1689,6 @@ class RemoteService:
except (Exception, RemoteError) as e: except (Exception, RemoteError) as e:
self.log.debug(f"Could not report the bad content key to the server: {e}") self.log.debug(f"Could not report the bad content key to the server: {e}")
@staticmethod
def create_drm_stub(drm_type: str, kid_hexes: list[str]) -> Any:
"""Make a DRM object stub that matches the type the server used.
For server_cdm mode, unshackle uses this stub for display only, because it
already has the content keys. We assemble a minimal DRM object that holds
content_keys.
"""
from uuid import UUID
if drm_type == "playready":
import base64 as b64
import struct
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
from unshackle.core.drm import PlayReady
kid_uuids = [UUID(hex=k) for k in kid_hexes]
kid_b64 = b64.b64encode(kid_uuids[0].bytes_le).decode()
wrm_xml = (
'<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0">'
f"<DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO>"
f"<KID>{kid_b64}</KID></DATA></WRMHEADER>"
)
wrm_bytes = wrm_xml.encode("utf-16-le")
record_length = len(wrm_bytes)
obj_length = 4 + 2 + 2 + 2 + record_length
pr_obj = struct.pack("<IHH", obj_length, 1, 1) + struct.pack("<H", record_length) + wrm_bytes
pr_pssh = PlayReadyPSSH(pr_obj)
pssh_b64 = b64.b64encode(pr_obj).decode("ascii")
drm = PlayReady(pssh=pr_pssh, pssh_b64=pssh_b64)
for kid_uuid in kid_uuids:
if kid_uuid not in drm.kids:
drm.kids.append(kid_uuid)
return drm
else:
from pywidevine.pssh import PSSH as WvPSSH
from unshackle.core.drm import Widevine
WIDEVINE_SYSTEM_ID = UUID("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed")
dummy_pssh = WvPSSH.new(system_id=WIDEVINE_SYSTEM_ID, key_ids=[UUID(hex=k) for k in kid_hexes])
# no kid: the stub names several KIDs, and the first is not the track's own
return Widevine(pssh=dummy_pssh)
def get_chapters(self, title: Title_T) -> Chapters: def get_chapters(self, title: Title_T) -> Chapters:
title_id = str(title.id) title_id = str(title.id)
if title_id not in self._chapters_by_title: if title_id not in self._chapters_by_title:
@@ -1793,9 +1702,6 @@ class RemoteService:
def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None: def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
return self.proxy_license(challenge, track, "playready") return self.proxy_license(challenge, track, "playready")
def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
return None
def get_widevine_service_certificate( def get_widevine_service_certificate(
self, self,
*, *,
@@ -1887,21 +1793,6 @@ class RemoteService:
self.drain_server_logs() self.drain_server_logs()
return base64.b64decode(resp["license"]) return base64.b64decode(resp["license"])
def on_segment_downloaded(self, track: AnyTrack, segment: Any) -> None:
pass
def on_track_downloaded(self, track: AnyTrack) -> None:
pass
def on_track_decrypted(self, track: AnyTrack, drm: Any, segment: Any = None) -> None:
pass
def on_track_repacked(self, track: AnyTrack) -> None:
pass
def on_track_multiplex(self, track: AnyTrack) -> None:
pass
def close(self) -> None: def close(self) -> None:
# a long-lived serve opens many of these; the atexit hook would keep every one alive # a long-lived serve opens many of these; the atexit hook would keep every one alive
atexit.unregister(self.close) atexit.unregister(self.close)
+16 -166
View File
@@ -1,18 +1,15 @@
import logging import logging
import time import time
from abc import ABCMeta, abstractmethod from abc import abstractmethod
from collections.abc import Callable, Generator, Sequence from collections.abc import Callable, Generator, Sequence
from dataclasses import dataclass, field from dataclasses import dataclass, field
from http.cookiejar import CookieJar from http.cookiejar import CookieJar
from pathlib import Path from typing import TYPE_CHECKING, Any, TypeVar
from typing import TYPE_CHECKING, Any, TypeVar, Union
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.drm.cbcs import SampleDecrypter
import click import click
import m3u8
import requests import requests
from requests.adapters import HTTPAdapter, Retry from requests.adapters import HTTPAdapter, Retry
from rich.padding import Padding from rich.padding import Padding
@@ -21,9 +18,7 @@ from rich.rule import Rule
from unshackle.core.cacher import Cacher from unshackle.core.cacher import Cacher
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import console, prompt_user, show_notice from unshackle.core.console import console, prompt_user, show_notice
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T
from unshackle.core.launch import launch_keys from unshackle.core.launch import launch_keys
from unshackle.core.proxies.basic import Basic from unshackle.core.proxies.basic import Basic
from unshackle.core.proxies.resolve import pick_proxy from unshackle.core.proxies.resolve import pick_proxy
@@ -39,11 +34,11 @@ from unshackle.core.session import (
RETRY_METHODS, RETRY_METHODS,
STATUS_FORCELIST, STATUS_FORCELIST,
) )
from unshackle.core.title_cacher import TitleCacher, get_account_hash from unshackle.core.title_cacher import TitleCacher
from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Title_T, Titles_T, remap_titles from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Chapters, Tracks from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video from unshackle.core.tracks.video import Video
from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
from unshackle.core.utils.collections import ci_get from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
@@ -150,7 +145,7 @@ def sanitize_proxy_for_log(uri: str | None, mask_host: bool = False) -> str | No
T = TypeVar("T") T = TypeVar("T")
class Service(metaclass=ABCMeta): class Service(TitleSource):
"""The Service Base Class. """The Service Base Class.
A Service must define the abstract methods. The rest are optional overrides that fall back to the base A Service must define the abstract methods. The rest are optional overrides that fall back to the base
@@ -162,8 +157,6 @@ class Service(metaclass=ABCMeta):
ALIASES: tuple[str, ...] = () # alternative tags for the service, matched without case. ALIASES: tuple[str, ...] = () # alternative tags for the service, matched without case.
GEOFENCE: tuple[str, ...] = () # list of ip regions required to use the service. empty list == no specific region. GEOFENCE: tuple[str, ...] = () # list of ip regions required to use the service. empty list == no specific region.
GEOBLOCK: tuple[str, ...] = () # ip regions where the service refuses to work; everything else is allowed. GEOBLOCK: tuple[str, ...] = () # ip regions where the service refuses to work; everything else is allowed.
ANIME: bool = False # service catalogue is anime; metadata lookups prefer AniList. Title.anime overrides per title.
DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title.
ANONYMOUS_SEARCH: bool = False # search() needs no login; a search then skips cookies and authenticate(). ANONYMOUS_SEARCH: bool = False # search() needs no login; a search then skips cookies and authenticate().
# vault namespace override; when set, key vault read/write uses this tag instead of the service's own. # vault namespace override; when set, key vault read/write uses this tag instead of the service's own.
VAULT_TAG: str | None = None VAULT_TAG: str | None = None
@@ -189,7 +182,7 @@ class Service(metaclass=ABCMeta):
self.session = self.get_session() self.session = self.get_session()
self.cache = Cacher(self.__class__.__name__) self.cache = Cacher(self.__class__.__name__)
self.title_cache = TitleCacher(self.__class__.__name__) self.title_cache: TitleCacher = TitleCacher(self.__class__.__name__)
self.cache_dir = config.directories.cache / self.__class__.__name__ self.cache_dir = config.directories.cache / self.__class__.__name__
self.ctx = ctx self.ctx = ctx
@@ -307,6 +300,11 @@ class Service(metaclass=ABCMeta):
run_proxy.watch(type(self), run_proxy.proxy_of(self.session)) run_proxy.watch(type(self), run_proxy.proxy_of(self.session))
@property
def login_cookies(self) -> CookieJar | None:
"""The HTTP session cookies, which dl saves to the profile's cookie file after each title."""
return self.session.cookies
@classmethod @classmethod
def is_region_allowed(cls, region: str | None) -> bool: def is_region_allowed(cls, region: str | None) -> bool:
"""True when an exit IP in `region` (two-letter region code, any case) can use the service. """True when an exit IP in `region` (two-letter region code, any case) can use the service.
@@ -516,83 +514,6 @@ class Service(metaclass=ABCMeta):
""" """
raise NotImplementedError(f"Search functionality has not been implemented by {self.__class__.__name__}") raise NotImplementedError(f"Search functionality has not been implemented by {self.__class__.__name__}")
def get_widevine_service_certificate(
self, *, challenge: bytes, title: Title_T, track: AnyTrack
) -> bytes | str | None:
"""
Get the Widevine Service Certificate used for Privacy Mode.
:param challenge: The service challenge, providing this to a License endpoint should return the
privacy certificate that the service uses.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The Service Privacy Certificate as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a Widevine License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be
read by the Cdm and decrypted.
This is a very important request to get correct. A bad, unexpected, or missing
value in the request can cause the service to detect your CDM device.
The service can then ban, revoke, disable, or downgrade that device.
:param challenge: The license challenge from the Widevine CDM.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The License response as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a PlayReady License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be
read by the CDM and decrypted.
This is a very important request to get correct. A bad, unexpected, or missing
value in the request can cause the service to detect your CDM device.
The service can then ban, revoke, disable, or downgrade that device.
:param challenge: The license challenge from the PlayReady CDM.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The License response as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
# A service that implements Widevine licensing only still gets PlayReady, with the
# arguments its own signature declares.
return self.get_widevine_license(
**declared_kwargs(self.get_widevine_license, {"challenge": challenge, "title": title, "track": track})
)
def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
"""
Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).
Used for DASH `org.w3.clearkey` tracks. unshackle uses no CDM here: the challenge is
the W3C EME JSON license request, e.g. ``{"kids": ["<base64url>"], "type": "temporary"}``,
and the license is a JWK Set, e.g. ``{"keys": [{"kty": "oct", "k": "...", "kid": "..."}]}``.
:param challenge: The JSON license request bytes to POST to the license server.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default)
to let the framework POST the challenge to the manifest-provided Laurl, if any.
Services with no license server can instead pre-populate the DRM object's
`signatures` in get_tracks.
"""
return None
@abstractmethod @abstractmethod
def get_titles(self) -> Titles_T: def get_titles(self) -> Titles_T:
""" """
@@ -622,14 +543,10 @@ class Service(metaclass=ABCMeta):
Returns: Returns:
Titles object (Movies, Series, or Album) Titles object (Movies, Series, or Album)
""" """
identity = self.cache_identity()
if title_id is None:
title_id = identity.title_id
if title_id is None: if title_id is None:
# Different services store the title ID in different attributes
if hasattr(self, "title"):
title_id = self.title
elif hasattr(self, "title_id"):
title_id = self.title_id
else:
# If we can't determine title_id, just call get_titles directly
self.log.debug("Cannot determine title_id for caching, bypassing cache") self.log.debug("Cannot determine title_id for caching, bypassing cache")
return self.apply_title_map(self.get_titles()) return self.apply_title_map(self.get_titles())
@@ -639,14 +556,11 @@ class Service(metaclass=ABCMeta):
no_cache = self.ctx.parent.params.get("no_cache", False) no_cache = self.ctx.parent.params.get("no_cache", False)
reset_cache = self.ctx.parent.params.get("reset_cache", False) reset_cache = self.ctx.parent.params.get("reset_cache", False)
# Get account hash for cache key
account_hash = get_account_hash(self.credential)
titles = self.title_cache.get_cached_titles( titles = self.title_cache.get_cached_titles(
title_id=str(title_id), title_id=str(title_id),
fetch_function=self.get_titles, fetch_function=self.get_titles,
region=self.current_region, region=identity.region,
account_hash=account_hash, account_hash=identity.account_hash,
no_cache=no_cache, no_cache=no_cache,
reset_cache=reset_cache, reset_cache=reset_cache,
) )
@@ -712,69 +626,5 @@ class Service(metaclass=ABCMeta):
option `chapter_fallback_name`. For example, `"Chapter {i:02}"` for "Chapter 01". option `chapter_fallback_name`. For example, `"Chapter {i:02}"` for "Chapter 01".
""" """
# Optional sample decryption
def decrypts_samples(self, track: AnyTrack) -> bool:
"""Whether this service decrypts the cbcs file of `track` after the download, through `get_sample_decrypter`."""
return False
def get_sample_decrypter(self, track: AnyTrack, entry: int) -> Union[bytes, "SampleDecrypter"]:
"""The content key, or a `cbcs.SampleDecrypter`, for `stsd` entry `entry` (1-based) of `track`.
unshackle calls this only for a track `decrypts_samples` names. A remote session runs it on the
server, so a decrypter that needs a local process works for remote clients too.
"""
raise NotImplementedError(f"{self.__class__.__name__} does not decrypt samples")
# Optional Event methods
def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> None:
"""
Called when one of a Track's Segments has finished downloading.
Parameters:
track: The Track object that had a Segment downloaded.
segment: The Path to the downloaded Segment.
"""
def on_track_downloaded(self, track: AnyTrack) -> None:
"""
Called when a Track has finished downloading.
Parameters:
track: The downloaded Track object.
"""
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: m3u8.Segment | None = None) -> None:
"""
Called when a Track has finished decrypting.
Parameters:
track: The decrypted Track object.
drm: The DRM object it decrypted with.
segment: The decrypted HLS segment information. None for DASH and ISM tracks and
for an HLS track that merged during the download (merge_segments).
"""
def on_track_repacked(self, track: AnyTrack) -> None:
"""
Called when a Track has finished repacking.
Parameters:
track: The repacked Track object.
"""
def on_track_multiplex(self, track: AnyTrack) -> None:
"""
Called immediately before unshackle multiplexes a Track into a Container.
Note: Right now unshackle multiplexes only MKV containers. In the future
unshackle can also call this when it multiplexes to other containers like
MP4 with FFmpeg/mp4box.
Parameters:
track: The repacked Track object.
"""
__all__ = ("Service", "TrackRequest") __all__ = ("Service", "TrackRequest")
+305
View File
@@ -0,0 +1,305 @@
"""Where a download takes its titles, tracks, chapters and content keys from: a Service, a remote session or an import."""
from __future__ import annotations
import logging
from abc import ABCMeta, abstractmethod
from enum import Enum
from http.cookiejar import CookieJar
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple, Protocol
from uuid import UUID
import click
import m3u8
import requests
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T
from unshackle.core.title_cacher import TitleCacher, get_account_hash
from unshackle.core.titles import Title_T, Titles_T
from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.utilities import declared_kwargs
if TYPE_CHECKING:
from unshackle.core.drm.cbcs import SampleDecrypter
from unshackle.core.remote_service import ServerVault
from unshackle.core.vault import Vault
class KeyArrival(Enum):
"""How the content keys of a title source reach dl.
``CALLBACK``: dl's CDM licenses each track through the source's licence callbacks. ``SERVER``: the server CDM
licenses, and dl asks ``ServerKeySource.license_track``. ``EXPORT``: the keys come in the export file.
"""
CALLBACK = "callback"
SERVER = "server"
EXPORT = "export"
@property
def needs_no_cdm(self) -> bool:
"""True when the keys arrive with no licence from dl's own CDM: from the server or the export."""
return self is not KeyArrival.CALLBACK
class CacheIdentity(NamedTuple):
"""The cache and the keys that the title and metadata caches file the entries of a source under."""
cacher: TitleCacher | None
title_id: str | None
region: str | None
account_hash: str | None
class ServerKeySource(Protocol):
"""A title source whose content keys dl gets before ``prepare_drm``: a remote session or an import."""
@property
def key_arrival(self) -> KeyArrival:
"""``SERVER`` or ``EXPORT`` when dl licenses with no CDM of its own, else ``CALLBACK``."""
@property
def server_cdm_type(self) -> str:
"""``widevine`` or ``playready``: the DRM system the keys came from."""
@property
def local_cdm(self) -> Any:
"""The CDM of this machine for a track ``licenses_locally`` names, or None."""
def resolve_server_keys(self, title: Title_T) -> None:
"""Put the content keys the server or the export holds on the tracks of ``title``."""
def licenses_locally(self, track: AnyTrack) -> bool:
"""True when this machine's own CDM licenses ``track`` instead of the server."""
def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""The content keys the server licenses for ``drm`` of ``track``, or None when it hands ``track`` to this machine's CDM.
Call it only for a track ``licenses_locally`` does not name; after None, it names the track. ``kid`` is
the KID the answer must hold. A failed request returns no keys. A refusal this machine cannot take over
raises ClickException.
"""
def vault_source(self, kid: UUID, key: str) -> Vault | None:
"""The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check."""
@property
def server_vault(self) -> ServerVault | None:
"""The server's vaults, which take the content keys a decrypt proved, or None."""
class TitleSource(metaclass=ABCMeta):
"""The titles, tracks, chapters and content keys of one download, as dl reads them.
Its three adapters are ``Service``, the remote client (``RemoteService``) and the import (``ImportService``).
dl asks the source what it can do (``key_arrival``, ``key_source``, ``cache_identity``, ``login_cookies``).
"""
NO_SUBTITLES: bool = False # the source has no subtitles; dl skips the subtitle and caption extraction.
ANIME: bool = False # service catalogue is anime; metadata lookups prefer AniList. Title.anime overrides per title.
DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title.
ctx: click.Context
log: logging.Logger
session: requests.Session
credential: Credential | None = None
current_region: str | None = None
title_cache: TitleCacher | None = None
@property
def key_arrival(self) -> KeyArrival:
"""How the content keys of this source reach dl."""
return KeyArrival.CALLBACK
@property
def key_source(self) -> ServerKeySource | None:
"""The source dl asks for content keys and vault answers before ``prepare_drm``, or None when only the licence callbacks give keys."""
return None
@property
def login_cookies(self) -> CookieJar | None:
"""The cookies dl saves to the profile's cookie file after each title, or None when the login is not on this machine."""
return None
def cache_identity(self) -> CacheIdentity:
"""The cache, and the title ID, region and account that this source files its cached titles and metadata under.
A service keeps its title ID in ``title`` or ``title_id``, whichever it sets.
"""
if hasattr(self, "title"):
title_id = self.title
elif hasattr(self, "title_id"):
title_id = self.title_id
else:
title_id = None
return CacheIdentity(self.title_cache, title_id, self.current_region, get_account_hash(self.credential))
@abstractmethod
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
"""Log in, before any title, track or chapter call."""
def get_widevine_service_certificate(
self, *, challenge: bytes, title: Title_T, track: AnyTrack
) -> bytes | str | None:
"""
Get the Widevine Service Certificate used for Privacy Mode.
:param challenge: The service challenge, providing this to a License endpoint should return the
privacy certificate that the service uses.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The Service Privacy Certificate as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a Widevine License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be
read by the Cdm and decrypted.
This is a very important request to get correct. A bad, unexpected, or missing
value in the request can cause the service to detect your CDM device.
The service can then ban, revoke, disable, or downgrade that device.
:param challenge: The license challenge from the Widevine CDM.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The License response as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a PlayReady License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be
read by the CDM and decrypted.
This is a very important request to get correct. A bad, unexpected, or missing
value in the request can cause the service to detect your CDM device.
The service can then ban, revoke, disable, or downgrade that device.
:param challenge: The license challenge from the PlayReady CDM.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The License response as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
# A service that implements Widevine licensing only still gets PlayReady, with the
# arguments its own signature declares.
return self.get_widevine_license(
**declared_kwargs(self.get_widevine_license, {"challenge": challenge, "title": title, "track": track})
)
def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
"""
Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).
Used for DASH `org.w3.clearkey` tracks. unshackle uses no CDM here: the challenge is
the W3C EME JSON license request, e.g. ``{"kids": ["<base64url>"], "type": "temporary"}``,
and the license is a JWK Set, e.g. ``{"keys": [{"kty": "oct", "k": "...", "kid": "..."}]}``.
:param challenge: The JSON license request bytes to POST to the license server.
:param title: The current `Title` from get_titles that unshackle processes now. unshackle
gives this in case it holds data you need, for example for an HTTP request.
:param track: The current `Track` needing decryption. Provided for same reason as `title`.
:return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default)
to let the framework POST the challenge to the manifest-provided Laurl, if any.
Services with no license server can instead pre-populate the DRM object's
`signatures` in get_tracks.
"""
return None
@abstractmethod
def get_titles(self) -> Titles_T:
"""The titles of the title ID."""
def get_titles_cached(self, title_id: str | None = None) -> Titles_T:
"""The titles as dl uses them: through the title cache and the ``title_map`` where the adapter has them."""
return self.get_titles()
@abstractmethod
def get_tracks(self, title: Title_T) -> Tracks:
"""The tracks of ``title``."""
@abstractmethod
def get_chapters(self, title: Title_T) -> Chapters:
"""The chapters of ``title``."""
def close(self) -> None:
"""Release what the source holds open once dl has finished every title."""
# Optional sample decryption
def decrypts_samples(self, track: AnyTrack) -> bool:
"""Whether this service decrypts the cbcs file of `track` after the download, through `get_sample_decrypter`."""
return False
def get_sample_decrypter(self, track: AnyTrack, entry: int) -> bytes | SampleDecrypter:
"""The content key, or a `cbcs.SampleDecrypter`, for `stsd` entry `entry` (1-based) of `track`.
unshackle calls this only for a track `decrypts_samples` names. A remote session runs it on the
server, so a decrypter that needs a local process works for remote clients too.
"""
raise NotImplementedError(f"{self.__class__.__name__} does not decrypt samples")
# Optional Event methods
def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> None:
"""
Called when one of a Track's Segments has finished downloading.
Parameters:
track: The Track object that had a Segment downloaded.
segment: The Path to the downloaded Segment.
"""
def on_track_downloaded(self, track: AnyTrack) -> None:
"""
Called when a Track has finished downloading.
Parameters:
track: The downloaded Track object.
"""
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: m3u8.Segment | None = None) -> None:
"""
Called when a Track has finished decrypting.
Parameters:
track: The decrypted Track object.
drm: The DRM object it decrypted with.
segment: The decrypted HLS segment information. None for DASH and ISM tracks and
for an HLS track that merged during the download (merge_segments).
"""
def on_track_repacked(self, track: AnyTrack) -> None:
"""
Called when a Track has finished repacking.
Parameters:
track: The repacked Track object.
"""
def on_track_multiplex(self, track: AnyTrack) -> None:
"""
Called immediately before unshackle multiplexes a Track into a Container.
Note: Right now unshackle multiplexes only MKV containers. In the future
unshackle can also call this when it multiplexes to other containers like
MP4 with FFmpeg/mp4box.
Parameters:
track: The repacked Track object.
"""
__all__ = ("CacheIdentity", "KeyArrival", "ServerKeySource", "TitleSource")
+2 -2
View File
@@ -14,7 +14,7 @@ from unshackle.core.session import RnetSession, utf8_text
from unshackle.core.utils.bitrate import PROBE_TIMEOUT, ranged_get from unshackle.core.utils.bitrate import PROBE_TIMEOUT, ranged_get
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.service import Service from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Title_T from unshackle.core.titles import Title_T
from unshackle.core.tracks import Audio, Track, Tracks, Video from unshackle.core.tracks import Audio, Track, Tracks, Video
@@ -331,7 +331,7 @@ def probe_audio_codecs(
def probed_tracks( def probed_tracks(
service: Service, service: TitleSource,
title: Title_T, title: Title_T,
*, *,
workers: int | None = None, workers: int | None = None,