mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 13:35:09 +00:00
refactor(core): one TitleSource base for Service, remote and import
This commit is contained in:
+22
-38
@@ -79,10 +79,10 @@ from unshackle.core.proxies.resolve import (
|
||||
split_proxy_query,
|
||||
)
|
||||
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.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.episode import Episode
|
||||
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:
|
||||
import pysubs2
|
||||
|
||||
from unshackle.core.remote_service import ServerKeySource
|
||||
from unshackle.core.title_source import ServerKeySource
|
||||
|
||||
|
||||
class SkippedTitle(TypedDict):
|
||||
@@ -252,7 +252,7 @@ def apply_enrich(title: Title_T, name: str | None, year: int | None, language: L
|
||||
|
||||
|
||||
def load_tracks(
|
||||
service: Service,
|
||||
service: TitleSource,
|
||||
title: Title_T,
|
||||
*,
|
||||
name: str | None = None,
|
||||
@@ -1124,6 +1124,7 @@ class dl:
|
||||
export_snapshots: dict[str, dict[str, Any] | None]
|
||||
keys: ContentKeyResolver
|
||||
_remote_service: ServerKeySource | None = None
|
||||
export_service: TitleSource | None = None
|
||||
typed_params: frozenset[str] = frozenset()
|
||||
|
||||
def __init__(
|
||||
@@ -1451,7 +1452,7 @@ class dl:
|
||||
@with_task_temp
|
||||
def result(
|
||||
self,
|
||||
service: Service,
|
||||
service: TitleSource,
|
||||
quality: list[int],
|
||||
vcodec: list[Video.Codec],
|
||||
acodec: list[Audio.Codec],
|
||||
@@ -1537,14 +1538,12 @@ class dl:
|
||||
config.sample = sample
|
||||
self.tmdb_searched = False
|
||||
self.search_source = None
|
||||
self.service_anime = bool(getattr(service, "ANIME", False))
|
||||
self.service_daily = bool(getattr(service, "DAILY", False))
|
||||
from unshackle.core.import_service import SERVER_KEY_SOURCES, ImportService
|
||||
|
||||
self.service_anime = service.ANIME
|
||||
self.service_daily = service.DAILY
|
||||
# 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._remote_service = service if isinstance(service, SERVER_KEY_SOURCES) else None
|
||||
self._remote_service = service.key_source
|
||||
start_time = time.time()
|
||||
|
||||
lang, lang_excl = partition_exclusions(lang)
|
||||
@@ -1560,7 +1559,7 @@ class dl:
|
||||
video_excl = inherited_exclusions(v_lang, v_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
|
||||
if parent_params is not None:
|
||||
# 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}
|
||||
)
|
||||
|
||||
title_cacher = service.title_cache if hasattr(service, "title_cache") else None
|
||||
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
|
||||
title_cacher, cache_title_id, cache_region, cache_account_hash = service.cache_identity()
|
||||
|
||||
enrich_lang: Language | None = None
|
||||
enrich_title: str | None = None
|
||||
@@ -2223,7 +2215,7 @@ class dl:
|
||||
elif 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):
|
||||
skip_title(title, outcome.reason, outcome.kind_only)
|
||||
continue
|
||||
@@ -2266,12 +2258,10 @@ class dl:
|
||||
download_table.add_row(selected_tracks)
|
||||
|
||||
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
|
||||
self.cdm = cdm_type_stub(server_cdm_type)
|
||||
from unshackle.core.import_service import ImportService
|
||||
|
||||
if isinstance(self._remote_service, ImportService):
|
||||
if self._remote_service.key_arrival is KeyArrival.EXPORT:
|
||||
self.log.info("Using keys from the export; no CDM required")
|
||||
else:
|
||||
self.log.info(f"Using server CDM ({server_cdm_type.title()}); no local CDM required")
|
||||
@@ -2554,12 +2544,7 @@ class dl:
|
||||
if has_decrypted:
|
||||
self.log.info("Decrypted tracks")
|
||||
|
||||
if (
|
||||
not no_subs
|
||||
and not (hasattr(service, "NO_SUBTITLES") and service.NO_SUBTITLES)
|
||||
and not video_only
|
||||
and not no_video
|
||||
):
|
||||
if not no_subs and not service.NO_SUBTITLES and not video_only and not no_video:
|
||||
for video_track_n, video_track in enumerate(title.tracks.videos):
|
||||
has_manifest_cc = bool(getattr(video_track, "closed_captions", None))
|
||||
has_eia_cc = (
|
||||
@@ -2764,14 +2749,13 @@ class dl:
|
||||
if progress_sink:
|
||||
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)
|
||||
if cookie_file:
|
||||
login.save_cookies(cookie_file, service.session.cookies)
|
||||
login.save_cookies(cookie_file, service.login_cookies)
|
||||
|
||||
self.keys.wait_vault_writes()
|
||||
if hasattr(service, "close"):
|
||||
service.close()
|
||||
service.close()
|
||||
|
||||
if post_script_folders and post_script_sample:
|
||||
run_context = dict.fromkeys(post_script_sample, "")
|
||||
@@ -3072,7 +3056,7 @@ class dl:
|
||||
doc.generator.setdefault("app", "unshackle")
|
||||
doc.generator.setdefault("version", __version__)
|
||||
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))
|
||||
if entry is None:
|
||||
@@ -3194,7 +3178,7 @@ class dl:
|
||||
manifest_type = next(
|
||||
(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
|
||||
headers = dict(getattr(session, "headers", None) or {})
|
||||
manifests = (
|
||||
@@ -3310,7 +3294,7 @@ class dl:
|
||||
return [":x: Download Failed...", f" {line}"]
|
||||
|
||||
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:
|
||||
"""Build the run's content-key resolution and make its verified decrypt the decrypt hook."""
|
||||
self.keys = ContentKeyResolver(
|
||||
|
||||
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from enum import Enum
|
||||
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.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
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.title_source import TitleSource
|
||||
|
||||
log = logging.getLogger("download_manager")
|
||||
|
||||
@@ -434,8 +434,7 @@ def perform_download(
|
||||
from unshackle.core.remote_service import make_remote_service
|
||||
|
||||
service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj)
|
||||
# RemoteService duck-types Service for dl.result()
|
||||
service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params))
|
||||
service_instance: TitleSource = make_remote_service(service_ctx, remote, service, title_id, params)
|
||||
else:
|
||||
service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
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:
|
||||
"""The KID of an EXT-X-KEY KEYID or KID attribute, or None when it is absent, a placeholder or not a KID."""
|
||||
try:
|
||||
|
||||
@@ -36,7 +36,7 @@ from unshackle.core.drm import (
|
||||
real_kids,
|
||||
verify,
|
||||
)
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.title_source import TitleSource
|
||||
from unshackle.core.titles import Title_T
|
||||
from unshackle.core.tracks import Video
|
||||
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
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.remote_service import ServerKeySource
|
||||
from unshackle.core.title_source import ServerKeySource
|
||||
from unshackle.core.utilities import DebugLogger
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ class ContentKeyResolver:
|
||||
self,
|
||||
vaults: Vaults,
|
||||
cdms: CdmChooser,
|
||||
service: Service,
|
||||
service: TitleSource,
|
||||
tag: str,
|
||||
source: ServerKeySource | None = None,
|
||||
cdm_only: bool = False,
|
||||
@@ -274,7 +274,7 @@ class ContentKeyResolver:
|
||||
def passes_left(done: int) -> bool:
|
||||
"""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."""
|
||||
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
|
||||
|
||||
try:
|
||||
@@ -832,7 +832,7 @@ class ContentKeyResolver:
|
||||
if not drm:
|
||||
return
|
||||
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))
|
||||
|
||||
if server_cdm and not licensed_locally:
|
||||
|
||||
@@ -18,10 +18,12 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
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.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.title_source import KeyArrival, TitleSource
|
||||
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.attachment import Attachment
|
||||
@@ -218,19 +220,14 @@ def int_or_none(value: Any) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
class ImportService:
|
||||
class ImportService(TitleSource):
|
||||
"""Reconstructs a download from an export JSON.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
ALIASES: tuple[str, ...] = ()
|
||||
GEOFENCE: tuple[str, ...] = ()
|
||||
GEOBLOCK: tuple[str, ...] = ()
|
||||
NO_SUBTITLES: bool = False
|
||||
server_cdm = True
|
||||
local_cdm = 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.ctx = ctx
|
||||
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:
|
||||
raise click.ClickException("No export file was provided to import from.")
|
||||
@@ -354,6 +348,16 @@ class ImportService:
|
||||
def title(self) -> str:
|
||||
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:
|
||||
self.credential = credential
|
||||
|
||||
@@ -682,7 +686,7 @@ class ImportService:
|
||||
stub_kids = list(keys) or sorted(row_kids or [])
|
||||
if drm_obj is None and stub_kids:
|
||||
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:
|
||||
return None
|
||||
@@ -745,7 +749,7 @@ class ImportService:
|
||||
if isinstance(drm_obj, (ClearKey, MonaLisa)):
|
||||
continue
|
||||
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():
|
||||
drm_obj.content_keys[kid] = key
|
||||
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:
|
||||
raise self.missing_key(track)
|
||||
|
||||
@@ -850,33 +851,8 @@ class ImportService:
|
||||
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:
|
||||
try:
|
||||
self.session.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
SERVER_KEY_SOURCES: tuple[type[ServerKeySource], ...] = (RemoteService, ImportService)
|
||||
"""The services dl takes content keys from before ``prepare_drm``; mypy checks each against ServerKeySource."""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Remote service adapter for unshackle.
|
||||
|
||||
Implements the Service interface by proxying authenticate, get_titles,
|
||||
get_tracks, get_chapters, and license methods to a remote unshackle server.
|
||||
A ``TitleSource`` that relays authenticate, get_titles, get_tracks,
|
||||
get_chapters, and license methods to a remote unshackle server.
|
||||
Everything else (track selection, download, decrypt, mux) runs locally.
|
||||
"""
|
||||
|
||||
@@ -24,7 +24,6 @@ from threading import Lock, local
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Protocol,
|
||||
TypeVar,
|
||||
cast,
|
||||
)
|
||||
@@ -46,6 +45,7 @@ from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.dl_options import remote_dl_params
|
||||
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.manifests.snapshot import match_track, restore
|
||||
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.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.episode import Episode, Series
|
||||
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
|
||||
|
||||
|
||||
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):
|
||||
"""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)
|
||||
|
||||
|
||||
class RemoteService:
|
||||
"""Service adapter that proxies to a remote unshackle server.
|
||||
class RemoteService(TitleSource):
|
||||
"""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
|
||||
subclassing Service (avoids proxy/geofence setup in __init__).
|
||||
It is not a Service, so it runs none of the proxy and geofence setup of ``Service.__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"
|
||||
channel: Channel | None = None
|
||||
|
||||
@@ -919,9 +876,6 @@ class RemoteService:
|
||||
self.ctx = ctx
|
||||
self._service_params = service_params or {}
|
||||
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._tracks_by_title: dict[str, Tracks] = {}
|
||||
self._chapters_by_title: dict[str, list] = {}
|
||||
@@ -942,9 +896,9 @@ class RemoteService:
|
||||
self._title_alias: dict[str, str] = {}
|
||||
self._track_alias: dict[str, str] = {}
|
||||
|
||||
self._session = requests.Session()
|
||||
self._session.headers.update(config.headers)
|
||||
self._session.mount(
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(config.headers)
|
||||
self.session.mount(
|
||||
"https://",
|
||||
HTTPAdapter(
|
||||
max_retries=Retry(
|
||||
@@ -957,7 +911,7 @@ class RemoteService:
|
||||
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, {})
|
||||
self._server_cdm: bool | None = services_config.get("_server_cdm")
|
||||
@@ -999,10 +953,6 @@ class RemoteService:
|
||||
existing[key] = value
|
||||
config.services[self.service_tag] = existing
|
||||
|
||||
@property
|
||||
def session(self) -> requests.Session:
|
||||
return self._session
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return self.title_id
|
||||
@@ -1091,7 +1041,7 @@ class RemoteService:
|
||||
try:
|
||||
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"):
|
||||
client_region = ip_info["country"].lower()
|
||||
except Exception:
|
||||
@@ -1124,8 +1074,8 @@ class RemoteService:
|
||||
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")
|
||||
if local_proxy:
|
||||
self._session.proxies["all"] = local_proxy
|
||||
run_proxy.pin(self._session)
|
||||
self.session.proxies["all"] = local_proxy
|
||||
run_proxy.pin(self.session)
|
||||
|
||||
if not no_proxy and not proxy and client_region:
|
||||
create_data["client_region"] = client_region
|
||||
@@ -1480,8 +1430,8 @@ class RemoteService:
|
||||
session_fields = cast(TracksReply, result)
|
||||
for k, v in session_fields.get("session_headers", {}).items():
|
||||
if k.lower() not in ("host", "content-length", "content-type"):
|
||||
self._session.headers[k] = v
|
||||
apply_session_cookies(self._session, result)
|
||||
self.session.headers[k] = v
|
||||
apply_session_cookies(self.session, result)
|
||||
|
||||
restore(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()
|
||||
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():
|
||||
drm_obj.content_keys[UUID(hex=kid_hex)] = key_hex
|
||||
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")
|
||||
|
||||
@property
|
||||
def server_cdm(self) -> bool:
|
||||
"""True when the server CDM licenses this remote session, so dl licenses with no CDM of its own."""
|
||||
return bool(self._server_cdm)
|
||||
def key_arrival(self) -> KeyArrival:
|
||||
"""``SERVER`` when the server CDM licenses this remote session, else ``CALLBACK``: the challenge relay."""
|
||||
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:
|
||||
"""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:
|
||||
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:
|
||||
title_id = str(title.id)
|
||||
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:
|
||||
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(
|
||||
self,
|
||||
*,
|
||||
@@ -1887,21 +1793,6 @@ class RemoteService:
|
||||
self.drain_server_logs()
|
||||
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:
|
||||
# a long-lived serve opens many of these; the atexit hook would keep every one alive
|
||||
atexit.unregister(self.close)
|
||||
|
||||
+18
-168
@@ -1,18 +1,15 @@
|
||||
import logging
|
||||
import time
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from abc import abstractmethod
|
||||
from collections.abc import Callable, Generator, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TypeVar, Union
|
||||
from typing import TYPE_CHECKING, Any, TypeVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.api.input_bridge import InputBridge
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
|
||||
import click
|
||||
import m3u8
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
from rich.padding import Padding
|
||||
@@ -21,9 +18,7 @@ from rich.rule import Rule
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.config import config
|
||||
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.drm import DRM_T
|
||||
from unshackle.core.launch import launch_keys
|
||||
from unshackle.core.proxies.basic import Basic
|
||||
from unshackle.core.proxies.resolve import pick_proxy
|
||||
@@ -39,11 +34,11 @@ from unshackle.core.session import (
|
||||
RETRY_METHODS,
|
||||
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.tracks import Chapters, Tracks
|
||||
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.collections import ci_get
|
||||
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")
|
||||
|
||||
|
||||
class Service(metaclass=ABCMeta):
|
||||
class Service(TitleSource):
|
||||
"""The Service Base Class.
|
||||
|
||||
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.
|
||||
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.
|
||||
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().
|
||||
# vault namespace override; when set, key vault read/write uses this tag instead of the service's own.
|
||||
VAULT_TAG: str | None = None
|
||||
@@ -189,7 +182,7 @@ class Service(metaclass=ABCMeta):
|
||||
|
||||
self.session = self.get_session()
|
||||
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.ctx = ctx
|
||||
@@ -307,6 +300,11 @@ class Service(metaclass=ABCMeta):
|
||||
|
||||
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
|
||||
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.
|
||||
@@ -516,83 +514,6 @@ class Service(metaclass=ABCMeta):
|
||||
"""
|
||||
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
|
||||
def get_titles(self) -> Titles_T:
|
||||
"""
|
||||
@@ -622,16 +543,12 @@ class Service(metaclass=ABCMeta):
|
||||
Returns:
|
||||
Titles object (Movies, Series, or Album)
|
||||
"""
|
||||
identity = self.cache_identity()
|
||||
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")
|
||||
return self.apply_title_map(self.get_titles())
|
||||
title_id = identity.title_id
|
||||
if title_id is None:
|
||||
self.log.debug("Cannot determine title_id for caching, bypassing cache")
|
||||
return self.apply_title_map(self.get_titles())
|
||||
|
||||
no_cache = False
|
||||
reset_cache = False
|
||||
@@ -639,14 +556,11 @@ class Service(metaclass=ABCMeta):
|
||||
no_cache = self.ctx.parent.params.get("no_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(
|
||||
title_id=str(title_id),
|
||||
fetch_function=self.get_titles,
|
||||
region=self.current_region,
|
||||
account_hash=account_hash,
|
||||
region=identity.region,
|
||||
account_hash=identity.account_hash,
|
||||
no_cache=no_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".
|
||||
"""
|
||||
|
||||
# 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")
|
||||
|
||||
@@ -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")
|
||||
@@ -14,7 +14,7 @@ from unshackle.core.session import RnetSession, utf8_text
|
||||
from unshackle.core.utils.bitrate import PROBE_TIMEOUT, ranged_get
|
||||
|
||||
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.tracks import Audio, Track, Tracks, Video
|
||||
|
||||
@@ -331,7 +331,7 @@ def probe_audio_codecs(
|
||||
|
||||
|
||||
def probed_tracks(
|
||||
service: Service,
|
||||
service: TitleSource,
|
||||
title: Title_T,
|
||||
*,
|
||||
workers: int | None = None,
|
||||
|
||||
Reference in New Issue
Block a user