diff --git a/docs/dev/creating-a-service.md b/docs/dev/creating-a-service.md index dcf11534..6a3cd3cd 100644 --- a/docs/dev/creating-a-service.md +++ b/docs/dev/creating-a-service.md @@ -98,29 +98,10 @@ Click `cli` entry point plus three abstract methods. ### Class variables -Declared at class level to configure framework behaviour: - -| Variable | Type | Purpose | -|---|---|---| -| `ALIASES` | `tuple[str, ...]` | Extra tags that resolve to this service (e.g. `("EX", "DOMAIN")`). Case does not matter. Default `()`. | -| `GEOFENCE` | `tuple[str, ...]` | IP region codes the service requires. Empty = no geofence. unshackle treats the **first** entry as the main region for auto-proxy. | -| `GEOBLOCK` | `tuple[str, ...]` | IP region codes where the service refuses to work. Every other region is allowed. Default `()`. | -| `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()`. | -| `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. Default `False`. | -| `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | -| `METADATA_PROVIDER` | `Optional[str]` | Set it, such as to `"tmdb"`, when an index keeps your catalogue's titles only in a form your service does not use (romanized, for one), and another provider finds them by the name your service gives. Lookups try that provider first. It only reorders `metadata_providers` and never adds a provider the user left out. A title's own `metadata_provider` 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. | - -`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 -blocked, fetches a proxy to `GEOFENCE[0]` from your configured proxy providers. A -proxy exit outside `GEOFENCE` logs a warning and the run continues. - -`GEOBLOCK` is the negative form: the service works everywhere except the listed -regions. With no `GEOFENCE` to name a main region, a `GEOBLOCK` hit stops the run -with a "not available in your region" error; pass `--proxy` yourself. +Class variables at the top of your class configure framework behaviour. The attributes table of +[`Service`][unshackle.core.service.Service] lists each one. +[Service Architecture](service-architecture.md#what-__init__-wires-up-for-you) explains the region check +that `GEOFENCE` and `GEOBLOCK` drive. ```python class EXAMPLE(Service): @@ -136,37 +117,12 @@ class WORLDWIDE(Service): ### What `Service.__init__` wires up When you call `super().__init__(ctx)`, the base class sets up the attributes you -will use throughout the service: +will use throughout the service, such as `self.config`, `self.session`, `self.cache` and +`self.track_request`. The attributes table of [`Service`][unshackle.core.service.Service] lists each one. -| Attribute | What it is | -|---|---| -| `self.config` | A dict: this service's `config.yaml`, with the user's `services.` block from `unshackle.yaml` merged over it. Without a `config.yaml`, it holds only the user's block. See [Services & authentication](../reference/configuration/services.md) for the override keys. | -| `self.log` | A `logging.Logger` named after your class. | -| `self.session` | A prepared `requests.Session` with config headers and a retry adapter (5 retries, backoff 0.2, retries on 429/500/502/503/504). Send every request through it: with a proxy active, a request from service code that does not go through the proxy logs a warning. A separate HTTP session that goes direct on purpose sets `proxy_exempt = True`. | -| `self.cache` | A `Cacher` for arbitrary key/value data, for example authentication tokens. | -| `self.title_cache` | A region/account-aware `TitleCacher` used by `get_titles_cached`. | -| `self.cache_dir` | `config.directories.cache / `. | -| `self.track_request` | A `TrackRequest` built from the CLI `--vcodec` / `--range` / `--best-available` flags. | -| `self.credential` | `None` until `authenticate()` runs. | -| `self.current_region` | The two-letter region resolved from proxy/IP. | - -`self.track_request` is a small dataclass you can read *and rewrite* before -fetching tracks: - -```python -@dataclass -class TrackRequest: - codecs: list[Video.Codec] = [] # empty == accept any codec - ranges: list[Video.Range] = [Video.Range.SDR] - best_available: bool = False - generate_dv: bool = False # --generate-dv: make Dolby Vision when a title has no DV track -``` - -!!! note "`generate_dv` and a hand-made HYBRID" - A service that fetches the HYBRID variants itself (HDR10 or HDR Vivid, and DV) must also fetch - HDR10P when `track_request.generate_dv` is set and the title has no DV track. - unshackle prefers an HEVC HDR10+ track as the base, and measures an HDR10 base from the decoded video. - `get_tracks_for_variants` does this for you. +`self.track_request` is a [`TrackRequest`][unshackle.core.service.TrackRequest] built from the CLI. +You can read it *and rewrite* it before you fetch tracks. A service that fetches the HYBRID variants itself reads the +[`TrackRequest` note](service-architecture.md#what-__init__-wires-up-for-you) first. !!! note "Read the request, don't second-guess the user" Services may narrow `track_request` for hard technical constraints (e.g. @@ -639,16 +595,8 @@ The core drives licensing. Your job is to answer the license challenges the CDM produces. Mark encrypted tracks with the right DRM in `get_tracks` (the manifest parsers do this automatically for PSSH/`EXT-X-KEY` found in the manifest), then write the license callbacks you need. Each receives the challenge plus the -current `title` and `track`: - -| Method | For | Returns | -|---|---|---| -| `get_widevine_service_certificate` | Widevine privacy mode | The service certificate (bytes or base64 str), or `None`. | -| `get_widevine_license` | Widevine | The raw license response (bytes or base64 str), **unmodified**. | -| `get_playready_license` | PlayReady | The license response. Defaults to delegating to `get_widevine_license`. | -| `get_clearkey_license` | DASH `org.w3.clearkey` | The JWK Set (dict/JSON/bytes), or `None` to let the framework POST the challenge to the manifest's Laurl. | - -A license callback can also declare optional keyword arguments. `get_widevine_license` can ask for `pssh` and `session_id`. `get_playready_license` can ask for `pssh_b64` and `session_id`. `session_id` is the open CDM session. A callback gets only the arguments that its signature declares. When a `--remote` client licenses with its own CDM, the callback on the server gets `pssh` or `pssh_b64` for the header the client licenses, but no `session_id`. +current `title` and `track`. [The service-side hooks](service-architecture.md#the-service-side-hooks) +names each callback, the optional arguments that it can declare, and what it returns: ```python def get_widevine_license(self, *, challenge: bytes, title, track): diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index d543e5a8..fe83aedc 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -57,19 +57,9 @@ Two kinds of members matter: **class variables** that give the details of the se ### Class variables -Declared at the top of your service class, these are static descriptors: - -| Class variable | Type | Purpose | -|---|---|---| -| `ALIASES` | `tuple[str, ...]` | Alternate tags the service answers to, in any case (resolved by `Services.get_tag`). | -| `GEOFENCE` | `tuple[str, ...]` | ISO region codes the service requires; empty means no geofence. unshackle treats the first entry as the "main region" for automatic proxy selection. | -| `GEOBLOCK` | `tuple[str, ...]` | ISO region codes where the service refuses to work; every other region is allowed. Use it for a service that works worldwide except in its home market. | -| `VAULT_TAG` | `Optional[str]` | Overrides the key-vault namespace; defaults to the service's own tag. | -| `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Accepted auth methods (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. | -| `ANONYMOUS_SEARCH` | `bool` | `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. | -| `ANIME` | `bool` | The catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | -| `METADATA_PROVIDER` | `Optional[str]` | The metadata provider the catalogue resolves through, such as `"tmdb"`. Lookups try it first. It only reorders `metadata_providers` and never adds a provider the user left out. A title's own `metadata_provider` overrides it. | -| `DAILY` | `bool` | The catalogue is daily/date-based, so unshackle names episodes by air date. A title's own `daily` flag overrides it. | +Declared at the top of your service class, class variables such as `ALIASES`, `GEOFENCE` and +`NO_SUBTITLES` describe the service to the framework. The attributes table of +[`Service`][unshackle.core.service.Service] in the Service API gives each one, with its type and purpose. ### Required methods @@ -87,9 +77,7 @@ These are abstract. A service will not load unless it defines all three: - **`search()`**: raises `NotImplementedError` by default. Write it so that the `search` command can operate. unshackle calls `authenticate()` first, unless the service sets `ANONYMOUS_SEARCH`. -- **DRM license hooks**: `get_widevine_service_certificate`, `get_widevine_license`, - `get_playready_license` (delegates to Widevine by default), and - `get_clearkey_license` (returns `None` by default). See [DRM hooks](#drm-hooks) below. +- **Licence callbacks**: see [DRM hooks](#drm-hooks) below. - **`request_input(prompt, qr=None)`**: prompts the user. It goes through the remote-dl input bridge, the REST download job relay, or the rich console. - **`wait_for_approval(message, check, timeout, interval=3.0, qr=None)`**: shows a message, then @@ -106,18 +94,9 @@ These are abstract. A service will not load unless it defines all three: ### What `__init__` wires up for you You rarely override `__init__`. The base constructor takes the Click context and sets -up the objects your methods rely on: - -| Attribute | What it is | -|---|---| -| `self.config` | The merged service config (see [Request and HTTP session objects](#request-and-http-session-objects)). | -| `self.log` | A `logging.Logger` named after your class. | -| `self.session` | A ready-to-use HTTP session (headers, retries, and proxy applied). Send every request through it: with a proxy active, a request from service code that does not go through the proxy logs a warning. A separate HTTP session that goes direct on purpose sets `proxy_exempt = True`. | -| `self.cache` | A generic key/value `Cacher` namespaced to the service. | -| `self.title_cache` | A region- and account-aware `TitleCacher`. | -| `self.cache_dir` | `config.directories.cache / `. | -| `self.credential` | The active `Credential`, or `None` until authenticated. | -| `self.track_request` | A `TrackRequest` describing the requested codecs, ranges, and best-available flag (see below). | +up the objects your methods rely on, such as `self.session`, `self.cache` and `self.track_request`. +The attributes table of [`Service`][unshackle.core.service.Service] lists each one. +[Request and HTTP session objects](#request-and-http-session-objects) explains the main ones. The constructor also resolves proxies: it reads `--proxy`, which `dl` and `search` have already resolved through the per-service `proxy_map`, and, if `GEOFENCE` is set and you did not give an explicit proxy, does a live @@ -129,12 +108,11 @@ outside `GEOFENCE` logs a warning and the run continues. See [Proxies and VPN](../guide/proxies-and-vpn.md). !!! note "`TrackRequest`" - `self.track_request` is a small dataclass built from the CLI: `codecs` - (from `--vcodec`, empty means "accept any"), `ranges` (from `--range`, default - `[Video.Range.SDR]`), `best_available`, and `generate_dv` (from `--generate-dv`). - Use it in `get_tracks` to decide which variants to fetch. A service that fetches + `self.track_request` is a [`TrackRequest`][unshackle.core.service.TrackRequest] built from the + CLI. Use it in `get_tracks` to decide which variants to fetch. A service that fetches the HYBRID variants itself must also fetch HDR10P when `generate_dv` is set and the title has no DV track, because unshackle prefers an HEVC HDR10+ base. + `get_tracks_for_variants` does this for you. ## Titles and the `Title` hierarchy @@ -240,9 +218,7 @@ Each subclass adds its own required fields on top of `id_` and `service`: changes nothing. A `Song` is an ordinary `Title` on the one generic download path. unshackle has no - music-specific service API and no separate music download loop. The - `GROUP_AUDIO_DOWNLOADS` flag, `get_music_track_options` and `get_music_collection_label` - no longer exist, and a music service does not need them. + music-specific service API and no separate path for music. Core picks the container of a `Song` from the codec in the downloaded file, so a music service does not rename the track path. Read @@ -443,7 +419,7 @@ least one and no track is left. from the `` fragment timeline, and rebuilds a `moov`/`ftyp` init box from `CodecPrivateData` (supported for AVC, HEVC, DV-over-HEVC, AAC, EC-3, and TTML). A track id covers the manifest URL, so a title you build from one ISM manifest per codec or range keeps every variant: - `Tracks.add` no longer reads the second manifest's tracks as duplicates of the first. + `Tracks.add` does not read the tracks of the second manifest as duplicates of the first. ## DRM hooks @@ -467,25 +443,31 @@ service to talk to the platform's license server. unshackle recognizes six DRM c ### The service-side hooks The framework supplies the CDM and the decryption backend. Your service gives the network -calls that must carry the CDM's challenge. Override the hooks that your platform -needs: +calls that must carry the CDM's challenge. Override the licence callbacks that your platform +needs: `get_widevine_service_certificate`, `get_widevine_license`, `get_playready_license` and +`get_clearkey_license`. Each one gets `challenge`, `title` and `track` as keyword arguments, and +returns the licence as the server gives it, without decoding it. The base `get_playready_license` calls +`get_widevine_license`, and the base `get_clearkey_license` returns `None`, so that the framework +POSTs the challenge to the manifest `Laurl`. The [Service API](../reference/api/service.md) gives the +signature and the return type of each callback. -| Hook | Return | Purpose | -|---|---|---| -| `get_widevine_service_certificate(title, track, challenge)` | cert bytes | Optional privacy-mode service certificate. | -| `get_widevine_license(title, track, challenge)` | license bytes | POST the Widevine challenge to the license server, return the response. | -| `get_playready_license(title, track, challenge)` | license | Same for PlayReady; defaults to delegating to Widevine. | -| `get_clearkey_license(title, track, challenge)` | dict / str / bytes / `None` | For `ClearKeyCENC`; return `None` to let the framework POST to the manifest `Laurl`. | -| `get_fairplay_bridge_license(title, track, challenge, drm_system)` | license | Optional, not on the base class. Licenses a FairPlay-only HLS track; see [The FairPlay bridge hook](#the-fairplay-bridge-hook). | +A licence callback can also declare optional keyword arguments. `get_widevine_license` can ask for +`pssh` and `session_id`. `get_playready_license` can ask for `pssh_b64` and `session_id`. +`session_id` is the open CDM session. A callback gets only the arguments that its signature declares. +When a `--remote` client licenses with its own CDM, the callback on the server gets `pssh` or +`pssh_b64` for the header that the client licenses, but no `session_id`. You do not open CDM sessions or operate shaka-packager yourself. The `Widevine`/`PlayReady` -classes drive the CDM handshake and call the decryption backend. Your hook is only the +classes drive the CDM handshake and call the decryption backend. Your callback is only the "send this challenge, give me back the license" step. ### The FairPlay bridge hook -unshackle has no FairPlay CDM and never sends a FairPlay challenge. For a FairPlay-only track it can send a PlayReady or Widevine challenge for the KIDs of the init segments to the licence server of the platform, which works only when that server issues the same content key to PlayReady or Widevine. The bridge runs only for a service that defines -`get_fairplay_bridge_license`. The base class does not define it. +unshackle has no FairPlay CDM and never sends a FairPlay challenge. For a FairPlay-only HLS track it can +send a PlayReady or Widevine challenge for the KIDs of the init segments to the licence server of the +platform. This works only when that server issues the same content key to PlayReady or Widevine. The +bridge runs only for a service that defines `get_fairplay_bridge_license`. The base class does not +define it. ```python def get_fairplay_bridge_license( @@ -497,11 +479,12 @@ def get_fairplay_bridge_license( ``` - `drm_system` is `"playready"` or `"widevine"`. The hook must accept it. -- The hook can also declare the arguments of the licence callback of that system: `pssh` for Widevine, - `pssh_b64` for PlayReady, and `session_id`. It gets only the arguments that it declares. +- The hook can also declare the optional arguments of the licence callback of that system (see + [The service-side hooks](#the-service-side-hooks)). It gets only the arguments that it declares. - The key IDs are on the DRM object of the track (`track.drm[0].kids`) when the hook runs. A service that needs its own request shape builds the request in the hook. -- The challenge of every other track goes to `get_playready_license` or `get_widevine_license`, as before. +- The hook gets only the challenges of FairPlay-only tracks. The challenge of every other track goes to + `get_playready_license` or `get_widevine_license`. The DRM system of the challenge is the `drm_preference` of the track, else the system of the configured CDM. For a licence server that issues the content key to one system only, set `drm_preference` on the @@ -513,22 +496,14 @@ for track in tracks.videos + tracks.audio: track.drm_preference = "playready" ``` -Without the hook, no challenge goes to the licence server for a FairPlay-only track, and `dl` leaves -such a track out of the selection: +The init segment (`EXT-X-MAP`) of the track must name a real key ID in its `tenc` box. When the `tenc` +key ID is all zeros and the playlist has one key URI, the `pssh` boxes of the init segment can name it. +unshackle never reads a key ID from the `skd://` URI. -- After the selection and the deferred DRM load, `dl` checks each selected video and audio track that has - no DRM object. An HLS track costs one request for its media playlist. A DASH track is FairPlay-only when - its `ContentProtection` elements name only DRM systems that unshackle cannot license and its init segment - has no Widevine or PlayReady `pssh`. -- `dl` removes each FairPlay-only track and selects again, so the run takes the next best track that - licenses. It logs one line for each title: `Left out 2 FairPlay-only tracks: EXAMPLE has no FairPlay bridge hook`. -- When a quality, range or codec flag matches only FairPlay-only tracks, the second selection skips the - title with its usual reason, and `--best-available` takes its usual fallback. When each selected video - or each selected audio track is FairPlay-only, `dl` skips the title. -- `--list` shows every track and checks none. An import is not checked, because its export holds the - content keys. -- With the hook, `dl` still leaves out FairPlay-only DASH tracks, because the bridge works for HLS only. - The line then reads `Left out 1 FairPlay-only track: DASH has no FairPlay bridge`. +Without the hook, `dl` leaves each FairPlay-only track out of the selection and takes the next best +track that licenses. It logs one line for each title: +`Left out 2 FairPlay-only tracks: EXAMPLE has no FairPlay bridge hook`. With the hook, `dl` still leaves +out FairPlay-only DASH tracks, because the bridge works for HLS only. A licence server that does not issue the content key refuses the challenge, and can flag the device. Test the route with a licence-only run (`--cdm-only --skip-dl`) before a service relies on it. @@ -554,43 +529,8 @@ that needs a process on the server also works for a remote client. ### A playlist whose key tag unshackle cannot license -A media playlist can name only a key system that unshackle does not read, such as an `skd://` key -over cbcs media, while the licence server of the platform also issues the same content key over -PlayReady or Widevine. `HLS.download_track` licenses such a track when all of these conditions are true: - -- The service has the [FairPlay bridge hook](#the-fairplay-bridge-hook). -- The track has no DRM object. -- Every `EXT-X-KEY` of its media playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a DRM system - unshackle cannot license, or `METHOD=NONE`. A segment under `METHOD=NONE` must have an init segment - that no encrypted segment uses: a decrypter that reads the encrypted init segment decrypts the clear - samples too. A tag with `KEYFORMAT="identity"`, or with no `KEYFORMAT`, names no DRM system: each - encrypted segment also needs a tag of a DRM system. -- The `drm_preference` of the track, or else the configured CDM, is PlayReady or Widevine. -- The init segment (`EXT-X-MAP`) of the track names a key ID in its `tenc` box. When the `tenc` key ID is all - zeros, the playlist must have one key URI, and each init segment under the key tag must give the same - key ID: its `tenc` key ID, or else the one key ID that its `pssh` boxes name. A clear init segment, - such as the one of a clear lead or tail, does not count. MPEG-TS media has no init segment. -- The init segment does not change without an `EXT-X-DISCONTINUITY`. - -The download reads the key ID from the init segment, builds a DRM object for that DRM system with -`drm_stub`, and sends the challenge to the hook. Over `--remote` the tracks reply tells the client that -the service on the server has the hook. The server reads the same key ID at the licence step, accepts -the DRM object of the client and sends the challenge to the hook of its service. A server that cannot -read the key ID refuses the challenge. A licence that gives no content key stops the track before it -downloads a segment. With the server CDM, the batch licence names the key IDs that the server read, so an -answer without their content keys stops the track in the same way. A content key that does not decode -the downloaded track stops the track with an error, and unshackle keeps no output file. - -unshackle reads one key ID from each init segment. So it licenses a playlist that changes its content key -correctly only when each content key has its own init segment with a real `tenc` key ID, after an -`EXT-X-DISCONTINUITY`. When the first key ID is real, the download also reads the `tenc` key ID of -each other init segment of the encrypted segments, and licenses each real key ID in its own licence step. A -PlayReady DRM object then has one header for each key ID, because the header of `drm_stub` holds -one key ID. A key ID that gets no content key stops the track before it downloads a segment. An -init segment that gives no real key ID does not count. - A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object -on the track: +on the track and needs no [FairPlay bridge hook](#the-fairplay-bridge-hook): 1. Read the key ID from the init segment of the encrypted segments. `HLS.get_track_kid_from_init` returns it for the track, a reader of init segments (`HLS.init_reader(playlist, session)`) and that init segment. @@ -600,19 +540,10 @@ on the track: 3. Let your licence callback send the challenge to the server that issues that key. `drm_stub` builds the header from the key ID alone, so this works with a licence server that goes -by the key ID, not with one that checks a header a packager signed. A platform can issue the -content key of one package of a title and refuse another. When a track carries a Widevine or PlayReady DRM -object and every `EXT-X-KEY` of its playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a key system -unshackle cannot license, or `METHOD=NONE` under the same condition, `HLS.drop_unsupported_keys` removes the -tags from the parsed playlist. -The download then licenses and decrypts the track with the DRM object of the track. This works for -one content key per track: the key changes of the playlist go with the tags. This limit also -applies to a DRM object that the download builds. Any other track stops with -`None of the key systems are supported` before it downloads a segment. - -A DASH track with no DRM object stops with the same error when its init segment has an encrypted -sample entry. A DASH track with no init segment stops after the download when the file has one, and -unshackle deletes the file. A service sample decrypter turns off both checks. +by the key ID, not with one that checks a header a packager signed. When every `EXT-X-KEY` of the +playlist names a key system that unshackle cannot license, unshackle ignores those tags and licenses +and decrypts the track with its DRM object, for one content key per track. Any other track that has +only such tags stops with `None of the key systems are supported` before it downloads a segment. ### How unshackle chooses a CDM and finds keys @@ -656,8 +587,8 @@ prepared, all derived from the Click context (`ctx`) that `dl` passes in. - **`self.session`**: a `requests.Session` with `config.headers` applied, a retry policy (`total=5`, backoff, retry on 429/5xx), and any resolved proxy already mounted. Pass this HTTP session into the manifest parsers and DRM calls so headers, cookies, and proxies flow - everywhere. (unshackle also ships an rnet-based TLS-fingerprinting HTTP session that the - newer `session()` factory uses and that the `network` config key configures.) + everywhere. To impersonate a browser TLS fingerprint, override `get_session()` to return an + rnet HTTP session from `session()` in `unshackle.core.session`, which the `network` config key configures. - **`self.credential`**: the active `Credential` (`username:password[:extra]`), populated by `authenticate`. unshackle uses its `sha1` as the account hash for cache keys. A login with cookies only uses a hash of the path of its cookie file. @@ -669,46 +600,8 @@ prepared, all derived from the Click context (`ctx`) that `dl` passes in. to stale data within `title_cache_max_retention` when an API call fails, and `--no-cache` bypasses it. If you put the cookies of a different account into the same cookie file, use `--reset-cache` once. -- **`self.track_request`**: the `TrackRequest` describing what the user asked for - (codecs, ranges, best-available), for use inside `get_tracks`. -!!! example "A minimal service skeleton" - ```python title="services/EXMP/__init__.py" - from unshackle.core.service import Service - from unshackle.core.manifests import DASH - from unshackle.core.titles import Movie, Movies - - - class EXMP(Service): - ALIASES = ("example",) - GEOFENCE = ("us",) - - def get_titles(self) -> Movies: - data = self.session.get(f"https://api.example.com/title/{self.title}").json() - return Movies([ - Movie( - id_=data["id"], - service=self.__class__, - name=data["name"], - year=data.get("year"), - language=data.get("language"), - ) - ]) - - def get_tracks(self, title) -> "Tracks": - mpd_url = self.session.get(...).json()["manifest"] - mpd = self.session.get(mpd_url).text - return DASH.from_text(mpd, mpd_url).to_tracks(language=title.language) - - def get_chapters(self, title): - return [] - - def get_widevine_license(self, *, challenge, title, track): - return self.session.post("https://lic.example.com/wv", data=challenge).content - ``` - - The directory name (`EXMP`) must match the class name exactly. That stem is the - service tag. Put your service in one of the `directories.services` paths. +[Creating a Service](creating-a-service.md#minimal-service-skeleton) gives a complete minimal service. ## Where to go next diff --git a/unshackle/core/service.py b/unshackle/core/service.py index 46c7c183..3ee88b2f 100644 --- a/unshackle/core/service.py +++ b/unshackle/core/service.py @@ -118,6 +118,9 @@ class TrackRequest: Attributes: codecs: Requested codecs from CLI. Empty list means no filter (accept any). ranges: Requested ranges from CLI. Defaults to [SDR]. + best_available: `--best-available`: take the best variant when a requested one is missing. + generate_dv: `--generate-dv`: make Dolby Vision when a title has no DV track, or for an HDR10 or HDR10P + base alone. """ codecs: list[Video.Codec] = field(default_factory=list) @@ -136,26 +139,51 @@ class Service(TitleSource): implementation when a Service does not define them. The main flow operates the HTTP session and authentication methods first, then titles, then tracks and chapters. The license callbacks operate later still, during track download. + + Attributes: + ALIASES: Other tags of the service, matched without case. + GEOFENCE: Region codes the service needs; empty means any region. With no `--proxy` and this machine + outside them, the service fetches a proxy to the first one that `GEOBLOCK` allows. + GEOBLOCK: Region codes where the service refuses to work; it works in every other region. + ANONYMOUS_SEARCH: `search()` needs no login, so a search skips the cookies and `authenticate()`. + VAULT_TAG: The key vault namespace, when it is not the tag of the service, such as to share one vault. + AUTH_METHODS: The accepted logins (`"cookies"`, `"credentials"`); when None, the REST `/services` + endpoint reads them from `authenticate()`. + CLIENT_CONFIG: Config keys of a device identity that a remote client gives when its own device licenses; + the server does not give its own values of these keys to that remote session. + SERVER_DEVICE_OPTIONS: Service options that make the service call `cdm.lend_server_device()`. With one + set, a remote session keeps the server CDM and the first device of the server's `cdm` entry. + IDENTITY_CACHE: Cache key prefixes of state built from the device identity, never login state. When the + server's device licenses, a remote session keeps them on the server, per API key. + NO_SUBTITLES: The service has no subtitles; dl drops its subtitle tracks and skips the caption extraction. + `get_tracks()` can set it for one title. + ANIME: The catalogue is anime, so metadata lookups try AniList before the configured order. + `Title.anime` overrides it. + METADATA_PROVIDER: The metadata provider that lookups try first, such as `"tmdb"`. It never adds a + provider that `metadata_providers` leaves out. `Title.metadata_provider` overrides it. + DAILY: The catalogue is date-based, so dl names episodes by air date. `Title.daily` overrides it. + config (dict): The `config.yaml` of the service with the `services.` block of `unshackle.yaml` + merged over it. + log (logging.Logger): A logger named after the service class. + session (requests.Session): The HTTP session from `get_session()`, with the proxy of the run. + Send every request through it. + cache (Cacher): A key/value `Cacher` for the service, such as for login tokens. + title_cache: The `TitleCacher` that `get_titles_cached` uses, per region and account. + cache_dir (Path): `config.directories.cache / `. + ctx (click.Context): The Click context of the run. + credential: The `Credential` that `authenticate()` gets, else None. + current_region (str | None): The two-letter region of the proxy exit or of this machine, else None. + track_request (TrackRequest): The `TrackRequest` from the CLI. A service can change it in its `__init__`. """ - 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. - 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. + ALIASES: tuple[str, ...] = () + GEOFENCE: tuple[str, ...] = () + GEOBLOCK: tuple[str, ...] = () + ANONYMOUS_SEARCH: bool = False VAULT_TAG: str | None = None - # Auth methods the service accepts ("cookies"/"credentials"); when None the REST /services - # endpoint infers them from authenticate(). AUTH_METHODS: tuple[str, ...] | None = None - # Config keys a remote client may supply for a session its own device licenses (a device identity - # such as an ESN); the server's own values for these keys are withheld from that session. CLIENT_CONFIG: tuple[str, ...] = () - # Every service option that makes the service call ``cdm.lend_server_device()``. A remote session with - # one of them set keeps the server CDM even when the remote client picked its own device, and the server - # loads the first-listed device of its cdm entry, whatever system the client's device is. SERVER_DEVICE_OPTIONS: tuple[str, ...] = () - # Cache key prefixes that hold state built from the device identity (a device ID, device session keys), never - # login state. A remote session on the server's device keeps them on the server, per API key. IDENTITY_CACHE: tuple[str, ...] = () def __init__(self, ctx: click.Context) -> None: @@ -172,11 +200,10 @@ class Service(TitleSource): self.cache_dir = config.directories.cache / self.__class__.__name__ self.ctx = ctx - self.credential: Credential | None = None # Will be set in authenticate() - self.current_region = None # Will be set based on proxy/geolocation + self.credential: Credential | None = None + self.current_region = None self._input_bridge: InputBridge | None = None - # Set track request from CLI params - services can read/override in their __init__ vcodec = ctx.parent.params.get("vcodec") if ctx.parent else None range_ = ctx.parent.params.get("range_") if ctx.parent else None best_available = ctx.parent.params.get("best_available", False) if ctx.parent else False diff --git a/unshackle/core/title_source.py b/unshackle/core/title_source.py index 293a1079..0f1acf05 100644 --- a/unshackle/core/title_source.py +++ b/unshackle/core/title_source.py @@ -128,10 +128,10 @@ class TitleSource(metaclass=ABCMeta): 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. - METADATA_PROVIDER: str | None = None # metadata lookups try this provider first. Title.metadata_provider overrides. - DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title. + NO_SUBTITLES: bool = False + ANIME: bool = False + METADATA_PROVIDER: str | None = None + DAILY: bool = False ctx: click.Context log: logging.Logger diff --git a/unshackle/services/EXAMPLE/__init__.py b/unshackle/services/EXAMPLE/__init__.py index 81f08db7..613096ed 100644 --- a/unshackle/services/EXAMPLE/__init__.py +++ b/unshackle/services/EXAMPLE/__init__.py @@ -70,13 +70,11 @@ class EXAMPLE(Service): # ALIASES: extra CLI tags that resolve to this service (e.g. `dl EX ...`). ALIASES = ("EX", "DOMAIN") - # GEOFENCE: regions required; the framework warns if the proxy exit region is not one of them. GEOFENCE = ("US", "GB") # GEOBLOCK: the negative form; regions where the service refuses to work, all others allowed. # GEOBLOCK = ("GB",) # TITLE_RE: named groups (?P<...>) parsed in get_titles(). Accepts URL or bare id. TITLE_RE = r"^(?:https?://(?:www\.)?domain\.com/details/)?(?P[^/?#]+)" - # NO_SUBTITLES: service-level idiom telling the pipeline subs are handled in-band. NO_SUBTITLES = False # ANIME: this catalogue is anime, so metadata lookups ask AniList first. Set it False (the # default) on a mixed catalogue and flag the anime titles individually in get_titles(). diff --git a/unshackle/services/MUSIC_EXAMPLE/__init__.py b/unshackle/services/MUSIC_EXAMPLE/__init__.py index 89b9e167..b9f81b1b 100644 --- a/unshackle/services/MUSIC_EXAMPLE/__init__.py +++ b/unshackle/services/MUSIC_EXAMPLE/__init__.py @@ -70,7 +70,6 @@ class MUSIC_EXAMPLE(Service): # ALIASES: extra CLI tags that resolve to this service (e.g. `dl MUSICEX ...`). ALIASES = ("MUSICEX", "MUSICDOMAIN") - # GEOFENCE: regions required; the framework warns if the proxy exit region is not one of them. GEOFENCE = ("US", "GB") # GEOBLOCK: the negative form; regions where the service refuses to work, all others allowed. # GEOBLOCK = ("GB",)