feat(dl): let a service force --license-first with the LICENSE_FIRST class variable

This commit is contained in:
imSp4rky
2026-12-05 20:23:47 -07:00
parent ce7cb41eac
commit bd178bc3af
18 changed files with 59 additions and 5 deletions
+3 -1
View File
@@ -446,7 +446,8 @@ file on the server travels as base64, and the client writes it to its own temp d
"server_cdm": false, "server_cdm": false,
"server_cdm_type": "widevine", "server_cdm_type": "widevine",
"sample_decrypt_tracks": [], "sample_decrypt_tracks": [],
"fairplay_bridge": false "fairplay_bridge": false,
"license_first": false
} }
``` ```
@@ -461,6 +462,7 @@ The remote session fields (`TracksReply`):
| `server_cdm_type` | The DRM system that a server-CDM licence takes first for the tracks of this title. | | `server_cdm_type` | The DRM system that a server-CDM licence takes first for the tracks of this title. |
| `sample_decrypt_tracks` | The IDs of the tracks that the service decrypts itself, through the `samples` route. | | `sample_decrypt_tracks` | The IDs of the tracks that the service decrypts itself, through the `samples` route. |
| `fairplay_bridge` | `true` when the service licenses FairPlay-only tracks through a bridge on the server. | | `fairplay_bridge` | `true` when the service licenses FairPlay-only tracks through a bridge on the server. |
| `license_first` | The `LICENSE_FIRST` value of the service. When `true`, the client licenses every track of a title before any track downloads, as with `--license-first`. |
| Status | Error code | Meaning | | Status | Error code | Meaning |
| --- | --- | --- | | --- | --- | --- |
+1 -1
View File
@@ -216,7 +216,7 @@ Keep only certain track types, or skip certain track types.
| `--vaults-only` | Get no licence. A content key that no key vault, export or earlier track gives fails the title. With both flags, the last one wins. | | `--vaults-only` | Get no licence. A content key that no key vault, export or earlier track gives fails the title. With both flags, the last one wins. |
| `--cdm <name>` | Use the named CDM device for this run, and ignore the `cdm` config mapping, its quality and Widevine/PlayReady entries included. Over `--remote`, that device licenses the remote session, not the server CDM. | | `--cdm <name>` | Use the named CDM device for this run, and ignore the `cdm` config mapping, its quality and Widevine/PlayReady entries included. Over `--remote`, that device licenses the remote session, not the server CDM. |
| `--skip-dl` | Skip the download but still retrieve keys. | | `--skip-dl` | Skip the download but still retrieve keys. |
| `--license-first` | Get the content keys of every track of a title before any track of that title downloads. A failed licence then stops the run before that title downloads data. Over `--remote` it applies on the client. No effect with `--skip-dl`. | | `--license-first` | Get the content keys of every track of a title before any track of that title downloads. A failed licence then stops the run before that title downloads data. Over `--remote` it applies on the client. No effect with `--skip-dl`. A service can turn it on for every run with [`LICENSE_FIRST`](../reference/api/service.md). |
| `--all-drm` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; `--cdm-only` sends a challenge for each system. Not for use with `--cdm`. | | `--all-drm` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; `--cdm-only` sends a challenge for each system. Not for use with `--cdm`. |
| `--export` | Write an [export](downloading.md#keys-vaults-and-export) of each title's tracks, DRM init data and content keys to the exports directory. | | `--export` | Write an [export](downloading.md#keys-vaults-and-export) of each title's tracks, DRM init data and content keys to the exports directory. |
+1
View File
@@ -68,6 +68,7 @@ prints every title the service returned and stops before `--wanted`/`--latest-ep
filtering. `--skip-dl` runs the licence step but skips the segment download. filtering. `--skip-dl` runs the licence step but skips the segment download.
`--license-first` runs the licence step of every track of a title before any segment of that title downloads, `--license-first` runs the licence step of every track of a title before any segment of that title downloads,
so a failed licence stops the run before that title downloads data. The download then sends no second licence. so a failed licence stops the run before that title downloads data. The download then sends no second licence.
A service can turn it on for every run with [`LICENSE_FIRST`](../reference/api/service.md).
## Choosing quality ## Choosing quality
+1 -1
View File
@@ -56,7 +56,7 @@ Common config keys. This is a useful subset, and every `dl` flag works:
| `slow` | str | *(unset)* | Inter-title delay, e.g. `"20-40"`. | | `slow` | str | *(unset)* | Inter-title delay, e.g. `"20-40"`. |
| `best_available` | bool | `false` | Warn instead of failing when a requested resolution, range, video language, or audio language is missing, or when one DRM system does not license under `--all-drm`. The CLI flag is `--best-available`, also spelled `--warn-only`. | | `best_available` | bool | `false` | Warn instead of failing when a requested resolution, range, video language, or audio language is missing, or when one DRM system does not license under `--all-drm`. The CLI flag is `--best-available`, also spelled `--warn-only`. |
| `skip_missing` | bool | `false` | Skip a title that misses a required language (`require_audio`, `require_video`, `require_subs`) or a track that a filter asks for, and continue with the next title. A run with one title, or a run that skips every title, still fails. The CLI flag is `--skip-missing`. For REST API jobs, set it in the [`serve`](services.md#serve) block. | | `skip_missing` | bool | `false` | Skip a title that misses a required language (`require_audio`, `require_video`, `require_subs`) or a track that a filter asks for, and continue with the next title. A run with one title, or a run that skips every title, still fails. The CLI flag is `--skip-missing`. For REST API jobs, set it in the [`serve`](services.md#serve) block. |
| `license_first` | bool | `false` | Get the content keys of every track of a title before any track of that title downloads. A failed licence stops the run before that title downloads data. The CLI flag is `--license-first`. For REST API jobs, set it in the [`serve`](services.md#serve) block or send `license_first` in the request. | | `license_first` | bool | `false` | Get the content keys of every track of a title before any track of that title downloads. A failed licence stops the run before that title downloads data. The CLI flag is `--license-first`. A `false` value does not turn off the [`LICENSE_FIRST`](../api/service.md) of a service. For REST API jobs, set it in the [`serve`](services.md#serve) block or send `license_first` in the request. |
| `generate_dv` | bool | `false` | With `-r HYBRID`, make Dolby Vision from the HDR10+ metadata or the decoded video when a title has no DV track. With `-r HDR10` or `-r HDR10P`, make it for that base and ignore a DV track. See [Dolby Vision without a DV track](../../guide/downloading.md#dolby-vision-without-a-dv-track). | | `generate_dv` | bool | `false` | With `-r HYBRID`, make Dolby Vision from the HDR10+ metadata or the decoded video when a title has no DV track. With `-r HDR10` or `-r HDR10P`, make it for that base and ignore a DV track. See [Dolby Vision without a DV track](../../guide/downloading.md#dolby-vision-without-a-dv-track). |
| `proxy` | str | *(unset)* | Default proxy URI or 2-letter country. | | `proxy` | str | *(unset)* | Default proxy URI or 2-letter country. |
| `no_folder` | bool | `false` | Do not create a per-title folder. | | `no_folder` | bool | `false` | Do not create a per-title folder. |
+16
View File
@@ -128,6 +128,22 @@ def test_without_the_flag_a_track_downloads_before_a_later_licence_fails(
assert run.fetched == ["Video_video.mp4"], result.output assert run.fetched == ["Video_video.mp4"], result.output
def test_a_service_with_license_first_licenses_every_track_with_no_flag(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
from unshackle.core import services
monkeypatch.setattr(services.ensure_loaded("EXAMPLE"), "LICENSE_FIRST", True)
run = Run(monkeypatch, tmp_path, refuse="audio")
result = run()
assert "Licence refused for track audio" in result.output
assert result.exit_code == 1
assert run.licences == ["video", "audio"]
assert run.fetched == []
def test_the_download_pass_sends_no_second_licence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: def test_the_download_pass_sends_no_second_licence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
run = Run(monkeypatch, tmp_path) run = Run(monkeypatch, tmp_path)
+16
View File
@@ -46,6 +46,7 @@ class StubService:
A test puts extra service work in ``hooks``: "titles" runs inside get_titles, on the service thread. A test puts extra service work in ``hooks``: "titles" runs inside get_titles, on the service thread.
""" """
LICENSE_FIRST = False
logins = 0 logins = 0
hooks: dict[str, Callable[[StubService], None]] = {} hooks: dict[str, Callable[[StubService], None]] = {}
@@ -290,3 +291,18 @@ def test_server_request_records_never_reach_the_remote_client(
assert all("body" not in e["response"] for e in entries) assert all("body" not in e["response"] for e in entries)
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")] own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
assert own and all((tmp_path / "server" / e["response"]["body_file"]).is_file() for e in own) assert own and all((tmp_path / "server" / e["response"]["body_file"]).is_file() for e in own)
@pytest.mark.parametrize("forced", [True, False])
def test_the_client_reports_the_license_first_of_the_served_service(
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, forced: bool
) -> None:
monkeypatch.setattr(StubService, "LICENSE_FIRST", forced)
remote = make_client(server.url)
try:
remote.authenticate()
remote.get_tracks(remote.get_titles()[0])
finally:
remote.close()
assert remote.LICENSE_FIRST is forced
@@ -263,6 +263,8 @@ def test_the_tracks_response_names_the_system_of_the_loaded_device(monkeypatch,
monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: None) monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: None)
class StubService: class StubService:
LICENSE_FIRST = False
session = SimpleNamespace(headers={}, cookies=[]) session = SimpleNamespace(headers={}, cookies=[])
ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(is_playready=system == "playready"))) ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(is_playready=system == "playready")))
@@ -308,6 +310,7 @@ def _reply_then_licence(monkeypatch, track, drm_type, loaded=None):
"get_chapters": lambda self, title: [], "get_chapters": lambda self, title: [],
"decrypts_samples": lambda self, track: False, "decrypts_samples": lambda self, track: False,
"fairplay_bridge": lambda self: None, "fairplay_bridge": lambda self: None,
"LICENSE_FIRST": False,
"get_widevine_service_certificate": lambda self, **k: None, "get_widevine_service_certificate": lambda self, **k: None,
"get_widevine_license": lambda self, **k: b"", "get_widevine_license": lambda self, **k: b"",
"get_playready_license": lambda self, **k: b"", "get_playready_license": lambda self, **k: b"",
@@ -116,6 +116,8 @@ def tracks_reply(client_plugins: Any) -> tuple[Any, Any]:
"""The answer of the tracks route for a title with an EXAMPLE plugin track (its body or its APIError), and the session.""" """The answer of the tracks route for a title with an EXAMPLE plugin track (its body or its APIError), and the session."""
class StubService: class StubService:
LICENSE_FIRST = False
session = SimpleNamespace(headers={}, cookies=[]) session = SimpleNamespace(headers={}, cookies=[])
def fairplay_bridge(self) -> None: def fairplay_bridge(self) -> None:
@@ -110,6 +110,8 @@ def test_tracks_handler_marks_the_title_live_before_it_fetches(monkeypatch: pyte
monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: published.append((topic, data))) monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: published.append((topic, data)))
class StubService: class StubService:
LICENSE_FIRST = False
session = SimpleNamespace(headers={}, cookies=[]) session = SimpleNamespace(headers={}, cookies=[])
def fairplay_bridge(self) -> None: def fairplay_bridge(self) -> None:
+2
View File
@@ -97,6 +97,8 @@ def call_session_handler(handler, body, service, **entry_fields):
class StubService: class StubService:
LICENSE_FIRST = False
def __init__(self, tracks=(), cookies=()): def __init__(self, tracks=(), cookies=()):
self.session = SimpleNamespace(headers={}, cookies=list(cookies)) self.session = SimpleNamespace(headers={}, cookies=list(cookies))
self.tracks = list(tracks) self.tracks = list(tracks)
+1 -1
View File
@@ -2452,7 +2452,7 @@ class dl:
progress_callables=tracks_progress_callables, progress_callables=tracks_progress_callables,
disk_check=disk_check, disk_check=disk_check,
) )
if license_first and not skip_dl: if (license_first or service.LICENSE_FIRST) and not skip_dl:
license_before_download( license_before_download(
title.tracks, title.tracks,
downloads, downloads,
+1
View File
@@ -3274,6 +3274,7 @@ async def session_tracks_handler(
str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t) str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t)
], ],
fairplay_bridge=service_instance.fairplay_bridge() is not None, fairplay_bridge=service_instance.fairplay_bridge() is not None,
license_first=service_instance.LICENSE_FIRST,
) )
reply = await asyncio.to_thread( reply = await asyncio.to_thread(
+2 -1
View File
@@ -1263,7 +1263,8 @@ async def download(request: web.Request) -> web.Response:
default: false default: false
description: >- description: >-
Get the content keys of every track of a title before any track of the title downloads. A licence Get the content keys of every track of a title before any track of the title downloads. A licence
failure stops the run before that title downloads data. No effect with `skip_dl`. failure stops the run before that title downloads data. No effect with `skip_dl`. A service with
`LICENSE_FIRST` always does this.
all_drm: all_drm:
type: boolean type: boolean
default: false default: false
+1
View File
@@ -291,6 +291,7 @@ class TracksReply(TypedDict, total=False):
server_cdm_type: str server_cdm_type: str
sample_decrypt_tracks: list[str] sample_decrypt_tracks: list[str]
fairplay_bridge: bool fairplay_bridge: bool
license_first: bool
class SegmentsRequest(TypedDict): class SegmentsRequest(TypedDict):
+1
View File
@@ -1502,6 +1502,7 @@ class RemoteService(TitleSource):
self.server_cdm_type = session_fields.get("server_cdm_type", "widevine") self.server_cdm_type = session_fields.get("server_cdm_type", "widevine")
self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or []) self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or [])
self._fairplay_bridge = bool(session_fields.get("fairplay_bridge")) self._fairplay_bridge = bool(session_fields.get("fairplay_bridge"))
self.LICENSE_FIRST = bool(session_fields.get("license_first"))
for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]: for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]:
if track.descriptor == Track.Descriptor.HLS: if track.descriptor == Track.Descriptor.HLS:
+2
View File
@@ -162,6 +162,8 @@ class Service(TitleSource):
METADATA_PROVIDER: The metadata provider that lookups try first, such as `"tmdb"`. It never adds a 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. 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. DAILY: The catalogue is date-based, so dl names episodes by air date. `Title.daily` overrides it.
LICENSE_FIRST: Every run of the service licenses each track of a title before any track downloads, as with
`dl --license-first`, locally and over `--remote`. The user cannot turn it off; `--skip-dl` skips it.
config (dict): The `config.yaml` of the service with the `services.<TAG>` block of `unshackle.yaml` config (dict): The `config.yaml` of the service with the `services.<TAG>` block of `unshackle.yaml`
merged over it. merged over it.
log (logging.Logger): A logger named after the service class. log (logging.Logger): A logger named after the service class.
+1
View File
@@ -132,6 +132,7 @@ class TitleSource(metaclass=ABCMeta):
ANIME: bool = False ANIME: bool = False
METADATA_PROVIDER: str | None = None METADATA_PROVIDER: str | None = None
DAILY: bool = False DAILY: bool = False
LICENSE_FIRST: bool = False
ctx: click.Context ctx: click.Context
log: logging.Logger log: logging.Logger
+3
View File
@@ -83,6 +83,9 @@ class EXAMPLE(Service):
# Lookups ask it first, ahead of AniList. It never adds one that the user's metadata_providers # Lookups ask it first, ahead of AniList. It never adds one that the user's metadata_providers
# leaves out. Set it when one index matches the names this service gives better than the default order. # leaves out. Set it when one index matches the names this service gives better than the default order.
METADATA_PROVIDER = None METADATA_PROVIDER = None
# LICENSE_FIRST: set True when the platform flags an account that downloads without a licence, or
# a licence fails often. Every run then licenses all tracks of a title before any track downloads.
LICENSE_FIRST = False
# ANONYMOUS_SEARCH: set True only when search() needs no login and no state from # ANONYMOUS_SEARCH: set True only when search() needs no login and no state from
# authenticate(). A search then skips the cookie load, authenticate() and the cookie save. # authenticate(). A search then skips the cookie load, authenticate() and the cookie save.
ANONYMOUS_SEARCH = False ANONYMOUS_SEARCH = False