mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-30 13:05:08 +00:00
refactor(export): move the --export writer out of dl into core ExportWriter
This commit is contained in:
@@ -2,35 +2,34 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any
|
from unittest.mock import create_autospec
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
from unshackle.core.drm import verify
|
from unshackle.core.drm import verify
|
||||||
|
from unshackle.core.export_writer import ExportWriter
|
||||||
|
|
||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
|
|
||||||
def runner(written: list[tuple[Any, ...]]) -> dl:
|
def runner() -> dl:
|
||||||
cmd = dl.__new__(dl)
|
cmd = dl.__new__(dl)
|
||||||
cmd.vaults = SimpleNamespace()
|
cmd.vaults = SimpleNamespace()
|
||||||
cmd.service = "EXAMPLE"
|
cmd.service = "EXAMPLE"
|
||||||
cmd.debug_logger = None
|
cmd.debug_logger = None
|
||||||
cmd._remote_service = SimpleNamespace()
|
cmd._remote_service = SimpleNamespace()
|
||||||
cmd.write_export = lambda *args: written.append(args) # type: ignore[method-assign]
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("cdm_only, vaults_only, best_available", [(True, False, False), (False, True, True)])
|
@pytest.mark.parametrize("cdm_only, vaults_only, best_available", [(True, False, False), (False, True, True)])
|
||||||
def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
||||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm_only: bool, vaults_only: bool, best_available: bool
|
monkeypatch: pytest.MonkeyPatch, cdm_only: bool, vaults_only: bool, best_available: bool
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
|
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
|
||||||
written: list[tuple[Any, ...]] = []
|
writer = create_autospec(ExportWriter, instance=True)
|
||||||
cmd = runner(written)
|
cmd = runner()
|
||||||
service = SimpleNamespace()
|
service = SimpleNamespace()
|
||||||
|
|
||||||
cmd.start_key_resolution(
|
cmd.start_key_resolution(
|
||||||
@@ -38,7 +37,7 @@ def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
|||||||
cdm_only=cdm_only,
|
cdm_only=cdm_only,
|
||||||
vaults_only=vaults_only,
|
vaults_only=vaults_only,
|
||||||
best_available=best_available,
|
best_available=best_available,
|
||||||
export=tmp_path / "export.json",
|
export=writer,
|
||||||
)
|
)
|
||||||
|
|
||||||
keys = cmd.keys
|
keys = cmd.keys
|
||||||
@@ -48,12 +47,12 @@ def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
|||||||
assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE"
|
assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE"
|
||||||
assert keys.export is not None
|
assert keys.export is not None
|
||||||
keys.export("title", "track", "drm")
|
keys.export("title", "track", "drm")
|
||||||
assert written == [(tmp_path / "export.json", "title", "track", "drm")]
|
writer.record.assert_called_once_with("title", "track", "drm")
|
||||||
|
|
||||||
|
|
||||||
def test_no_export_path_gives_no_export_callback(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_no_export_gives_no_export_callback(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
|
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
|
||||||
cmd = runner([])
|
cmd = runner()
|
||||||
|
|
||||||
cmd.start_key_resolution(SimpleNamespace(), cdm_only=False, vaults_only=True, best_available=False, export=None)
|
cmd.start_key_resolution(SimpleNamespace(), cdm_only=False, vaults_only=True, best_available=False, export=None)
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,9 @@ from datetime import date
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
|
||||||
from unshackle.core.config import Config, config
|
from unshackle.core.config import Config, config
|
||||||
from unshackle.core.titles.episode import Episode
|
from unshackle.core.titles.episode import Episode
|
||||||
from unshackle.core.wire import build_title, serialize_title
|
from unshackle.core.wire import build_title, serialize_title, title_to_meta
|
||||||
|
|
||||||
SERIES = "{title}.{year?}.{season_episode}.{episode_name?}.{quality?}-{tag?}"
|
SERIES = "{title}.{year?}.{season_episode}.{episode_name?}.{quality?}-{tag?}"
|
||||||
SPORTS = "{title}.{year?}.{date?}.{episode_name}.{quality?}-{tag?}"
|
SPORTS = "{title}.{year?}.{date?}.{episode_name}.{quality?}-{tag?}"
|
||||||
@@ -90,7 +89,7 @@ def test_the_sport_flag_survives_the_remote_round_trip():
|
|||||||
|
|
||||||
|
|
||||||
def test_the_sport_flag_survives_the_export_round_trip():
|
def test_the_sport_flag_survives_the_export_round_trip():
|
||||||
rebuilt = build_title(dl.title_to_meta(make_episode()), "TEST", fallback_id="x")
|
rebuilt = build_title(title_to_meta(make_episode()), "TEST", fallback_id="x")
|
||||||
assert isinstance(rebuilt, Episode) and rebuilt.sport
|
assert isinstance(rebuilt, Episode) and rebuilt.sport
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+97
-48
@@ -1,6 +1,6 @@
|
|||||||
"""Tests for ``dl.write_export``, the ``--export`` mediaexport sidecar.
|
"""Tests for ``ExportWriter.record``, the ``--export`` mediaexport sidecar.
|
||||||
|
|
||||||
Regression: DRM-free tracks never pass through ``prepare_drm``, so ``write_export``
|
Regression: DRM-free tracks never pass through ``prepare_drm``, so ``record``
|
||||||
must accept ``drm=None`` (and DRM systems without ``to_dict``/``content_keys`` such
|
must accept ``drm=None`` (and DRM systems without ``to_dict``/``content_keys`` such
|
||||||
as ClearKey) and still record the track/manifest/chapter/attachment info that
|
as ClearKey) and still record the track/manifest/chapter/attachment info that
|
||||||
``unshackle import`` rebuilds a download from.
|
``unshackle import`` rebuilds a download from.
|
||||||
@@ -18,9 +18,9 @@ from uuid import UUID
|
|||||||
import click
|
import click
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
|
||||||
from unshackle.core.drm.clearkey import ClearKey
|
from unshackle.core.drm.clearkey import ClearKey
|
||||||
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
|
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
|
||||||
|
from unshackle.core.export_writer import ExportWriter
|
||||||
from unshackle.core.import_service import ImportService
|
from unshackle.core.import_service import ImportService
|
||||||
from unshackle.core.titles import Movie
|
from unshackle.core.titles import Movie
|
||||||
from unshackle.core.tracks import Audio, Chapter, Subtitle, Video
|
from unshackle.core.tracks import Audio, Chapter, Subtitle, Video
|
||||||
@@ -43,12 +43,21 @@ class StubDRM:
|
|||||||
return {"system": "Widevine", "pssh_b64": "AAAA"}
|
return {"system": "Widevine", "pssh_b64": "AAAA"}
|
||||||
|
|
||||||
|
|
||||||
def make_dl() -> dl:
|
class StubSource:
|
||||||
# __new__ skips the CLI-driven __init__; write_export only needs `service` and `log`.
|
"""A title source with no session headers and no region."""
|
||||||
instance = dl.__new__(dl)
|
|
||||||
instance.service = "EXAMPLE"
|
session = None
|
||||||
instance.log = logging.getLogger("download")
|
current_region = None
|
||||||
return instance
|
|
||||||
|
|
||||||
|
def make_writer(tmp_path: Path, source: Any = None, proxy_requested: bool = False) -> ExportWriter:
|
||||||
|
return ExportWriter(tmp_path / "export_EXAMPLE_1.json", "EXAMPLE", source or StubSource(), proxy_requested)
|
||||||
|
|
||||||
|
|
||||||
|
def written(writer: ExportWriter) -> Path:
|
||||||
|
"""The export file after the writer named it."""
|
||||||
|
assert writer.namer.path is not None
|
||||||
|
return writer.namer.path
|
||||||
|
|
||||||
|
|
||||||
def make_title() -> Movie:
|
def make_title() -> Movie:
|
||||||
@@ -100,11 +109,12 @@ def entry(path: Path) -> dict:
|
|||||||
|
|
||||||
def test_drm_free_track_exports(tmp_path: Path) -> None:
|
def test_drm_free_track_exports(tmp_path: Path) -> None:
|
||||||
"""The reported bug: DRM-free downloads produced no usable export."""
|
"""The reported bug: DRM-free downloads produced no usable export."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
video = title.tracks.videos[0]
|
video = title.tracks.videos[0]
|
||||||
|
|
||||||
make_dl().write_export(export, title, video)
|
writer.record(title, video)
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
doc = read_export(export)
|
doc = read_export(export)
|
||||||
assert doc["kind"] == "mediaexport" and doc["version"] == 1
|
assert doc["kind"] == "mediaexport" and doc["version"] == 1
|
||||||
@@ -119,11 +129,12 @@ def test_drm_free_track_exports(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
def test_clearkey_drm_exports_track_without_keys(tmp_path: Path) -> None:
|
def test_clearkey_drm_exports_track_without_keys(tmp_path: Path) -> None:
|
||||||
"""ClearKey has no to_dict/content_keys; the track info must still export."""
|
"""ClearKey has no to_dict/content_keys; the track info must still export."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
video = title.tracks.videos[0]
|
video = title.tracks.videos[0]
|
||||||
|
|
||||||
make_dl().write_export(export, title, video, ClearKey(key="bb" * 16))
|
writer.record(title, video, ClearKey(key="bb" * 16))
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
tinfo = entry(export)
|
tinfo = entry(export)
|
||||||
assert "keys" not in tinfo and "drm" not in tinfo
|
assert "keys" not in tinfo and "drm" not in tinfo
|
||||||
@@ -132,13 +143,13 @@ def test_clearkey_drm_exports_track_without_keys(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
def test_post_download_write_keeps_licensed_keys(tmp_path: Path) -> None:
|
def test_post_download_write_keeps_licensed_keys(tmp_path: Path) -> None:
|
||||||
"""The drm=None write after download must not clobber prepare_drm's DRM/keys."""
|
"""The drm=None write after download must not clobber prepare_drm's DRM/keys."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
video = title.tracks.videos[0]
|
video = title.tracks.videos[0]
|
||||||
runner = make_dl()
|
|
||||||
|
|
||||||
runner.write_export(export, title, video, StubDRM()) # prepare_drm
|
writer.record(title, video, StubDRM()) # prepare_drm
|
||||||
runner.write_export(export, title, video) # post-download hook
|
writer.record(title, video) # post-download hook
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
tinfo = entry(export)
|
tinfo = entry(export)
|
||||||
assert tinfo["drm"] == [{"system": "widevine", "pssh": "AAAA"}]
|
assert tinfo["drm"] == [{"system": "widevine", "pssh": "AAAA"}]
|
||||||
@@ -149,12 +160,12 @@ def test_post_download_write_keeps_licensed_keys(tmp_path: Path) -> None:
|
|||||||
def test_drm_free_export_roundtrips_through_import_service(tmp_path: Path) -> None:
|
def test_drm_free_export_roundtrips_through_import_service(tmp_path: Path) -> None:
|
||||||
"""A DRM-free export must rebuild via ImportService: titles, tracks (no DRM),
|
"""A DRM-free export must rebuild via ImportService: titles, tracks (no DRM),
|
||||||
empty key pool (resolve_server_keys no-op) and chapters."""
|
empty key pool (resolve_server_keys no-op) and chapters."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
title.tracks.chapters.add(Chapter("00:00:10.000", "Intro"))
|
title.tracks.chapters.add(Chapter("00:00:10.000", "Intro"))
|
||||||
runner = make_dl()
|
|
||||||
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
||||||
runner.write_export(export, title, track)
|
writer.record(title, track)
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
||||||
|
|
||||||
@@ -181,12 +192,13 @@ def test_drm_free_export_roundtrips_through_import_service(tmp_path: Path) -> No
|
|||||||
def test_clearkey_cenc_exports_drm_and_keys(tmp_path: Path) -> None:
|
def test_clearkey_cenc_exports_drm_and_keys(tmp_path: Path) -> None:
|
||||||
"""A licensed ClearKeyCENC exports its system dict and KID:KEY map, and the
|
"""A licensed ClearKeyCENC exports its system dict and KID:KEY map, and the
|
||||||
exported DRM dict plus keys rebuild a decrypt-ready instance via drm_from_dict."""
|
exported DRM dict plus keys rebuild a decrypt-ready instance via drm_from_dict."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
video = title.tracks.videos[0]
|
video = title.tracks.videos[0]
|
||||||
drm = ClearKeyCENC(kids=[KID], laurl="https://license.example.test/ck", content_keys={KID: "cc" * 16})
|
drm = ClearKeyCENC(kids=[KID], laurl="https://license.example.test/ck", content_keys={KID: "cc" * 16})
|
||||||
|
|
||||||
make_dl().write_export(export, title, video, drm)
|
writer.record(title, video, drm)
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
tinfo = entry(export)
|
tinfo = entry(export)
|
||||||
assert tinfo["drm"] == [{"system": "clearkey"}]
|
assert tinfo["drm"] == [{"system": "clearkey"}]
|
||||||
@@ -201,13 +213,14 @@ def test_clearkey_cenc_exports_drm_and_keys(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
def test_keyless_content_keys_writes_no_keys_entry(tmp_path: Path) -> None:
|
def test_keyless_content_keys_writes_no_keys_entry(tmp_path: Path) -> None:
|
||||||
"""A DRM object with empty content_keys must not create an empty keys map."""
|
"""A DRM object with empty content_keys must not create an empty keys map."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
video = title.tracks.videos[0]
|
video = title.tracks.videos[0]
|
||||||
drm = StubDRM()
|
drm = StubDRM()
|
||||||
drm.content_keys = {}
|
drm.content_keys = {}
|
||||||
|
|
||||||
make_dl().write_export(export, title, video, drm)
|
writer.record(title, video, drm)
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
tinfo = entry(export)
|
tinfo = entry(export)
|
||||||
assert tinfo["drm"] == [{"system": "widevine", "pssh": "AAAA"}]
|
assert tinfo["drm"] == [{"system": "widevine", "pssh": "AAAA"}]
|
||||||
@@ -313,14 +326,13 @@ class KeyDRM:
|
|||||||
|
|
||||||
def test_export_drops_session_headers(tmp_path: Path) -> None:
|
def test_export_drops_session_headers(tmp_path: Path) -> None:
|
||||||
"""The file travels between people: the session cookie and bearer token must not go with it."""
|
"""The file travels between people: the session cookie and bearer token must not go with it."""
|
||||||
export = tmp_path / "export.json"
|
|
||||||
title = make_title()
|
title = make_title()
|
||||||
title.tracks.manifest_url = "https://example.test/m.mpd"
|
title.tracks.manifest_url = "https://example.test/m.mpd"
|
||||||
runner = make_dl()
|
|
||||||
headers = {"User-Agent": "example-ua", "Cookie": "session=secret", "Authorization": "Bearer secret"}
|
headers = {"User-Agent": "example-ua", "Cookie": "session=secret", "Authorization": "Bearer secret"}
|
||||||
runner.export_service = cast(Any, SimpleNamespace(session=SimpleNamespace(headers=headers)))
|
writer = make_writer(tmp_path, SimpleNamespace(session=SimpleNamespace(headers=headers)))
|
||||||
|
|
||||||
runner.write_export(export, title, title.tracks.videos[0])
|
writer.record(title, title.tracks.videos[0])
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
assert entry(export)["manifests"][0]["headers"] == {"User-Agent": "example-ua"}
|
assert entry(export)["manifests"][0]["headers"] == {"User-Agent": "example-ua"}
|
||||||
assert "secret" not in export.read_text(encoding="utf8")
|
assert "secret" not in export.read_text(encoding="utf8")
|
||||||
@@ -328,14 +340,14 @@ def test_export_drops_session_headers(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
def test_second_key_for_one_kid_keeps_the_first(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
def test_second_key_for_one_kid_keeps_the_first(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
"""Two titles that license one KID to different keys: the file keeps the first key and stays readable."""
|
"""Two titles that license one KID to different keys: the file keeps the first key and stays readable."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
first, second = make_title(), make_title()
|
first, second = make_title(), make_title()
|
||||||
second.id = "movie-2"
|
second.id = "movie-2"
|
||||||
runner = make_dl()
|
|
||||||
|
|
||||||
runner.write_export(export, first, first.tracks.videos[0], KeyDRM("aa" * 16))
|
writer.record(first, first.tracks.videos[0], KeyDRM("aa" * 16))
|
||||||
with caplog.at_level(logging.WARNING, logger="download"):
|
with caplog.at_level(logging.WARNING, logger="download"):
|
||||||
runner.write_export(export, second, second.tracks.videos[0], KeyDRM("bb" * 16))
|
writer.record(second, second.tracks.videos[0], KeyDRM("bb" * 16))
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
titles = read_export(export)["titles"]
|
titles = read_export(export)["titles"]
|
||||||
assert titles[0]["keys"] == {KID.hex: "aa" * 16}
|
assert titles[0]["keys"] == {KID.hex: "aa" * 16}
|
||||||
@@ -345,14 +357,14 @@ def test_second_key_for_one_kid_keeps_the_first(tmp_path: Path, caplog: pytest.L
|
|||||||
|
|
||||||
def test_uppercase_content_key_is_stored_lowercase(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
def test_uppercase_content_key_is_stored_lowercase(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
"""A licence server that sends uppercase hex still gives one key, not a conflict with itself."""
|
"""A licence server that sends uppercase hex still gives one key, not a conflict with itself."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
first, second = make_title(), make_title()
|
first, second = make_title(), make_title()
|
||||||
second.id = "movie-2"
|
second.id = "movie-2"
|
||||||
runner = make_dl()
|
|
||||||
|
|
||||||
runner.write_export(export, first, first.tracks.videos[0], KeyDRM("AA" * 16))
|
writer.record(first, first.tracks.videos[0], KeyDRM("AA" * 16))
|
||||||
with caplog.at_level(logging.WARNING, logger="download"):
|
with caplog.at_level(logging.WARNING, logger="download"):
|
||||||
runner.write_export(export, second, second.tracks.videos[0], KeyDRM("AA" * 16))
|
writer.record(second, second.tracks.videos[0], KeyDRM("AA" * 16))
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
titles = read_export(export)["titles"]
|
titles = read_export(export)["titles"]
|
||||||
assert titles[0]["keys"] == {KID.hex: "aa" * 16}
|
assert titles[0]["keys"] == {KID.hex: "aa" * 16}
|
||||||
@@ -364,13 +376,13 @@ def test_malformed_content_key_skips_the_key_not_the_download(
|
|||||||
tmp_path: Path, caplog: pytest.LogCaptureFixture, key: str
|
tmp_path: Path, caplog: pytest.LogCaptureFixture, key: str
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A key that is not 16 bytes of hex, as a new DRM system's tool might return, must not stop licensing."""
|
"""A key that is not 16 bytes of hex, as a new DRM system's tool might return, must not stop licensing."""
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
title.tracks.manifest_url = "https://example.test/m.mpd"
|
title.tracks.manifest_url = "https://example.test/m.mpd"
|
||||||
runner = make_dl()
|
|
||||||
|
|
||||||
with caplog.at_level(logging.WARNING, logger="download"):
|
with caplog.at_level(logging.WARNING, logger="download"):
|
||||||
runner.write_export(export, title, title.tracks.videos[0], KeyDRM(key))
|
writer.record(title, title.tracks.videos[0], KeyDRM(key))
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
assert "keys" not in entry(export)
|
assert "keys" not in entry(export)
|
||||||
assert f"Not exporting the key for KID {KID.hex}" in caplog.text
|
assert f"Not exporting the key for KID {KID.hex}" in caplog.text
|
||||||
@@ -412,8 +424,9 @@ def export_service_filtered_title(tmp_path: Path, manifest_url: str | None) -> P
|
|||||||
assert video.data["dash"]["filtered_period_ids"] == ["ad-1"]
|
assert video.data["dash"]["filtered_period_ids"] == ["ad-1"]
|
||||||
title.tracks.add(video)
|
title.tracks.add(video)
|
||||||
title.tracks.manifest_url = manifest_url
|
title.tracks.manifest_url = manifest_url
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
make_dl().write_export(export, title, video)
|
writer.record(title, video)
|
||||||
|
export = written(writer)
|
||||||
doc = read_export(export)
|
doc = read_export(export)
|
||||||
doc["titles"][0]["x-unshackle"].pop("snapshot", None)
|
doc["titles"][0]["x-unshackle"].pop("snapshot", None)
|
||||||
export.write_text(json.dumps(doc), encoding="utf8")
|
export.write_text(json.dumps(doc), encoding="utf8")
|
||||||
@@ -479,12 +492,12 @@ def test_import_keeps_every_period_when_no_exported_period_is_left(
|
|||||||
|
|
||||||
|
|
||||||
def test_a_3d_video_stays_3d_through_export_and_import(tmp_path: Path) -> None:
|
def test_a_3d_video_stays_3d_through_export_and_import(tmp_path: Path) -> None:
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = make_title()
|
title = make_title()
|
||||||
title.tracks.videos[0].stereo = True
|
title.tracks.videos[0].stereo = True
|
||||||
runner = make_dl()
|
|
||||||
for track in [*title.tracks.videos, *title.tracks.audio]:
|
for track in [*title.tracks.videos, *title.tracks.audio]:
|
||||||
runner.write_export(export, title, track)
|
writer.record(title, track)
|
||||||
|
export = written(writer)
|
||||||
assert [row.get("stereo") for row in entry(export)["tracks"]][0] is True
|
assert [row.get("stereo") for row in entry(export)["tracks"]][0] is True
|
||||||
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
||||||
movie = next(iter(svc.get_titles()))
|
movie = next(iter(svc.get_titles()))
|
||||||
@@ -498,12 +511,48 @@ class ProviderService:
|
|||||||
|
|
||||||
|
|
||||||
def test_the_service_metadata_provider_survives_export_and_import(tmp_path: Path) -> None:
|
def test_the_service_metadata_provider_survives_export_and_import(tmp_path: Path) -> None:
|
||||||
export = tmp_path / "export.json"
|
|
||||||
title = make_title()
|
title = make_title()
|
||||||
runner = make_dl()
|
writer = make_writer(tmp_path, ProviderService())
|
||||||
runner.export_service = cast(Any, ProviderService())
|
|
||||||
|
|
||||||
runner.write_export(export, title, title.tracks.videos[0])
|
writer.record(title, title.tracks.videos[0])
|
||||||
|
export = written(writer)
|
||||||
|
|
||||||
movie = list(ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export)).get_titles())[0]
|
movie = list(ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export)).get_titles())[0]
|
||||||
assert (movie.metadata_provider, movie.anime) == ("tmdb", True)
|
assert (movie.metadata_provider, movie.anime) == ("tmdb", True)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("proxy_requested, region", [(True, "us"), (False, None)])
|
||||||
|
def test_the_region_is_recorded_only_for_a_proxy_run(tmp_path: Path, proxy_requested: bool, region: str | None) -> None:
|
||||||
|
writer = make_writer(tmp_path, SimpleNamespace(session=None, current_region="us"), proxy_requested)
|
||||||
|
title = make_title()
|
||||||
|
|
||||||
|
writer.record(title, title.tracks.videos[0])
|
||||||
|
|
||||||
|
assert read_export(written(writer)).get("region") == region
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_log_lines_read_the_named_file(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
|
writer = make_writer(tmp_path)
|
||||||
|
title = make_title()
|
||||||
|
with caplog.at_level(logging.INFO, logger="download"):
|
||||||
|
writer.log_summary()
|
||||||
|
writer.record(title, title.tracks.videos[0], StubDRM())
|
||||||
|
writer.log_title(title)
|
||||||
|
writer.log_summary()
|
||||||
|
|
||||||
|
assert caplog.messages[0] == "Nothing was exported"
|
||||||
|
assert f"Saved the export to {written(writer)}: 1 title, 1 key" in caplog.messages
|
||||||
|
assert "The export holds content keys: keep it private" in caplog.messages
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_title_with_no_record_logs_that_nothing_was_exported(
|
||||||
|
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
writer = make_writer(tmp_path)
|
||||||
|
first, second = make_title(), make_title()
|
||||||
|
second.id = "movie-2"
|
||||||
|
writer.record(first, first.tracks.videos[0])
|
||||||
|
with caplog.at_level(logging.WARNING, logger="download"):
|
||||||
|
writer.log_title(second)
|
||||||
|
|
||||||
|
assert caplog.messages == ["Exported nothing for 'Example Movie' (2024)"]
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ from uuid import UUID
|
|||||||
import mediaexport
|
import mediaexport
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
from tests.core.test_export import make_writer
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.export_name import ExportNamer, export_name, move_export, quality_parts, season_episodes
|
from unshackle.core.export_name import export_name, move_export, quality_parts, season_episodes
|
||||||
from unshackle.core.titles import Episode, Movie, Song
|
from unshackle.core.titles import Episode, Movie, Song
|
||||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||||
|
|
||||||
@@ -186,45 +186,36 @@ def test_collision_gets_a_suffix(tmp_path: Path) -> None:
|
|||||||
assert move_export(moved, "Example.Movie.2024-EXAMPLE") == moved
|
assert move_export(moved, "Example.Movie.2024-EXAMPLE") == moved
|
||||||
|
|
||||||
|
|
||||||
def make_dl(tmp_path: Path, seasons: dict[int, set[int]] | None = None) -> dl:
|
|
||||||
instance = dl.__new__(dl)
|
|
||||||
instance.service = "EXAMPLE"
|
|
||||||
instance.log = logging.getLogger("download")
|
|
||||||
instance.export_namer = ExportNamer("EXAMPLE", seasons or {})
|
|
||||||
return instance
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_is_renamed_as_titles_arrive_and_stays_valid(tmp_path: Path) -> None:
|
def test_export_is_renamed_as_titles_arrive_and_stays_valid(tmp_path: Path) -> None:
|
||||||
instance = make_dl(tmp_path, seasons_of((1, 2)))
|
writer = make_writer(tmp_path)
|
||||||
work = tmp_path / "export_EXAMPLE_1.json"
|
writer.namer.seasons = seasons_of((1, 2))
|
||||||
first, second = episode(1, 1), episode(1, 2)
|
first, second = episode(1, 1), episode(1, 2)
|
||||||
for title in (first, second):
|
for title in (first, second):
|
||||||
title.tracks.add(video(f"v{title.number}"))
|
title.tracks.add(video(f"v{title.number}"))
|
||||||
|
|
||||||
instance.write_export(work, first, first.tracks.videos[0], StubDRM())
|
writer.record(first, first.tracks.videos[0], StubDRM())
|
||||||
partial = tmp_path / "Example.Show.S01E01.1080p.h264.sdr.dash-EXAMPLE.json"
|
partial = tmp_path / "Example.Show.S01E01.1080p.h264.sdr.dash-EXAMPLE.json"
|
||||||
assert [p.name for p in tmp_path.iterdir()] == [partial.name]
|
assert [p.name for p in tmp_path.iterdir()] == [partial.name]
|
||||||
assert [e.id for e in mediaexport.read(partial).titles] == ["ep-1-1"]
|
assert [e.id for e in mediaexport.read(partial).titles] == ["ep-1-1"]
|
||||||
|
|
||||||
instance.write_export(work, second, second.tracks.videos[0])
|
writer.record(second, second.tracks.videos[0])
|
||||||
final = tmp_path / "Example.Show.S01.1080p.h264.sdr.dash-EXAMPLE.json"
|
final = tmp_path / "Example.Show.S01.1080p.h264.sdr.dash-EXAMPLE.json"
|
||||||
assert [p.name for p in tmp_path.iterdir()] == [final.name]
|
assert [p.name for p in tmp_path.iterdir()] == [final.name]
|
||||||
assert [e.id for e in mediaexport.read(final).titles] == ["ep-1-1", "ep-1-2"]
|
assert [e.id for e in mediaexport.read(final).titles] == ["ep-1-1", "ep-1-2"]
|
||||||
|
|
||||||
|
|
||||||
def test_export_messages(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
def test_export_messages(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
instance = make_dl(tmp_path)
|
writer = make_writer(tmp_path)
|
||||||
title = movie()
|
title = movie()
|
||||||
title.tracks.add(video())
|
title.tracks.add(video())
|
||||||
title.tracks.add(audio())
|
title.tracks.add(audio())
|
||||||
title.tracks.add(audio("a2"))
|
title.tracks.add(audio("a2"))
|
||||||
work = tmp_path / "export_EXAMPLE_1.json"
|
|
||||||
|
|
||||||
with caplog.at_level(logging.INFO, logger="download"):
|
with caplog.at_level(logging.INFO, logger="download"):
|
||||||
for track in title.tracks:
|
for track in title.tracks:
|
||||||
instance.write_export(work, title, track, StubDRM() if isinstance(track, Video) else None)
|
writer.record(title, track, StubDRM() if isinstance(track, Video) else None)
|
||||||
instance.log_export_title(title)
|
writer.log_title(title)
|
||||||
instance.log_export_summary()
|
writer.log_summary()
|
||||||
|
|
||||||
lines = [r.getMessage() for r in caplog.records]
|
lines = [r.getMessage() for r in caplog.records]
|
||||||
assert "Exporting to Example.Movie.2024.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json" in lines
|
assert "Exporting to Example.Movie.2024.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json" in lines
|
||||||
@@ -235,21 +226,21 @@ def test_export_messages(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> No
|
|||||||
|
|
||||||
|
|
||||||
def test_episode_message_names_the_episode(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
def test_episode_message_names_the_episode(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
instance = make_dl(tmp_path)
|
writer = make_writer(tmp_path)
|
||||||
title = episode(1, 5, "Example Episode")
|
title = episode(1, 5, "Example Episode")
|
||||||
title.tracks.add(video())
|
title.tracks.add(video())
|
||||||
instance.write_export(tmp_path / "export_EXAMPLE_1.json", title, title.tracks.videos[0])
|
writer.record(title, title.tracks.videos[0])
|
||||||
|
|
||||||
with caplog.at_level(logging.INFO, logger="download"):
|
with caplog.at_level(logging.INFO, logger="download"):
|
||||||
instance.log_export_title(title)
|
writer.log_title(title)
|
||||||
|
|
||||||
assert "Exported S01E05 'Example Episode': 1 video, 0 audio, 0 subtitles, 0 keys" in caplog.messages
|
assert "Exported S01E05 'Example Episode': 1 video, 0 audio, 0 subtitles, 0 keys" in caplog.messages
|
||||||
|
|
||||||
|
|
||||||
def test_summary_when_nothing_was_exported(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
def test_summary_when_nothing_was_exported(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
instance = make_dl(tmp_path)
|
writer = make_writer(tmp_path)
|
||||||
with caplog.at_level(logging.INFO, logger="download"):
|
with caplog.at_level(logging.INFO, logger="download"):
|
||||||
instance.log_export_summary()
|
writer.log_summary()
|
||||||
assert "Nothing was exported" in caplog.messages
|
assert "Nothing was exported" in caplog.messages
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ re-parse path and needs ``track.data["ism"]["segments"]`` restored, because
|
|||||||
restored, because ``HLS.download_track`` re-fetches the variant from ``track.url``. That makes
|
restored, because ``HLS.download_track`` re-fetches the variant from ``track.url``. That makes
|
||||||
the stored per-track URL load-bearing for HLS in a way it is not for ISM.
|
the stored per-track URL load-bearing for HLS in a way it is not for ISM.
|
||||||
|
|
||||||
These drive the real ``dl.write_export`` rather than hand-written export dicts, so a change to
|
These drive the real ``ExportWriter`` rather than hand-written export dicts, so a change to
|
||||||
the export format fails here instead of silently invalidating the fixtures.
|
the export format fails here instead of silently invalidating the fixtures.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ from types import SimpleNamespace
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
from tests.core.test_export import make_writer, written
|
||||||
from unshackle.core.import_service import ImportService
|
from unshackle.core.import_service import ImportService
|
||||||
from unshackle.core.manifests import HLS, ISM
|
from unshackle.core.manifests import HLS, ISM
|
||||||
|
|
||||||
@@ -63,12 +63,10 @@ def export_tracks(tmp_path: Path, tracks, manifest_url: str | None) -> Path:
|
|||||||
title.tracks.add(track)
|
title.tracks.add(track)
|
||||||
title.tracks.manifest_url = manifest_url
|
title.tracks.manifest_url = manifest_url
|
||||||
|
|
||||||
runner = dl.__new__(dl)
|
writer = make_writer(tmp_path)
|
||||||
runner.service = "EXAMPLE"
|
|
||||||
export = tmp_path / "export.json"
|
|
||||||
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
||||||
runner.write_export(export, title, track)
|
writer.record(title, track)
|
||||||
return export
|
return written(writer)
|
||||||
|
|
||||||
|
|
||||||
def import_tracks(export: Path):
|
def import_tracks(export: Path):
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ the fallback for a track that declares no KID.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
@@ -18,7 +17,7 @@ from uuid import UUID
|
|||||||
import click
|
import click
|
||||||
from pywidevine.pssh import PSSH
|
from pywidevine.pssh import PSSH
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
from tests.core.test_export import make_writer, written
|
||||||
from unshackle.core.drm import ClearKey, Widevine
|
from unshackle.core.drm import ClearKey, Widevine
|
||||||
from unshackle.core.drm.key_args import ZERO_KID
|
from unshackle.core.drm.key_args import ZERO_KID
|
||||||
from unshackle.core.import_service import ImportService
|
from unshackle.core.import_service import ImportService
|
||||||
@@ -85,13 +84,11 @@ def write_export(tmp_path: Path, kids: bool = True) -> Path:
|
|||||||
for track in DASH.from_text(MPD, MPD_URL).to_tracks(language="en"):
|
for track in DASH.from_text(MPD, MPD_URL).to_tracks(language="en"):
|
||||||
title.tracks.add(track)
|
title.tracks.add(track)
|
||||||
title.tracks.manifest_url = MPD_URL
|
title.tracks.manifest_url = MPD_URL
|
||||||
runner = dl.__new__(dl)
|
writer = make_writer(tmp_path)
|
||||||
runner.service = "EXAMPLE"
|
|
||||||
runner.log = logging.getLogger("download")
|
|
||||||
export = tmp_path / "export.json"
|
|
||||||
drm = {"video": widevine(VIDEO_KID, VIDEO_KEY), "en": widevine(AUDIO_KID, AUDIO_KEY)}
|
drm = {"video": widevine(VIDEO_KID, VIDEO_KEY), "en": widevine(AUDIO_KID, AUDIO_KEY)}
|
||||||
for track in [*title.tracks.videos, *title.tracks.audio]:
|
for track in [*title.tracks.videos, *title.tracks.audio]:
|
||||||
runner.write_export(export, title, track, drm.get(label(track)))
|
writer.record(title, track, drm.get(label(track)))
|
||||||
|
export = written(writer)
|
||||||
if not kids:
|
if not kids:
|
||||||
doc = json.loads(export.read_text(encoding="utf8"))
|
doc = json.loads(export.read_text(encoding="utf8"))
|
||||||
for row in doc["titles"][0]["tracks"]:
|
for row in doc["titles"][0]["tracks"]:
|
||||||
@@ -220,13 +217,11 @@ def hls_import(
|
|||||||
for track in HLS.from_text(HLS_MASTER, HLS_URL).to_tracks(language="en"):
|
for track in HLS.from_text(HLS_MASTER, HLS_URL).to_tracks(language="en"):
|
||||||
title.tracks.add(track)
|
title.tracks.add(track)
|
||||||
title.tracks.manifest_url = HLS_URL
|
title.tracks.manifest_url = HLS_URL
|
||||||
runner = dl.__new__(dl)
|
writer = make_writer(tmp_path)
|
||||||
runner.service = "EXAMPLE"
|
|
||||||
runner.log = logging.getLogger("download")
|
|
||||||
export = tmp_path / "export.json"
|
|
||||||
drm = {"video": widevine(VIDEO_KID, VIDEO_KEY), "en": audio_drm, "es": subtitle_drm}
|
drm = {"video": widevine(VIDEO_KID, VIDEO_KEY), "en": audio_drm, "es": subtitle_drm}
|
||||||
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
for track in [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]:
|
||||||
runner.write_export(export, title, track, drm.get(label(track)))
|
writer.record(title, track, drm.get(label(track)))
|
||||||
|
export = written(writer)
|
||||||
if not kids:
|
if not kids:
|
||||||
doc = json.loads(export.read_text(encoding="utf8"))
|
doc = json.loads(export.read_text(encoding="utf8"))
|
||||||
for row in doc["titles"][0]["tracks"]:
|
for row in doc["titles"][0]["tracks"]:
|
||||||
|
|||||||
@@ -79,17 +79,16 @@ def detach_video(tracks: Tracks, track_id: str | None = None) -> Track:
|
|||||||
|
|
||||||
|
|
||||||
def export_and_import(tmp_path: Any, tracks: Tracks) -> Tracks:
|
def export_and_import(tmp_path: Any, tracks: Tracks) -> Tracks:
|
||||||
from tests.core.test_export import StubService, import_ctx, make_dl
|
from tests.core.test_export import StubService, import_ctx, make_writer, written
|
||||||
from unshackle.core.import_service import ImportService
|
from unshackle.core.import_service import ImportService
|
||||||
from unshackle.core.titles import Movie
|
from unshackle.core.titles import Movie
|
||||||
|
|
||||||
export = tmp_path / "export.json"
|
writer = make_writer(tmp_path)
|
||||||
title = Movie(id_="movie-1", service=StubService, name="Example Movie", year=2024, language="en")
|
title = Movie(id_="movie-1", service=StubService, name="Example Movie", year=2024, language="en")
|
||||||
title.tracks = tracks
|
title.tracks = tracks
|
||||||
runner = make_dl()
|
|
||||||
for track in title.tracks:
|
for track in title.tracks:
|
||||||
runner.write_export(export, title, track)
|
writer.record(title, track)
|
||||||
service = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
service = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(written(writer)))
|
||||||
return service.get_tracks(next(iter(service.get_titles())))
|
return service.get_tracks(next(iter(service.get_titles())))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import pytest
|
|||||||
from pywidevine.pssh import PSSH as WidevinePSSH
|
from pywidevine.pssh import PSSH as WidevinePSSH
|
||||||
|
|
||||||
from tests.core.test_zero_kid_fallback import _playready_pssh
|
from tests.core.test_zero_kid_fallback import _playready_pssh
|
||||||
from unshackle.commands.dl import dl
|
|
||||||
from unshackle.core import wire
|
from unshackle.core import wire
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
|
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
|
||||||
@@ -715,13 +714,13 @@ def test_rest_title_key_order_is_stable() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_export_episode_meta() -> None:
|
def test_export_episode_meta() -> None:
|
||||||
meta = dl.title_to_meta(full_episode())
|
meta = title_to_meta(full_episode())
|
||||||
assert meta == META_EPISODE
|
assert meta == META_EPISODE
|
||||||
assert list(meta) == list(META_EPISODE)
|
assert list(meta) == list(META_EPISODE)
|
||||||
|
|
||||||
|
|
||||||
def test_export_movie_meta() -> None:
|
def test_export_movie_meta() -> None:
|
||||||
assert dl.title_to_meta(movie()) == {
|
assert title_to_meta(movie()) == {
|
||||||
"id": "movie-0001",
|
"id": "movie-0001",
|
||||||
"language": "fr",
|
"language": "fr",
|
||||||
"type": "movie",
|
"type": "movie",
|
||||||
@@ -731,7 +730,7 @@ def test_export_movie_meta() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_export_meta_of_another_title_is_a_movie_named_by_str() -> None:
|
def test_export_meta_of_another_title_is_a_movie_named_by_str() -> None:
|
||||||
assert dl.title_to_meta(song()) == {
|
assert title_to_meta(song()) == {
|
||||||
"id": "song-0001",
|
"id": "song-0001",
|
||||||
"language": "en",
|
"language": "en",
|
||||||
"type": "movie",
|
"type": "movie",
|
||||||
|
|||||||
@@ -14,13 +14,12 @@ from typing import Any
|
|||||||
import pytest
|
import pytest
|
||||||
from langcodes import Language
|
from langcodes import Language
|
||||||
|
|
||||||
from unshackle.commands.dl import dl
|
|
||||||
from unshackle.core.api import handlers
|
from unshackle.core.api import handlers
|
||||||
from unshackle.core.titles.episode import Episode
|
from unshackle.core.titles.episode import Episode
|
||||||
from unshackle.core.titles.movie import Movie
|
from unshackle.core.titles.movie import Movie
|
||||||
from unshackle.core.titles.music import Song
|
from unshackle.core.titles.music import Song
|
||||||
from unshackle.core.tracks import Tracks
|
from unshackle.core.tracks import Tracks
|
||||||
from unshackle.core.wire import build_title, serialize_title
|
from unshackle.core.wire import build_title, serialize_title, title_to_meta
|
||||||
|
|
||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
@@ -142,7 +141,7 @@ def test_the_metadata_provider_survives_the_round_trip() -> None:
|
|||||||
def test_title_to_meta_round_trip_keeps_the_metadata_provider() -> None:
|
def test_title_to_meta_round_trip_keeps_the_metadata_provider() -> None:
|
||||||
movie = _movie()
|
movie = _movie()
|
||||||
movie.metadata_provider = "tmdb"
|
movie.metadata_provider = "tmdb"
|
||||||
assert build_title(dl.title_to_meta(movie), "FAKE", "fallback-id").metadata_provider == "tmdb"
|
assert build_title(title_to_meta(movie), "FAKE", "fallback-id").metadata_provider == "tmdb"
|
||||||
|
|
||||||
|
|
||||||
def test_a_movie_is_never_stamped_daily() -> None:
|
def test_a_movie_is_never_stamped_daily() -> None:
|
||||||
@@ -228,7 +227,7 @@ def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_title_to_meta_omits_the_new_keys_for_a_plain_episode() -> None:
|
def test_title_to_meta_omits_the_new_keys_for_a_plain_episode() -> None:
|
||||||
meta = dl.title_to_meta(ep())
|
meta = title_to_meta(ep())
|
||||||
assert not [k for k in ("absolute", "daily", "anime") if k in meta]
|
assert not [k for k in ("absolute", "daily", "anime") if k in meta]
|
||||||
|
|
||||||
|
|
||||||
@@ -236,14 +235,14 @@ def test_title_to_meta_round_trip_keeps_the_new_fields() -> None:
|
|||||||
episode = ep(air_date=date(2026, 8, 11), absolute=57)
|
episode = ep(air_date=date(2026, 8, 11), absolute=57)
|
||||||
episode.daily = True
|
episode.daily = True
|
||||||
episode.anime = True
|
episode.anime = True
|
||||||
rebuilt = build_title(dl.title_to_meta(episode), "FAKE", "fallback-id")
|
rebuilt = build_title(title_to_meta(episode), "FAKE", "fallback-id")
|
||||||
assert rebuilt.air_date == date(2026, 8, 11)
|
assert rebuilt.air_date == date(2026, 8, 11)
|
||||||
assert rebuilt.absolute == 57
|
assert rebuilt.absolute == 57
|
||||||
assert (rebuilt.daily, rebuilt.anime) == (True, True)
|
assert (rebuilt.daily, rebuilt.anime) == (True, True)
|
||||||
|
|
||||||
|
|
||||||
def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
|
def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
|
||||||
rebuilt = build_title(dl.title_to_meta(ep()), "FAKE", "fallback-id")
|
rebuilt = build_title(title_to_meta(ep()), "FAKE", "fallback-id")
|
||||||
assert rebuilt.absolute is None
|
assert rebuilt.absolute is None
|
||||||
assert (rebuilt.daily, rebuilt.anime) == (None, None)
|
assert (rebuilt.daily, rebuilt.anime) == (None, None)
|
||||||
|
|
||||||
@@ -251,7 +250,7 @@ def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
|
|||||||
def test_title_to_meta_round_trip_keeps_the_movie_anime_flag() -> None:
|
def test_title_to_meta_round_trip_keeps_the_movie_anime_flag() -> None:
|
||||||
movie = _movie()
|
movie = _movie()
|
||||||
movie.anime = True
|
movie.anime = True
|
||||||
rebuilt = build_title(dl.title_to_meta(movie), "FAKE", "fallback-id")
|
rebuilt = build_title(title_to_meta(movie), "FAKE", "fallback-id")
|
||||||
assert rebuilt.anime is True
|
assert rebuilt.anime is True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+32
-292
@@ -17,7 +17,6 @@ from threading import Lock
|
|||||||
from typing import TYPE_CHECKING, Any, TypedDict
|
from typing import TYPE_CHECKING, Any, TypedDict
|
||||||
|
|
||||||
import click
|
import click
|
||||||
import mediaexport
|
|
||||||
from click.core import ParameterSource
|
from click.core import ParameterSource
|
||||||
from langcodes import Language
|
from langcodes import Language
|
||||||
from pymediainfo import MediaInfo
|
from pymediainfo import MediaInfo
|
||||||
@@ -28,7 +27,7 @@ from rich.rule import Rule
|
|||||||
from rich.spinner import Spinner
|
from rich.spinner import Spinner
|
||||||
from rich.table import Table
|
from rich.table import Table
|
||||||
|
|
||||||
from unshackle.core import __version__, binaries, login
|
from unshackle.core import binaries, login
|
||||||
from unshackle.core.cdm.choice import choose_cdm
|
from unshackle.core.cdm.choice import choose_cdm
|
||||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
|
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
|
||||||
from unshackle.core.config import (
|
from unshackle.core.config import (
|
||||||
@@ -58,15 +57,14 @@ from unshackle.core.downloaders import (
|
|||||||
from unshackle.core.drm import (
|
from unshackle.core.drm import (
|
||||||
WHOLE_FILE_DRM,
|
WHOLE_FILE_DRM,
|
||||||
MonaLisa,
|
MonaLisa,
|
||||||
own_kids,
|
|
||||||
verify,
|
verify,
|
||||||
)
|
)
|
||||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||||
from unshackle.core.drm.verify import has_encrypted_sample_entry
|
from unshackle.core.drm.verify import has_encrypted_sample_entry
|
||||||
from unshackle.core.events import events
|
from unshackle.core.events import events
|
||||||
from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label
|
from unshackle.core.export_name import season_episodes
|
||||||
|
from unshackle.core.export_writer import ExportWriter
|
||||||
from unshackle.core.launch import LaunchKeys, launch, load_service_config
|
from unshackle.core.launch import LaunchKeys, launch, load_service_config
|
||||||
from unshackle.core.manifests.snapshot import capture
|
|
||||||
from unshackle.core.mux_step import mux_title
|
from unshackle.core.mux_step import mux_title
|
||||||
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name
|
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name
|
||||||
from unshackle.core.providers.tvdb import SEASON_TYPES
|
from unshackle.core.providers.tvdb import SEASON_TYPES
|
||||||
@@ -1151,11 +1149,9 @@ class dl:
|
|||||||
def cli(ctx: click.Context, **kwargs: Any) -> dl:
|
def cli(ctx: click.Context, **kwargs: Any) -> dl:
|
||||||
return dl(ctx, **kwargs)
|
return dl(ctx, **kwargs)
|
||||||
|
|
||||||
EXPORT_LOCK = Lock()
|
|
||||||
export_snapshots: dict[str, dict[str, Any] | None]
|
|
||||||
keys: ContentKeyResolver
|
keys: ContentKeyResolver
|
||||||
|
export: ExportWriter | None = None
|
||||||
_remote_service: ServerKeySource | None = None
|
_remote_service: ServerKeySource | None = None
|
||||||
export_service: TitleSource | None = None
|
|
||||||
typed_params: frozenset[str] = frozenset()
|
typed_params: frozenset[str] = frozenset()
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -1611,11 +1607,12 @@ class dl:
|
|||||||
if export:
|
if export:
|
||||||
config.directories.exports.mkdir(parents=True, exist_ok=True)
|
config.directories.exports.mkdir(parents=True, exist_ok=True)
|
||||||
# a working name until the first write, which renames it after what it holds
|
# a working name until the first write, which renames it after what it holds
|
||||||
export_path = config.directories.exports / f"export_{self.service}_{int(time.time())}.json"
|
self.export = ExportWriter(
|
||||||
self.export_service = service
|
config.directories.exports / f"export_{self.service}_{int(time.time())}.json",
|
||||||
self.export_namer = ExportNamer(self.service)
|
self.service,
|
||||||
else:
|
service,
|
||||||
export_path = None
|
proxy_requested=self.proxy_requested,
|
||||||
|
)
|
||||||
|
|
||||||
vbitrate_min, vbitrate_max = bitrate_range(vbitrate_range, "--vbitrate-range", "6000-7000") or (None, None)
|
vbitrate_min, vbitrate_max = bitrate_range(vbitrate_range, "--vbitrate-range", "6000-7000") or (None, None)
|
||||||
abitrate_min, abitrate_max = bitrate_range(abitrate_range, "--abitrate-range", "128-256") or (None, None)
|
abitrate_min, abitrate_max = bitrate_range(abitrate_range, "--abitrate-range", "128-256") or (None, None)
|
||||||
@@ -1653,7 +1650,7 @@ class dl:
|
|||||||
cdm_only=bool(cdm_only),
|
cdm_only=bool(cdm_only),
|
||||||
vaults_only=bool(vaults_only),
|
vaults_only=bool(vaults_only),
|
||||||
best_available=bool(best_available),
|
best_available=bool(best_available),
|
||||||
export=export_path,
|
export=self.export,
|
||||||
)
|
)
|
||||||
|
|
||||||
config.decryption = resolve_decryption(
|
config.decryption = resolve_decryption(
|
||||||
@@ -1754,9 +1751,9 @@ class dl:
|
|||||||
if list_titles:
|
if list_titles:
|
||||||
return self.outcome()
|
return self.outcome()
|
||||||
|
|
||||||
if export_path and isinstance(titles, Series):
|
if self.export and isinstance(titles, Series):
|
||||||
# before --select-titles and -w drop titles, so a whole season can be told from part of one
|
# before --select-titles and -w drop titles, so a whole season can be told from part of one
|
||||||
self.export_namer.seasons = season_episodes(titles)
|
self.export.namer.seasons = season_episodes(titles)
|
||||||
|
|
||||||
if select_titles and isinstance(titles, Movies) and len(titles) > 1:
|
if select_titles and isinstance(titles, Movies) and len(titles) > 1:
|
||||||
console.print(Padding(Rule("[rule.text]Select Titles"), (1, 2)))
|
console.print(Padding(Rule("[rule.text]Select Titles"), (1, 2)))
|
||||||
@@ -2245,9 +2242,9 @@ class dl:
|
|||||||
)
|
)
|
||||||
# DRM-free and HLS-ClearKey tracks never reach prepare_drm, so export here.
|
# DRM-free and HLS-ClearKey tracks never reach prepare_drm, so export here.
|
||||||
# drm=None on purpose: licensed tracks already recorded their DRM/keys
|
# drm=None on purpose: licensed tracks already recorded their DRM/keys
|
||||||
# in prepare_drm, and write_export merges via setdefault.
|
# in prepare_drm, and record merges via setdefault.
|
||||||
if export_path:
|
if self.export:
|
||||||
self.write_export(export_path, title, track)
|
self.export.record(title, track)
|
||||||
|
|
||||||
def on_subtitle_skipped(track: Subtitle, *, title: Title_T) -> None:
|
def on_subtitle_skipped(track: Subtitle, *, title: Title_T) -> None:
|
||||||
lang = str(track.language)
|
lang = str(track.language)
|
||||||
@@ -2302,8 +2299,8 @@ class dl:
|
|||||||
context={"title": str(title)},
|
context={"title": str(title)},
|
||||||
)
|
)
|
||||||
self.keys.wait_vault_writes()
|
self.keys.wait_vault_writes()
|
||||||
if export_path:
|
if self.export:
|
||||||
self.log_export_summary()
|
self.export.log_summary()
|
||||||
return self.outcome()
|
return self.outcome()
|
||||||
except Exception as e: # noqa
|
except Exception as e: # noqa
|
||||||
# Reported and swallowed (no re-raise) so the CLI exits cleanly; keep it so the
|
# Reported and swallowed (no re-raise) so the CLI exits cleanly; keep it so the
|
||||||
@@ -2338,13 +2335,13 @@ class dl:
|
|||||||
postscript,
|
postscript,
|
||||||
)
|
)
|
||||||
self.keys.wait_vault_writes()
|
self.keys.wait_vault_writes()
|
||||||
if export_path:
|
if self.export:
|
||||||
self.log_export_summary()
|
self.export.log_summary()
|
||||||
return self.outcome()
|
return self.outcome()
|
||||||
|
|
||||||
self.keys.wait_vault_writes()
|
self.keys.wait_vault_writes()
|
||||||
if export_path:
|
if self.export:
|
||||||
self.log_export_title(title)
|
self.export.log_title(title)
|
||||||
|
|
||||||
if skip_dl:
|
if skip_dl:
|
||||||
console.log("Skipped downloads as --skip-dl was used...")
|
console.log("Skipped downloads as --skip-dl was used...")
|
||||||
@@ -2661,8 +2658,8 @@ class dl:
|
|||||||
run_context["folder"] = str(folder)
|
run_context["folder"] = str(folder)
|
||||||
dispatch("success", "run", run_context, postscript)
|
dispatch("success", "run", run_context, postscript)
|
||||||
|
|
||||||
if export_path:
|
if self.export:
|
||||||
self.log_export_summary()
|
self.export.log_summary()
|
||||||
if self.skipped_titles:
|
if self.skipped_titles:
|
||||||
if len(self.skipped_titles) == wanted_total:
|
if len(self.skipped_titles) == wanted_total:
|
||||||
stop = f"Skipped all {wanted_total} titles"
|
stop = f"Skipped all {wanted_total} titles"
|
||||||
@@ -2706,269 +2703,6 @@ class dl:
|
|||||||
if returncode > 1 or not output.exists():
|
if returncode > 1 or not output.exists():
|
||||||
self.log.warning(f"mkvmerge wrote no sample for {source.name}")
|
self.log.warning(f"mkvmerge wrote no sample for {source.name}")
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def title_to_meta(title: Title_T) -> dict[str, Any]:
|
|
||||||
"""Capture the title fields needed to rebuild a Title for output naming on import."""
|
|
||||||
from unshackle.core import wire
|
|
||||||
|
|
||||||
return wire.title_to_meta(title)
|
|
||||||
|
|
||||||
def write_export(self, export: Path, title: Title_T, track: AnyTrack, drm: Any = None) -> None:
|
|
||||||
"""Write a shareable mediaexport file usable by ``unshackle import`` and unidl.
|
|
||||||
|
|
||||||
Carries no HTTP session or cookies. The export records the region (country code)
|
|
||||||
only when the export used ``--proxy``, as an import geofence. DRM init data and
|
|
||||||
content keys live once per title. ``drm`` may be None (DRM-free track) or a DRM
|
|
||||||
system without ``to_dict``/``content_keys`` (e.g. ClearKey) - the export still
|
|
||||||
records the track, manifest, chapter and attachment info. unshackle's full track
|
|
||||||
dicts, title meta and manifest snapshot go under ``x-unshackle`` for its own importer.
|
|
||||||
"""
|
|
||||||
namer: ExportNamer | None = getattr(self, "export_namer", None)
|
|
||||||
snapshots = getattr(self, "export_snapshots", None)
|
|
||||||
if snapshots is None:
|
|
||||||
snapshots = self.export_snapshots = {}
|
|
||||||
if str(title.id) not in snapshots:
|
|
||||||
try:
|
|
||||||
fresh = capture(title.tracks)
|
|
||||||
snapshots[str(title.id)] = fresh if any(fresh.values()) else None
|
|
||||||
except Exception as e:
|
|
||||||
self.log.warning(f"Not saving the manifest of {title.id} in {export}: {e!r}")
|
|
||||||
snapshots[str(title.id)] = None
|
|
||||||
with self.EXPORT_LOCK:
|
|
||||||
if namer and namer.path:
|
|
||||||
export = namer.path
|
|
||||||
try:
|
|
||||||
doc = mediaexport.read(export) if export.is_file() else mediaexport.Document(service_tag=self.service)
|
|
||||||
except mediaexport.ExportError as e:
|
|
||||||
# a download mid-licensing must not die over the file it exports to
|
|
||||||
self.log.warning(f"Not exporting {title.id}: {export} is not a usable export ({e})")
|
|
||||||
return
|
|
||||||
doc.generator.setdefault("app", "unshackle")
|
|
||||||
doc.generator.setdefault("version", __version__)
|
|
||||||
if not doc.region and getattr(self, "proxy_requested", False):
|
|
||||||
doc.region = (self.export_service and self.export_service.current_region) or ""
|
|
||||||
|
|
||||||
entry = doc.get(str(title.id))
|
|
||||||
if entry is None:
|
|
||||||
entry = self.export_entry(title)
|
|
||||||
doc.add(entry)
|
|
||||||
|
|
||||||
tracks_map = entry.ext("unshackle").setdefault("tracks", {})
|
|
||||||
track_dict = tracks_map.setdefault(str(track.id), track.to_dict())
|
|
||||||
unwanted = (track.data.get("hls") or {}).get("unwanted_segments")
|
|
||||||
if unwanted:
|
|
||||||
track_dict["unwanted_segments"] = unwanted
|
|
||||||
elif unwanted is not None:
|
|
||||||
track_dict.pop("unwanted_segments", None)
|
|
||||||
if saved := snapshots[str(title.id)]:
|
|
||||||
entry.ext("unshackle")["snapshot"] = saved
|
|
||||||
# the row names the track's KIDs, so an import gives the track only their keys
|
|
||||||
track_kids = [kid.hex for kid in own_kids(drm)] if drm is not None else []
|
|
||||||
for row in entry.tracks:
|
|
||||||
if row.get("id") == str(track.id):
|
|
||||||
row["selected"] = True
|
|
||||||
if track_kids:
|
|
||||||
row["kids"] = list(dict.fromkeys([*(row.get("kids") or []), *track_kids]))
|
|
||||||
|
|
||||||
if drm is not None:
|
|
||||||
if hasattr(drm, "to_dict"):
|
|
||||||
d = drm.to_dict()
|
|
||||||
own = entry.ext("unshackle").setdefault("drm", [])
|
|
||||||
if d not in own:
|
|
||||||
own.append(d)
|
|
||||||
system = str(d.get("system", "")).lower().replace("cenc", "")
|
|
||||||
pssh = str(d.get("pssh_b64") or "")
|
|
||||||
if system and all(x.pssh != pssh or x.system != system for x in entry.drm):
|
|
||||||
entry.drm.append(mediaexport.Drm(system, pssh))
|
|
||||||
content_keys = getattr(drm, "content_keys", None) or {}
|
|
||||||
pool = doc.key_pool()
|
|
||||||
for kid, key in content_keys.items():
|
|
||||||
# a KID that already holds a different key must not be overwritten:
|
|
||||||
# the reader rejects a file that disagrees with itself
|
|
||||||
if pool.setdefault(kid.hex, key.lower()) != key.lower():
|
|
||||||
self.log.warning(
|
|
||||||
f"KID {kid.hex} already has a different key in {export}, keeping the existing one"
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
entry.add_key(kid.hex, key)
|
|
||||||
except mediaexport.ExportError as e:
|
|
||||||
# a key the format cannot hold (not 16 bytes of hex) costs the export that key,
|
|
||||||
# never the download
|
|
||||||
self.log.warning(f"Not exporting the key for KID {kid.hex}: {e}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
mediaexport.write(export, doc)
|
|
||||||
except (mediaexport.ExportError, OSError) as e:
|
|
||||||
self.log.warning(f"Could not write export {export}: {e}")
|
|
||||||
return
|
|
||||||
if namer:
|
|
||||||
self.rename_export(namer, export, title, track)
|
|
||||||
|
|
||||||
def rename_export(self, namer: ExportNamer, export: Path, title: Title_T, track: AnyTrack) -> None:
|
|
||||||
"""Give the run's export a name that tells what it holds, after each write to it.
|
|
||||||
|
|
||||||
The file on disk is complete after each write, so a run that stops early still leaves
|
|
||||||
a usable file with a name that matches what it holds.
|
|
||||||
"""
|
|
||||||
first = namer.path is None
|
|
||||||
namer.add(title, track)
|
|
||||||
try:
|
|
||||||
namer.path = move_export(export, namer.name())
|
|
||||||
except OSError as e:
|
|
||||||
self.log.warning(f"Could not rename export {export}: {e}")
|
|
||||||
namer.path = export
|
|
||||||
if first:
|
|
||||||
self.log.info(f"Exporting to {namer.path.name}")
|
|
||||||
elif namer.path != export:
|
|
||||||
self.log.debug(f"Renamed the export to {namer.path.name}")
|
|
||||||
|
|
||||||
def log_export_title(self, title: Title_T) -> None:
|
|
||||||
"""Log what the export holds for one title: its track counts and its keys."""
|
|
||||||
namer: ExportNamer | None = getattr(self, "export_namer", None)
|
|
||||||
entry = None
|
|
||||||
if namer and namer.path:
|
|
||||||
try:
|
|
||||||
entry = mediaexport.read(namer.path).get(str(title.id))
|
|
||||||
except (mediaexport.ExportError, OSError) as e:
|
|
||||||
self.log.warning(f"Could not read export {namer.path}: {e}")
|
|
||||||
return
|
|
||||||
if entry is None:
|
|
||||||
self.log.warning(f"Exported nothing for {title_label(title)}")
|
|
||||||
return
|
|
||||||
selected = [r.get("type") for r in entry.tracks if r.get("selected")]
|
|
||||||
self.log.info(
|
|
||||||
f"Exported {title_label(title)}: {selected.count('video')} video, {selected.count('audio')} audio, "
|
|
||||||
f"{plural(selected.count('subtitle'), 'subtitle')}, {plural(len(entry.keys), 'key')}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def log_export_summary(self) -> None:
|
|
||||||
"""Log where the run's export is and what it holds, and that it must stay private."""
|
|
||||||
namer: ExportNamer | None = getattr(self, "export_namer", None)
|
|
||||||
if not namer or not namer.path:
|
|
||||||
self.log.warning("Nothing was exported")
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
doc = mediaexport.read(namer.path)
|
|
||||||
except (mediaexport.ExportError, OSError) as e:
|
|
||||||
self.log.warning(f"Could not read export {namer.path}: {e}")
|
|
||||||
return
|
|
||||||
keys = len(doc.key_pool())
|
|
||||||
self.log.info(f"Saved the export to {namer.path}: {plural(len(doc.titles), 'title')}, {plural(keys, 'key')}")
|
|
||||||
if keys:
|
|
||||||
self.log.warning("The export holds content keys: keep it private")
|
|
||||||
|
|
||||||
def export_entry(self, title: Title_T) -> mediaexport.Entry:
|
|
||||||
"""A mediaexport entry for ``title``: manifests, chapters, a small track list, no keys yet."""
|
|
||||||
from unshackle.core import wire
|
|
||||||
|
|
||||||
meta = wire.stamp_service_flags(self.title_to_meta(title), self.export_service)
|
|
||||||
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
|
|
||||||
primary_url = title.tracks.manifest_url or next(
|
|
||||||
(str(t.url) for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
|
||||||
)
|
|
||||||
manifest_type = next(
|
|
||||||
(t.descriptor.name.lower() for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
|
||||||
)
|
|
||||||
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 = (
|
|
||||||
[
|
|
||||||
mediaexport.Manifest(
|
|
||||||
primary_url,
|
|
||||||
manifest_type,
|
|
||||||
headers,
|
|
||||||
role="primary",
|
|
||||||
content_periods=self.content_periods(all_tracks, primary_url),
|
|
||||||
)
|
|
||||||
]
|
|
||||||
if primary_url
|
|
||||||
else []
|
|
||||||
)
|
|
||||||
# the whole URL identifies a manifest: two profiles on one endpoint are two manifests
|
|
||||||
seen = {primary_url}
|
|
||||||
for t in all_tracks:
|
|
||||||
url = str(t.url)
|
|
||||||
if t.descriptor in (Video.Descriptor.DASH, Video.Descriptor.ISM) and url not in seen:
|
|
||||||
seen.add(url)
|
|
||||||
manifests.append(
|
|
||||||
mediaexport.Manifest(
|
|
||||||
url,
|
|
||||||
t.descriptor.name.lower(),
|
|
||||||
role="extra",
|
|
||||||
content_periods=self.content_periods(all_tracks, url),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for t in all_tracks:
|
|
||||||
codec = getattr(t, "codec", None)
|
|
||||||
row: dict[str, Any] = {
|
|
||||||
"id": str(t.id),
|
|
||||||
"type": t.__class__.__name__.lower(),
|
|
||||||
# a subtitle side-load names its file format so another tool can fetch it
|
|
||||||
"codec": (codec.value if isinstance(t, Subtitle) else codec.name).lower() if codec else "",
|
|
||||||
"language": str(t.language) if t.language else "",
|
|
||||||
"bitrate": int(bitrate) if (bitrate := getattr(t, "bitrate", None)) else None,
|
|
||||||
}
|
|
||||||
if isinstance(t, Video):
|
|
||||||
row.update(width=t.width, height=t.height, range=t.range.name.lower() if t.range else "")
|
|
||||||
if t.stereo:
|
|
||||||
row["stereo"] = True
|
|
||||||
elif isinstance(t, Audio):
|
|
||||||
row.update(channels=str(t.channels) if t.channels else "", atmos=bool(t.joc), descriptive=t.descriptive)
|
|
||||||
elif isinstance(t, Subtitle):
|
|
||||||
row.update(sdh=t.sdh, forced=t.forced, cc=t.cc)
|
|
||||||
if t.descriptor == Video.Descriptor.URL:
|
|
||||||
row["url"] = str(t.url)
|
|
||||||
rows.append({k: v for k, v in row.items() if v not in (None, "")})
|
|
||||||
|
|
||||||
return mediaexport.Entry(
|
|
||||||
id=str(title.id),
|
|
||||||
kind=meta.get("type", "movie"),
|
|
||||||
title=meta.get("name") or "",
|
|
||||||
series=meta.get("series_title") or "",
|
|
||||||
season=meta.get("season"),
|
|
||||||
episode=meta.get("number"),
|
|
||||||
year=meta.get("year"),
|
|
||||||
language=meta.get("language") or "",
|
|
||||||
artist=meta.get("artist") or "",
|
|
||||||
album=meta.get("album") or "",
|
|
||||||
track_number=meta.get("track"),
|
|
||||||
manifests=manifests,
|
|
||||||
chapters=[
|
|
||||||
{"start_ms": mediaexport.ts_ms(c.timestamp), "title": c.name or ""}
|
|
||||||
for c in (title.tracks.chapters or [])
|
|
||||||
],
|
|
||||||
tracks=rows,
|
|
||||||
extensions={
|
|
||||||
"x-unshackle": {
|
|
||||||
"meta": meta,
|
|
||||||
"tracks": {},
|
|
||||||
"attachments": [a.to_dict() for a in (title.tracks.attachments or []) if a.url],
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def content_periods(tracks: Sequence[Track], url: str) -> list[str]:
|
|
||||||
"""The ids of the DASH periods a service kept in the manifest at ``url``, empty when it filtered none.
|
|
||||||
|
|
||||||
An import re-fetches the manifest without the service, so its period filter must travel in the export.
|
|
||||||
Empty also when a kept period has no id, since an id allow-list cannot name it.
|
|
||||||
"""
|
|
||||||
dash = next(
|
|
||||||
(d for t in tracks if (d := t.data.get("dash") or {}).get("filtered_period_ids") and str(t.url) == url),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
if dash is None:
|
|
||||||
return []
|
|
||||||
kept = [
|
|
||||||
p.get("id") for p in dash["manifest"].findall("Period") if p.get("id") not in dash["filtered_period_ids"]
|
|
||||||
]
|
|
||||||
return kept if all(kept) else []
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def failure_lines(e: BaseException) -> list[str]:
|
def failure_lines(e: BaseException) -> list[str]:
|
||||||
"""Return the header and the one line that report a failed download.
|
"""Return the header and the one line that report a failed download.
|
||||||
@@ -2988,7 +2722,13 @@ class dl:
|
|||||||
return [":x: Download Failed...", f" {line}"]
|
return [":x: Download Failed...", f" {line}"]
|
||||||
|
|
||||||
def start_key_resolution(
|
def start_key_resolution(
|
||||||
self, service: TitleSource, *, 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: ExportWriter | None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Build the run's content-key resolution and make its verified decrypt the decrypt hook."""
|
"""Build the run's content-key resolution and make its verified decrypt the decrypt hook."""
|
||||||
self.keys = ContentKeyResolver(
|
self.keys = ContentKeyResolver(
|
||||||
@@ -3000,7 +2740,7 @@ class dl:
|
|||||||
cdm_only=cdm_only,
|
cdm_only=cdm_only,
|
||||||
vaults_only=vaults_only,
|
vaults_only=vaults_only,
|
||||||
best_available=best_available,
|
best_available=best_available,
|
||||||
export=partial(self.write_export, export) if export else None,
|
export=export.record if export else None,
|
||||||
debug_logger=self.debug_logger,
|
debug_logger=self.debug_logger,
|
||||||
)
|
)
|
||||||
verify.DECRYPT_HOOK = self.keys.decrypt_verified
|
verify.DECRYPT_HOOK = self.keys.decrypt_verified
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
"""The writer of one ``dl --export`` run: the mediaexport file that ``unshackle import`` and unidl read."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Lock
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
import mediaexport
|
||||||
|
|
||||||
|
from unshackle.core import __version__, wire
|
||||||
|
from unshackle.core.constants import AnyTrack
|
||||||
|
from unshackle.core.drm import own_kids
|
||||||
|
from unshackle.core.export_name import ExportNamer, move_export, plural, title_label
|
||||||
|
from unshackle.core.manifests.snapshot import capture
|
||||||
|
from unshackle.core.titles import Title_T
|
||||||
|
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||||
|
from unshackle.core.tracks.track import Track
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from unshackle.core.title_source import TitleSource
|
||||||
|
|
||||||
|
|
||||||
|
class ExportWriter:
|
||||||
|
"""Writes the titles, tracks, DRM and keys of one run into its export file, and names the file after them.
|
||||||
|
|
||||||
|
Every failure of the export is a warning: a download never stops over its export.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, path: Path, service_tag: str, source: TitleSource, proxy_requested: bool) -> None:
|
||||||
|
self.path = path
|
||||||
|
self.source = source
|
||||||
|
self.proxy_requested = proxy_requested
|
||||||
|
self.namer = ExportNamer(service_tag)
|
||||||
|
self.snapshots: dict[str, dict[str, Any] | None] = {}
|
||||||
|
self.lock = Lock()
|
||||||
|
self.log = logging.getLogger("download")
|
||||||
|
|
||||||
|
def record(self, title: Title_T, track: AnyTrack, drm: Any = None) -> None:
|
||||||
|
"""Write ``track`` of ``title``, with the DRM and keys of ``drm``, into the export file.
|
||||||
|
|
||||||
|
Carries no HTTP session or cookies. The export records the region (country code)
|
||||||
|
only when the run used ``--proxy``, as an import geofence. DRM init data and
|
||||||
|
content keys live once per title. ``drm`` may be None (DRM-free track) or a DRM
|
||||||
|
system without ``to_dict``/``content_keys`` (e.g. ClearKey) - the export still
|
||||||
|
records the track, manifest, chapter and attachment info. unshackle's full track
|
||||||
|
dicts, title meta and manifest snapshot go under ``x-unshackle`` for its own importer.
|
||||||
|
"""
|
||||||
|
if str(title.id) not in self.snapshots:
|
||||||
|
try:
|
||||||
|
fresh = capture(title.tracks)
|
||||||
|
self.snapshots[str(title.id)] = fresh if any(fresh.values()) else None
|
||||||
|
except Exception as e:
|
||||||
|
self.log.warning(f"Not saving the manifest of {title.id} in {self.path}: {e!r}")
|
||||||
|
self.snapshots[str(title.id)] = None
|
||||||
|
with self.lock:
|
||||||
|
export = self.namer.path or self.path
|
||||||
|
try:
|
||||||
|
doc = (
|
||||||
|
mediaexport.read(export)
|
||||||
|
if export.is_file()
|
||||||
|
else mediaexport.Document(service_tag=self.namer.service_tag)
|
||||||
|
)
|
||||||
|
except mediaexport.ExportError as e:
|
||||||
|
# a download mid-licensing must not die over the file it exports to
|
||||||
|
self.log.warning(f"Not exporting {title.id}: {export} is not a usable export ({e})")
|
||||||
|
return
|
||||||
|
doc.generator.setdefault("app", "unshackle")
|
||||||
|
doc.generator.setdefault("version", __version__)
|
||||||
|
if not doc.region and self.proxy_requested:
|
||||||
|
doc.region = self.source.current_region or ""
|
||||||
|
|
||||||
|
entry = doc.get(str(title.id))
|
||||||
|
if entry is None:
|
||||||
|
entry = self._entry(title)
|
||||||
|
doc.add(entry)
|
||||||
|
|
||||||
|
tracks_map = entry.ext("unshackle").setdefault("tracks", {})
|
||||||
|
track_dict = tracks_map.setdefault(str(track.id), track.to_dict())
|
||||||
|
unwanted = (track.data.get("hls") or {}).get("unwanted_segments")
|
||||||
|
if unwanted:
|
||||||
|
track_dict["unwanted_segments"] = unwanted
|
||||||
|
elif unwanted is not None:
|
||||||
|
track_dict.pop("unwanted_segments", None)
|
||||||
|
if saved := self.snapshots[str(title.id)]:
|
||||||
|
entry.ext("unshackle")["snapshot"] = saved
|
||||||
|
# the row names the track's KIDs, so an import gives the track only their keys
|
||||||
|
track_kids = [kid.hex for kid in own_kids(drm)] if drm is not None else []
|
||||||
|
for row in entry.tracks:
|
||||||
|
if row.get("id") == str(track.id):
|
||||||
|
row["selected"] = True
|
||||||
|
if track_kids:
|
||||||
|
row["kids"] = list(dict.fromkeys([*(row.get("kids") or []), *track_kids]))
|
||||||
|
|
||||||
|
if drm is not None:
|
||||||
|
if hasattr(drm, "to_dict"):
|
||||||
|
d = drm.to_dict()
|
||||||
|
own = entry.ext("unshackle").setdefault("drm", [])
|
||||||
|
if d not in own:
|
||||||
|
own.append(d)
|
||||||
|
system = str(d.get("system", "")).lower().replace("cenc", "")
|
||||||
|
pssh = str(d.get("pssh_b64") or "")
|
||||||
|
if system and all(x.pssh != pssh or x.system != system for x in entry.drm):
|
||||||
|
entry.drm.append(mediaexport.Drm(system, pssh))
|
||||||
|
content_keys = getattr(drm, "content_keys", None) or {}
|
||||||
|
pool = doc.key_pool()
|
||||||
|
for kid, key in content_keys.items():
|
||||||
|
# a KID that already holds a different key must not be overwritten:
|
||||||
|
# the reader rejects a file that disagrees with itself
|
||||||
|
if pool.setdefault(kid.hex, key.lower()) != key.lower():
|
||||||
|
self.log.warning(
|
||||||
|
f"KID {kid.hex} already has a different key in {export}, keeping the existing one"
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry.add_key(kid.hex, key)
|
||||||
|
except mediaexport.ExportError as e:
|
||||||
|
# a key the format cannot hold (not 16 bytes of hex) costs the export that key,
|
||||||
|
# never the download
|
||||||
|
self.log.warning(f"Not exporting the key for KID {kid.hex}: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
mediaexport.write(export, doc)
|
||||||
|
except (mediaexport.ExportError, OSError) as e:
|
||||||
|
self.log.warning(f"Could not write export {export}: {e}")
|
||||||
|
return
|
||||||
|
self._rename(export, title, track)
|
||||||
|
|
||||||
|
def _rename(self, export: Path, title: Title_T, track: AnyTrack) -> None:
|
||||||
|
"""Give the run's export a name that tells what it holds, after each write to it.
|
||||||
|
|
||||||
|
The file on disk is complete after each write, so a run that stops early still leaves
|
||||||
|
a usable file with a name that matches what it holds.
|
||||||
|
"""
|
||||||
|
first = self.namer.path is None
|
||||||
|
self.namer.add(title, track)
|
||||||
|
try:
|
||||||
|
self.namer.path = move_export(export, self.namer.name())
|
||||||
|
except OSError as e:
|
||||||
|
self.log.warning(f"Could not rename export {export}: {e}")
|
||||||
|
self.namer.path = export
|
||||||
|
if first:
|
||||||
|
self.log.info(f"Exporting to {self.namer.path.name}")
|
||||||
|
elif self.namer.path != export:
|
||||||
|
self.log.debug(f"Renamed the export to {self.namer.path.name}")
|
||||||
|
|
||||||
|
def log_title(self, title: Title_T) -> None:
|
||||||
|
"""Log what the export holds for one title: its track counts and its keys."""
|
||||||
|
entry = None
|
||||||
|
if self.namer.path:
|
||||||
|
try:
|
||||||
|
entry = mediaexport.read(self.namer.path).get(str(title.id))
|
||||||
|
except (mediaexport.ExportError, OSError) as e:
|
||||||
|
self.log.warning(f"Could not read export {self.namer.path}: {e}")
|
||||||
|
return
|
||||||
|
if entry is None:
|
||||||
|
self.log.warning(f"Exported nothing for {title_label(title)}")
|
||||||
|
return
|
||||||
|
selected = [r.get("type") for r in entry.tracks if r.get("selected")]
|
||||||
|
self.log.info(
|
||||||
|
f"Exported {title_label(title)}: {selected.count('video')} video, {selected.count('audio')} audio, "
|
||||||
|
f"{plural(selected.count('subtitle'), 'subtitle')}, {plural(len(entry.keys), 'key')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def log_summary(self) -> None:
|
||||||
|
"""Log where the run's export is and what it holds, and that it must stay private."""
|
||||||
|
if not self.namer.path:
|
||||||
|
self.log.warning("Nothing was exported")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
doc = mediaexport.read(self.namer.path)
|
||||||
|
except (mediaexport.ExportError, OSError) as e:
|
||||||
|
self.log.warning(f"Could not read export {self.namer.path}: {e}")
|
||||||
|
return
|
||||||
|
keys = len(doc.key_pool())
|
||||||
|
self.log.info(
|
||||||
|
f"Saved the export to {self.namer.path}: {plural(len(doc.titles), 'title')}, {plural(keys, 'key')}"
|
||||||
|
)
|
||||||
|
if keys:
|
||||||
|
self.log.warning("The export holds content keys: keep it private")
|
||||||
|
|
||||||
|
def _entry(self, title: Title_T) -> mediaexport.Entry:
|
||||||
|
"""A mediaexport entry for ``title``: manifests, chapters, a small track list, no keys yet."""
|
||||||
|
meta = wire.stamp_service_flags(wire.title_to_meta(title), self.source)
|
||||||
|
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
|
||||||
|
primary_url = title.tracks.manifest_url or next(
|
||||||
|
(str(t.url) for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
||||||
|
)
|
||||||
|
manifest_type = next(
|
||||||
|
(t.descriptor.name.lower() for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
||||||
|
)
|
||||||
|
# mediaexport drops Cookie and Authorization itself, on write and on read
|
||||||
|
headers = dict(getattr(self.source.session, "headers", None) or {})
|
||||||
|
manifests = (
|
||||||
|
[
|
||||||
|
mediaexport.Manifest(
|
||||||
|
primary_url,
|
||||||
|
manifest_type,
|
||||||
|
headers,
|
||||||
|
role="primary",
|
||||||
|
content_periods=self._content_periods(all_tracks, primary_url),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
if primary_url
|
||||||
|
else []
|
||||||
|
)
|
||||||
|
# the whole URL identifies a manifest: two profiles on one endpoint are two manifests
|
||||||
|
seen = {primary_url}
|
||||||
|
for t in all_tracks:
|
||||||
|
url = str(t.url)
|
||||||
|
if t.descriptor in (Video.Descriptor.DASH, Video.Descriptor.ISM) and url not in seen:
|
||||||
|
seen.add(url)
|
||||||
|
manifests.append(
|
||||||
|
mediaexport.Manifest(
|
||||||
|
url,
|
||||||
|
t.descriptor.name.lower(),
|
||||||
|
role="extra",
|
||||||
|
content_periods=self._content_periods(all_tracks, url),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for t in all_tracks:
|
||||||
|
codec = getattr(t, "codec", None)
|
||||||
|
row: dict[str, Any] = {
|
||||||
|
"id": str(t.id),
|
||||||
|
"type": t.__class__.__name__.lower(),
|
||||||
|
# a subtitle side-load names its file format so another tool can fetch it
|
||||||
|
"codec": (codec.value if isinstance(t, Subtitle) else codec.name).lower() if codec else "",
|
||||||
|
"language": str(t.language) if t.language else "",
|
||||||
|
"bitrate": int(bitrate) if (bitrate := getattr(t, "bitrate", None)) else None,
|
||||||
|
}
|
||||||
|
if isinstance(t, Video):
|
||||||
|
row.update(width=t.width, height=t.height, range=t.range.name.lower() if t.range else "")
|
||||||
|
if t.stereo:
|
||||||
|
row["stereo"] = True
|
||||||
|
elif isinstance(t, Audio):
|
||||||
|
row.update(channels=str(t.channels) if t.channels else "", atmos=bool(t.joc), descriptive=t.descriptive)
|
||||||
|
elif isinstance(t, Subtitle):
|
||||||
|
row.update(sdh=t.sdh, forced=t.forced, cc=t.cc)
|
||||||
|
if t.descriptor == Video.Descriptor.URL:
|
||||||
|
row["url"] = str(t.url)
|
||||||
|
rows.append({k: v for k, v in row.items() if v not in (None, "")})
|
||||||
|
|
||||||
|
return mediaexport.Entry(
|
||||||
|
id=str(title.id),
|
||||||
|
kind=meta.get("type", "movie"),
|
||||||
|
title=meta.get("name") or "",
|
||||||
|
series=meta.get("series_title") or "",
|
||||||
|
season=meta.get("season"),
|
||||||
|
episode=meta.get("number"),
|
||||||
|
year=meta.get("year"),
|
||||||
|
language=meta.get("language") or "",
|
||||||
|
artist=meta.get("artist") or "",
|
||||||
|
album=meta.get("album") or "",
|
||||||
|
track_number=meta.get("track"),
|
||||||
|
manifests=manifests,
|
||||||
|
chapters=[
|
||||||
|
{"start_ms": mediaexport.ts_ms(c.timestamp), "title": c.name or ""}
|
||||||
|
for c in (title.tracks.chapters or [])
|
||||||
|
],
|
||||||
|
tracks=rows,
|
||||||
|
extensions={
|
||||||
|
"x-unshackle": {
|
||||||
|
"meta": meta,
|
||||||
|
"tracks": {},
|
||||||
|
"attachments": [a.to_dict() for a in (title.tracks.attachments or []) if a.url],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _content_periods(tracks: Sequence[Track], url: str) -> list[str]:
|
||||||
|
"""The ids of the DASH periods a service kept in the manifest at ``url``, empty when it filtered none.
|
||||||
|
|
||||||
|
An import re-fetches the manifest without the service, so its period filter must travel in the export.
|
||||||
|
Empty also when a kept period has no id, since an id allow-list cannot name it.
|
||||||
|
"""
|
||||||
|
dash = next(
|
||||||
|
(d for t in tracks if (d := t.data.get("dash") or {}).get("filtered_period_ids") and str(t.url) == url),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if dash is None:
|
||||||
|
return []
|
||||||
|
kept = [
|
||||||
|
p.get("id") for p in dash["manifest"].findall("Period") if p.get("id") not in dash["filtered_period_ids"]
|
||||||
|
]
|
||||||
|
return kept if all(kept) else []
|
||||||
Reference in New Issue
Block a user