diff --git a/tests/core/test_blowfish_stripe.py b/tests/core/test_blowfish_stripe.py index f48f03a9..9e99c47a 100644 --- a/tests/core/test_blowfish_stripe.py +++ b/tests/core/test_blowfish_stripe.py @@ -12,13 +12,12 @@ import pytest import requests from Cryptodome.Cipher import Blowfish -from unshackle.core.api.handlers import serialize_audio_track, serialize_drm from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import BlowfishStripe -from unshackle.core.remote_service import build_tracks, reconstruct_drm from unshackle.core.tracks import Audio, Track from unshackle.core.tracks import track as track_module +from unshackle.core.wire import build_tracks, reconstruct_drm, serialize_audio_track, serialize_drm KEY = bytes.fromhex("00112233445566778899aabbccddeeff") CHUNK = BlowfishStripe.CHUNK diff --git a/tests/core/test_clearkey_cenc.py b/tests/core/test_clearkey_cenc.py index e19b59f2..75778f76 100644 --- a/tests/core/test_clearkey_cenc.py +++ b/tests/core/test_clearkey_cenc.py @@ -20,9 +20,9 @@ import pytest # lxml.etree: XML parser used to build ContentProtection fixtures for DASH.get_drm from lxml import etree -from unshackle.core.drm import drm_from_dict from unshackle.core.drm.clearkey_cenc import ClearKeyCENC from unshackle.core.manifests.dash import DASH +from unshackle.core.wire import drm_from_dict KID = UUID("9eb4050d-e44b-4802-932e-27d75083e266") KEY = bytes.fromhex("ccd0064c43f7e9fcbaa9b12af3fd1f40") diff --git a/tests/core/test_continuous_episodes.py b/tests/core/test_continuous_episodes.py index 85b2877b..30d93fde 100644 --- a/tests/core/test_continuous_episodes.py +++ b/tests/core/test_continuous_episodes.py @@ -5,8 +5,8 @@ from __future__ import annotations from types import SimpleNamespace from unshackle.commands.dl import dl -from unshackle.core.remote_service import apply_title_fields from unshackle.core.titles.episode import Episode, Series +from unshackle.core.wire import apply_title_fields class DummyService: diff --git a/tests/core/test_episode_sports.py b/tests/core/test_episode_sports.py index b222c473..4f19adfc 100644 --- a/tests/core/test_episode_sports.py +++ b/tests/core/test_episode_sports.py @@ -7,10 +7,9 @@ from datetime import date import pytest from unshackle.commands.dl import dl -from unshackle.core.api.handlers import serialize_title from unshackle.core.config import Config, config -from unshackle.core.remote_service import build_title from unshackle.core.titles.episode import Episode +from unshackle.core.wire import build_title, serialize_title SERIES = "{title}.{year?}.{season_episode}.{episode_name?}.{quality?}-{tag?}" SPORTS = "{title}.{year?}.{date?}.{episode_name}.{quality?}-{tag?}" diff --git a/tests/core/test_export.py b/tests/core/test_export.py index a59b67d1..0acaf80a 100644 --- a/tests/core/test_export.py +++ b/tests/core/test_export.py @@ -19,12 +19,12 @@ import click import pytest from unshackle.commands.dl import dl -from unshackle.core.drm import drm_from_dict from unshackle.core.drm.clearkey import ClearKey from unshackle.core.drm.clearkey_cenc import ClearKeyCENC from unshackle.core.import_service import ImportService from unshackle.core.titles import Movie from unshackle.core.tracks import Audio, Chapter, Subtitle, Video +from unshackle.core.wire import drm_from_dict KID = UUID(hex="00000000000000000000000000000001") diff --git a/tests/core/test_hdr10plus_probe.py b/tests/core/test_hdr10plus_probe.py index 9936bbb6..07f28b6e 100644 --- a/tests/core/test_hdr10plus_probe.py +++ b/tests/core/test_hdr10plus_probe.py @@ -13,6 +13,7 @@ from unshackle.core.remote_service import RemoteService from unshackle.core.tracks import Audio, Video from unshackle.core.utils import hdr10plus from unshackle.core.utils.hdr10plus import HDR10PLUS_T35, TS_PACKET, fragment_has_t35 +from unshackle.core.wire import track_from_dict, track_to_dict def box(kind: bytes, body: bytes) -> bytes: @@ -127,7 +128,7 @@ def test_a_dv_track_with_hdr10plus_lists_as_dv_plus_hdr10p() -> None: assert "[H.265, DV]" in str(video) video.hdr10plus = True assert "[H.265, DV+HDR10P]" in str(video) - assert Video.from_dict(video.to_dict()).hdr10plus + assert track_from_dict(track_to_dict(video)).hdr10plus def test_on_start_runs_only_when_there_is_a_track_to_probe(monkeypatch: pytest.MonkeyPatch) -> None: @@ -229,7 +230,7 @@ def test_a_quoted_dl_workers_value_works_like_the_cli(monkeypatch: pytest.Monkey def test_a_dv_track_with_an_hdr10_base_lists_as_dv_plus_hdr10() -> None: video = Video(url="https://x/v.mp4", language="en", codec=Video.Codec.HEVC, range_=Video.Range.DV, hdr10_base=True) assert "[H.265, DV+HDR10]" in str(video) - assert Video.from_dict(video.to_dict()).hdr10_base + assert track_from_dict(track_to_dict(video)).hdr10_base def ts_packet(pid: int, section: bytes) -> bytes: diff --git a/tests/core/test_load_tracks_enrich.py b/tests/core/test_load_tracks_enrich.py index 3fe4c94a..ae044717 100644 --- a/tests/core/test_load_tracks_enrich.py +++ b/tests/core/test_load_tracks_enrich.py @@ -3,9 +3,9 @@ from types import SimpleNamespace from langcodes import Language from unshackle.commands.dl import apply_enrich, load_tracks -from unshackle.core.remote_service import apply_title_fields from unshackle.core.titles import Episode, Movie, Song from unshackle.core.tracks import Chapters, Tracks +from unshackle.core.wire import apply_title_fields SERVICE = type("SVC", (), {}) diff --git a/tests/core/test_manifest_snapshot.py b/tests/core/test_manifest_snapshot.py index 5473f062..e09ad7bc 100644 --- a/tests/core/test_manifest_snapshot.py +++ b/tests/core/test_manifest_snapshot.py @@ -16,6 +16,7 @@ from unshackle.core.manifests import snapshot as snapshot_module from unshackle.core.manifests.snapshot import capture, parse, restore from unshackle.core.tracks import Tracks from unshackle.core.tracks.track import Track +from unshackle.core.wire import track_from_dict, track_to_dict URL = "https://cdn.example/title/manifest.mpd" @@ -116,7 +117,7 @@ def round_trip(tracks: Tracks, level: int = -1) -> Tracks: assert {"manifests", "track_manifests"} <= set(snapshot) client = Tracks() for track in tracks: - client.add(Track.from_dict(track.to_dict())) + client.add(track_from_dict(track_to_dict(track))) restore(client, snapshot) return client @@ -174,7 +175,7 @@ def test_a_filtered_period_that_reuses_a_kept_id_keeps_the_content(): @pytest.mark.parametrize("snapshot", ["garbage", {"manifests": "x"}, {"manifests": [1]}, {"track_manifests": {"a": 1}}]) def test_a_malformed_snapshot_restores_nothing(snapshot): client = Tracks() - client.add(Track.from_dict(service_tracks().videos[0].to_dict())) + client.add(track_from_dict(track_to_dict(service_tracks().videos[0]))) restore(client, snapshot) assert not client.videos[0].data.get("dash") assert parse(snapshot, URL, "en") is None @@ -193,7 +194,7 @@ def test_the_inflate_budget_covers_every_entry_of_one_restore(monkeypatch, caplo assert parse(saved, URL, "en") is not None client = Tracks() - client.add(Track.from_dict(service_tracks().videos[0].to_dict())) + client.add(track_from_dict(track_to_dict(service_tracks().videos[0]))) with caplog.at_level(logging.WARNING, logger="snapshot"): restore(client, saved) assert client.videos[0].data.get("dash") diff --git a/tests/core/test_playready_bare_header.py b/tests/core/test_playready_bare_header.py index 6d5e25ec..f7170169 100644 --- a/tests/core/test_playready_bare_header.py +++ b/tests/core/test_playready_bare_header.py @@ -16,10 +16,11 @@ from pyplayready.system.wrmheader import WRMHeader from pywidevine.pssh import PSSH as WV_PSSH from unshackle.core.api.handlers import pssh_kids -from unshackle.core.drm import PlayReady, Widevine, drm_from_dict +from unshackle.core.drm import PlayReady, Widevine from unshackle.core.manifests.dash import DASH from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.ism import ISM +from unshackle.core.wire import drm_from_dict KID = UUID("00112233-4455-6677-8899-aabbccddeeff") KID_B64 = base64.b64encode(KID.bytes_le).decode() diff --git a/tests/core/test_stereo_video.py b/tests/core/test_stereo_video.py index d54af33e..cbc999ec 100644 --- a/tests/core/test_stereo_video.py +++ b/tests/core/test_stereo_video.py @@ -20,6 +20,7 @@ from unshackle.core.titles.movie import Movie from unshackle.core.tracks import Audio, Chapter, Chapters, Track, Tracks, Video from unshackle.core.tracks import tracks as tracks_module from unshackle.core.tracks.tracks import pick_video +from unshackle.core.wire import track_from_dict, track_to_dict VIDEO_IDS = itertools.count() @@ -59,7 +60,7 @@ def test_hls_marks_stereo_tracks_from_the_layout_or_the_codec() -> None: def test_a_stereo_track_lists_as_3d_and_keeps_the_flag_through_to_dict() -> None: video = Video(url="https://x/v.mp4", language="en", codec=Video.Codec.HEVC, range_=Video.Range.DV, stereo=True) assert str(video).startswith("VID | [H.265, DV, 3D] |") - assert Video.from_dict(video.to_dict()).stereo + assert track_from_dict(track_to_dict(video)).stereo def stereo_video(tmp_path: Path, stereo: bool = True, **kwargs: Any) -> Video: diff --git a/tests/core/test_wire.py b/tests/core/test_wire.py new file mode 100644 index 00000000..b3fb222d --- /dev/null +++ b/tests/core/test_wire.py @@ -0,0 +1,1309 @@ +"""Pins the wire form of titles, tracks, DRM and attachments, in the REST form and the export form.""" + +from __future__ import annotations + +import inspect +import json +import logging +import re +import subprocess +import sys +from datetime import date +from pathlib import Path +from typing import Any +from uuid import UUID + +import click +import pytest +from pywidevine.pssh import PSSH as WidevinePSSH + +from tests.core.test_zero_kid_fallback import _playready_pssh +from unshackle.commands.dl import dl +from unshackle.core import wire +from unshackle.core.config import config +from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine +from unshackle.core.import_service import ImportService +from unshackle.core.titles import Episode, Movie, Song +from unshackle.core.titles.music import SONG_FIELDS +from unshackle.core.tracks import Audio, Subtitle, Tracks, Video +from unshackle.core.tracks.attachment import Attachment +from unshackle.core.tracks.track import Track +from unshackle.core.wire import ( + apply_title_fields, + attachment_to_dict, + build_attachment, + build_title, + build_tracks, + deserialize_audio, + deserialize_subtitle, + deserialize_video, + drm_from_dict, + drm_to_dict, + reconstruct_drm, + serialize_attachment, + serialize_audio_track, + serialize_drm, + serialize_subtitle_track, + serialize_title, + serialize_tracks, + serialize_video_track, + title_to_meta, + track_from_dict, + track_to_dict, +) + +pytestmark = pytest.mark.unit + +VIDEO_KID = UUID("00112233-4455-6677-8899-aabbccddeeff") +AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100") +VIDEO_KEY = "0123456789abcdef0123456789abcdef" +BLOWFISH_KEY = bytes(range(16)) + + +class EXAMPLE: + pass + + +def widevine(*kids: UUID, keys: bool = False) -> Widevine: + drm = Widevine(pssh=WidevinePSSH.new(system_id=WidevinePSSH.SystemId.Widevine, key_ids=list(kids))) + if keys: + drm.content_keys[VIDEO_KID] = VIDEO_KEY + return drm + + +def playready(*kids: UUID) -> PlayReady: + pssh, pssh_b64 = _playready_pssh(*kids) + return PlayReady(pssh=pssh, pssh_b64=pssh_b64) + + +def clearkey() -> ClearKeyCENC: + return ClearKeyCENC(kids=[VIDEO_KID], laurl="https://licence.example/ck") + + +def episode(**extra: Any) -> Episode: + fields: dict[str, Any] = dict( + id_="ep-0001", + service=EXAMPLE, + title="Example Show", + season=2, + number=5, + name="The Example", + year=2024, + language="en", + description="An example episode.", + air_date=date(2024, 3, 9), + data={"date": "2024-03-09", "cover_url": "https://img.example/ep.jpg"}, + ) + fields.update(extra) + return Episode(**fields) + + +def full_episode() -> Episode: + ep = episode(part=2, absolute=17, sport=True) + ep.anime = True + ep.daily = False + return ep + + +def movie() -> Movie: + return Movie( + id_="movie-0001", + service=EXAMPLE, + name="Example Film", + year=2023, + language="fr", + description="An example film.", + data={"cover_url": "https://img.example/film.jpg"}, + ) + + +def song() -> Song: + return Song( + id_="song-0001", + service=EXAMPLE, + name="Example Song", + artist="Example Artist", + album="Example Album", + track=3, + disc=1, + year=2022, + language="en", + data={"release_date": "2022-01-02", "composer": "Example Composer", "metadata": {"comment": "nested"}}, + album_artist="Example Band", + release_type="single", + total_tracks=12, + total_discs=2, + genre="Pop", + explicit=False, + isrc="EX0000000001", + upc="000000000001", + copyright="(c) Example", + label="Example Records", + lyrics="la la", + artwork_url="https://img.example/song.jpg", + synced_lyrics="[00:01.00]la", + lyrics_suffix=".lrc", + ) + + +class OtherTitle: + """A title of no known kind, as a service could hand back.""" + + id = "other-0001" + language = None + name = "Other Thing" + data = None + + def __str__(self) -> str: + return "Other Thing" + + +def video(**extra: Any) -> Video: + fields: dict[str, Any] = dict( + url="https://cdn.example/video.mpd", + language="en", + is_original_lang=True, + descriptor=Track.Descriptor.DASH, + needs_repack=True, + name="Main", + edition=["IMAX"], + note="High profile", + codec=Video.Codec.HEVC, + range_=Video.Range.DV, + bitrate=8_123_456, + width=3840, + height=2160, + fps="24000/1001", + scan_type=Video.ScanType.PROGRESSIVE, + closed_captions=[{"language": "en", "channel": "CC1"}], + dv_compatible_bitstream=True, + hdr10plus=True, + hdr10_base=True, + stereo=True, + id_="video-0001", + ) + fields.update(extra) + track = Video(**fields) + track.data["service_value"] = {"a": 1} + track.data["dash"] = {"not": "json-safe here"} + track.data["unsafe"] = object() + return track + + +def audio(**extra: Any) -> Audio: + fields: dict[str, Any] = dict( + url="https://cdn.example/audio.mpd", + language="en", + descriptor=Track.Descriptor.HLS, + codec=Audio.Codec.EC3, + bitrate=640_000, + channels="5.1", + joc=16, + descriptive=True, + id_="audio-0001", + ) + fields.update(extra) + return Audio(**fields) + + +def subtitle(**extra: Any) -> Subtitle: + fields: dict[str, Any] = dict( + url="https://cdn.example/sub.vtt", + language="pt-BR", + descriptor=Track.Descriptor.URL, + codec=Subtitle.Codec.WebVTT, + cc=False, + sdh=True, + forced=False, + id_="sub-0001", + ) + fields.update(extra) + return Subtitle(**fields) + + +def drm_fields(drm: Any) -> dict[str, Any]: + """What a DRM object carries across the edge.""" + out: dict[str, Any] = { + "class": type(drm).__name__, + "kids": [kid.hex for kid in getattr(drm, "kids", None) or []], + "content_keys": {kid.hex: key for kid, key in (getattr(drm, "content_keys", None) or {}).items()}, + } + if isinstance(drm, Widevine): + out["pssh"] = drm.pssh.dumps() + if isinstance(drm, PlayReady): + out["pssh"] = drm.pssh_b64 + if isinstance(drm, ClearKeyCENC): + out["laurl"] = drm.laurl + if isinstance(drm, BlowfishStripe): + out["key"] = drm.key.hex() + return out + + +def track_fields(track: Any) -> dict[str, Any]: + """What a track carries across the edge.""" + out: dict[str, Any] = { + "class": type(track).__name__, + "id": track.id, + "url": track.url, + "language": str(track.language), + "is_original_lang": track.is_original_lang, + "descriptor": track.descriptor.name, + "needs_repack": track.needs_repack, + "name": track.name, + "edition": track.edition, + "note": track.note, + "codec": track.codec.name if track.codec else None, + "drm": [drm_fields(d) for d in track.drm or []], + "drm_preference": track.drm_preference, + } + if isinstance(track, Video): + out.update( + range=track.range.name if track.range else None, + bitrate=track.bitrate, + width=track.width, + height=track.height, + fps=track.fps, + scan_type=track.scan_type.name if track.scan_type else None, + closed_captions=track.closed_captions, + dv_compatible_bitstream=track.dv_compatible_bitstream, + hdr10plus=track.hdr10plus, + hdr10_base=track.hdr10_base, + stereo=track.stereo, + ) + elif isinstance(track, Audio): + out.update( + bitrate=track.bitrate, + channels=track.channels, + joc=track.joc, + atmos=track.atmos, + descriptive=track.descriptive, + ) + elif isinstance(track, Subtitle): + out.update(cc=track.cc, sdh=track.sdh, forced=track.forced) + return out + + +def title_fields(title: Any) -> dict[str, Any]: + """What a title carries across the edge.""" + out: dict[str, Any] = { + "class": type(title).__name__, + "service": title.service.__name__, + "id": title.id, + "language": str(title.language) if title.language else None, + "year": title.year, + "data": title.data, + } + if isinstance(title, Episode): + out.update( + title=title.title, + season=title.season, + number=title.number, + name=title.name, + part=title.part, + description=title.description, + air_date=title.air_date, + absolute=title.absolute, + sport=title.sport, + anime=getattr(title, "anime", None), + daily=getattr(title, "daily", None), + ) + elif isinstance(title, Movie): + out.update(name=title.name, description=title.description, anime=getattr(title, "anime", None)) + elif isinstance(title, Song): + out.update(name=title.name, **{f: getattr(title, f) for f in SONG_FIELDS}) + return out + + +WIDEVINE_PSSH = "AAAAMnBzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAABISEAARIjNEVWZ3iJmqu8zd7v8=" +KIDLESS_PSSH = "AAAAJXBzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAAAUiA2FiYw==" +KIDLESS_WITH_KID_PSSH = "AAAAN3Bzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAABcSEAARIjNEVWZ3iJmqu8zd7v8iA2FiYw==" +PLAYREADY_PSSH = _playready_pssh(VIDEO_KID, AUDIO_KID)[1] + + +def json_copy(value: Any) -> Any: + """What the other side of the edge reads.""" + return json.loads(json.dumps(value)) + + +def named(expected: dict[str, Any], track: Any) -> dict[str, Any]: + """The expected REST dict with the track name the muxing config gives this track.""" + return {**expected, "track_name": track.get_track_name()} + + +def drm_track() -> Video: + track = video() + track.drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID)] + track.drm_preference = "pr" + return track + + +REST_EPISODE = { + "type": "episode", + "name": "The Example", + "id": "ep-0001", + "language": "en", + "description": "An example episode.", + "date": "2024-03-09", + "cover_url": "https://img.example/ep.jpg", + "year": 2024, + "series_title": "Example Show", + "season": 2, + "number": 5, + "part": 2, + "air_date": "2024-03-09", + "absolute": 17, + "daily": False, + "sport": True, + "anime": True, +} + +REST_MOVIE = { + "type": "movie", + "name": "Example Film", + "id": "movie-0001", + "language": "fr", + "description": "An example film.", + "date": None, + "cover_url": "https://img.example/film.jpg", + "year": 2023, +} + +REST_SONG = { + "type": "song", + "name": "Example Song", + "id": "song-0001", + "language": "en", + "description": None, + "date": None, + "cover_url": None, + "year": 2022, + "artist": "Example Artist", + "album": "Example Album", + "track": 3, + "disc": 1, + "album_artist": "Example Band", + "release_type": "single", + "total_tracks": 12, + "total_discs": 2, + "genre": "Pop", + "explicit": False, + "isrc": "EX0000000001", + "upc": "000000000001", + "copyright": "(c) Example", + "label": "Example Records", + "lyrics": "la la", + "synced_lyrics": "[00:01.00]la", + "lyrics_suffix": ".lrc", + "artwork_url": "https://img.example/song.jpg", + "music_data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"}, +} + +META_EPISODE = { + "id": "ep-0001", + "language": "en", + "type": "episode", + "series_title": "Example Show", + "season": 2, + "number": 5, + "name": "The Example", + "year": 2024, + "air_date": "2024-03-09", + "part": 2, + "absolute": 17, + "daily": False, + "sport": True, + "anime": True, +} + +REST_VIDEO = { + "id": "video-0001", + "codec": "HEVC", + "codec_display": "H.265", + "bitrate": 8123, + "bitrate_bps": 8123456, + "width": 3840, + "height": 2160, + "resolution": "3840x2160", + "fps": 23.976023976023978, + "range": "DV", + "range_display": "DV+HDR10P", + "scan_type": "PROGRESSIVE", + "closed_captions": [{"language": "en", "channel": "CC1"}], + "dv_compatible_bitstream": True, + "hdr10plus": True, + "hdr10_base": True, + "stereo": True, + "language": "en", + "is_original_lang": True, + "name": "Main", + "track_name": "Main", + "needs_repack": True, + "edition": ["IMAX"], + "note": "High profile", + "descriptor": "DASH", + "drm": [ + { + "type": "widevine", + "pssh": WIDEVINE_PSSH, + "kids": ["00112233-4455-6677-8899-aabbccddeeff"], + "content_keys": {"00112233-4455-6677-8899-aabbccddeeff": VIDEO_KEY}, + }, + { + "type": "playready", + "pssh": PLAYREADY_PSSH, + "kids": ["00112233-4455-6677-8899-aabbccddeeff", "ffeeddcc-bbaa-9988-7766-554433221100"], + }, + ], + "drm_preference": "pr", + "data": {"service_value": {"a": 1}}, + "url": "https://cdn.example/video.mpd", +} + +REST_AUDIO = { + "id": "audio-0001", + "codec": "EC3", + "codec_display": "DDP", + "bitrate": 640, + "bitrate_bps": 640000, + "channels": 5.1, + "is_original": True, + "atmos": True, + "joc": 16, + "descriptive": True, + "language": "en", + "is_original_lang": False, + "name": None, + "track_name": "set per test", + "needs_repack": False, + "edition": [], + "note": None, + "descriptor": "HLS", + "drm": None, + "drm_preference": None, + "data": None, + "url": "https://cdn.example/audio.mpd", +} + +REST_SUBTITLE = { + "id": "sub-0001", + "codec": "WebVTT", + "forced": False, + "sdh": True, + "cc": False, + "language": "pt-BR", + "is_original_lang": False, + "name": None, + "track_name": "set per test", + "needs_repack": False, + "edition": [], + "note": None, + "descriptor": "URL", + "drm": None, + "drm_preference": None, + "data": None, +} + +EXPORT_VIDEO = { + "type": "Video", + "id": "video-0001", + "url": "https://cdn.example/video.mpd", + "language": "en", + "is_original_lang": True, + "descriptor": "DASH", + "needs_repack": True, + "name": "Main", + "edition": ["IMAX"], + "note": "High profile", + "codec": "HEVC", + "range": "DV", + "bitrate": 8123456, + "width": 3840, + "height": 2160, + "fps": "23.976023976023978", + "scan_type": "PROGRESSIVE", + "dv_compatible_bitstream": True, + "hdr10plus": True, + "hdr10_base": True, + "stereo": True, +} + +EXPORT_AUDIO = { + "type": "Audio", + "id": "audio-0001", + "url": "https://cdn.example/audio.mpd", + "language": "en", + "is_original_lang": False, + "descriptor": "HLS", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "EC3", + "bitrate": 640000, + "channels": 5.1, + "joc": 16, + "descriptive": True, +} + +EXPORT_SUBTITLE = { + "type": "Subtitle", + "id": "sub-0001", + "url": "https://cdn.example/sub.vtt", + "language": "pt-BR", + "is_original_lang": False, + "descriptor": "URL", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "WebVTT", + "cc": False, + "sdh": True, + "forced": False, +} + +VIDEO_FIELDS = { + "class": "Video", + "id": "video-0001", + "url": "https://cdn.example/video.mpd", + "language": "en", + "is_original_lang": True, + "descriptor": "DASH", + "needs_repack": True, + "name": "Main", + "edition": ["IMAX"], + "note": "High profile", + "codec": "HEVC", + "drm": [], + "drm_preference": None, + "range": "DV", + "bitrate": 8123456, + "width": 3840, + "height": 2160, + "fps": 23.976023976023978, + "scan_type": "PROGRESSIVE", + "closed_captions": [{"language": "en", "channel": "CC1"}], + "dv_compatible_bitstream": True, + "hdr10plus": True, + "hdr10_base": True, + "stereo": True, +} + +AUDIO_FIELDS = { + "class": "Audio", + "id": "audio-0001", + "url": "https://cdn.example/audio.mpd", + "language": "en", + "is_original_lang": False, + "descriptor": "HLS", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "EC3", + "drm": [], + "drm_preference": None, + "bitrate": 640000, + "channels": 5.1, + "joc": 16, + "atmos": True, + "descriptive": True, +} + +SUBTITLE_FIELDS = { + "class": "Subtitle", + "id": "sub-0001", + "url": "https://cdn.example/sub.vtt", + "language": "pt-BR", + "is_original_lang": False, + "descriptor": "URL", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "WebVTT", + "drm": [], + "drm_preference": None, + "cc": False, + "sdh": True, + "forced": False, +} + +WIDEVINE_FIELDS = {"class": "Widevine", "kids": [VIDEO_KID.hex], "content_keys": {}, "pssh": WIDEVINE_PSSH} +PLAYREADY_FIELDS = { + "class": "PlayReady", + "kids": [VIDEO_KID.hex, AUDIO_KID.hex], + "content_keys": {}, + "pssh": PLAYREADY_PSSH, +} +CLEARKEY_FIELDS = { + "class": "ClearKeyCENC", + "kids": [VIDEO_KID.hex], + "content_keys": {}, + "laurl": "https://licence.example/ck", +} + +EPISODE_FIELDS = { + "class": "Episode", + "service": "EXAMPLE", + "id": "ep-0001", + "language": "en", + "year": 2024, + "data": {"date": "2024-03-09", "cover_url": "https://img.example/ep.jpg"}, + "title": "Example Show", + "season": 2, + "number": 5, + "name": "The Example", + "part": 2, + "description": "An example episode.", + "air_date": date(2024, 3, 9), + "absolute": 17, + "sport": True, + "anime": True, + "daily": False, +} + + +def test_rest_episode() -> None: + assert serialize_title(full_episode()) == REST_EPISODE + + +def test_rest_episode_without_a_name_gets_a_placeholder_and_no_optional_keys() -> None: + assert serialize_title(episode(name=None)) == { + "type": "episode", + "name": "Episode 05", + "id": "ep-0001", + "language": "en", + "description": "An example episode.", + "date": "2024-03-09", + "cover_url": "https://img.example/ep.jpg", + "year": 2024, + "series_title": "Example Show", + "season": 2, + "number": 5, + "air_date": "2024-03-09", + } + + +def test_rest_movie() -> None: + assert serialize_title(movie()) == REST_MOVIE + + +def test_rest_song() -> None: + assert serialize_title(song()) == REST_SONG + + +def test_rest_title_of_no_known_kind() -> None: + assert serialize_title(OtherTitle()) == { + "type": "other", + "name": "Other Thing", + "id": "other-0001", + "language": None, + "description": None, + "date": None, + "cover_url": None, + } + + +def test_rest_title_key_order_is_stable() -> None: + assert list(serialize_title(full_episode())) == list(REST_EPISODE) + assert list(serialize_title(song())) == list(REST_SONG) + + +def test_export_episode_meta() -> None: + meta = dl.title_to_meta(full_episode()) + assert meta == META_EPISODE + assert list(meta) == list(META_EPISODE) + + +def test_export_movie_meta() -> None: + assert dl.title_to_meta(movie()) == { + "id": "movie-0001", + "language": "fr", + "type": "movie", + "name": "Example Film", + "year": 2023, + } + + +def test_export_meta_of_another_title_is_a_movie_named_by_str() -> None: + assert dl.title_to_meta(song()) == { + "id": "song-0001", + "language": "en", + "type": "movie", + "name": "Example Artist - Example Album (2022) / 03. Example Song", + } + + +def test_build_title_from_rest_episode() -> None: + assert title_fields(build_title(json_copy(REST_EPISODE), "EXAMPLE", "fallback-id")) == EPISODE_FIELDS + + +def test_build_title_drops_the_placeholder_name() -> None: + title = build_title(json_copy(serialize_title(episode(name=None))), "EXAMPLE", "fallback-id") + assert title_fields(title) == { + **EPISODE_FIELDS, + "name": None, + "part": None, + "absolute": None, + "sport": False, + "anime": None, + "daily": None, + } + + +def test_build_title_from_rest_movie() -> None: + assert title_fields(build_title(json_copy(REST_MOVIE), "EXAMPLE", "fallback-id")) == { + "class": "Movie", + "service": "EXAMPLE", + "id": "movie-0001", + "language": "fr", + "year": 2023, + "data": {"cover_url": "https://img.example/film.jpg"}, + "name": "Example Film", + "description": "An example film.", + "anime": None, + } + + +def test_build_title_from_rest_song() -> None: + fields = title_fields(build_title(json_copy(REST_SONG), "EXAMPLE", "fallback-id")) + assert fields == { + "class": "Song", + "service": "EXAMPLE", + "id": "song-0001", + "language": "en", + "year": 2022, + "data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"}, + "name": "Example Song", + **{key: REST_SONG[key] for key in SONG_FIELDS}, + } + + +def test_build_title_from_export_meta() -> None: + title = build_title(json_copy(META_EPISODE), "EXAMPLE", "fallback-id") + assert title_fields(title) == {**EPISODE_FIELDS, "data": None, "description": None} + + +def test_build_title_from_a_bare_episode_uses_the_fallbacks() -> None: + assert title_fields(build_title({"type": "episode"}, "EXAMPLE", "fallback-id")) == { + "class": "Episode", + "service": "EXAMPLE", + "id": "fallback-id", + "language": None, + "year": None, + "data": None, + "title": "Unknown", + "season": 0, + "number": 0, + "name": None, + "part": None, + "description": None, + "air_date": None, + "absolute": None, + "sport": False, + "anime": None, + "daily": None, + } + + +def test_build_title_refuses_an_unknown_kind() -> None: + with pytest.raises(click.ClickException, match="unknown title type 'other'"): + build_title(json_copy(serialize_title(OtherTitle())), "EXAMPLE", "fallback-id") + + +def test_apply_title_fields_keeps_season_and_number() -> None: + title = episode(name=None, description=None, data=None) + apply_title_fields( + title, + { + "language": "de", + "description": "New", + "year": 2030, + "series_title": "Renamed", + "name": "Episode 9", + "absolute": 3, + "air_date": "2030-01-02T00:00:00", + "anime": True, + "sport": True, + "date": "d", + "cover_url": "c", + "season": 9, + }, + ) + assert title_fields(title) == { + **EPISODE_FIELDS, + "language": "de", + "year": 2030, + "data": {"date": "d", "cover_url": "c"}, + "title": "Renamed", + "name": None, + "part": None, + "description": "New", + "air_date": date(2030, 1, 2), + "absolute": 3, + "sport": True, + "anime": True, + "daily": None, + } + + +def test_rest_video() -> None: + serialized = serialize_video_track(drm_track(), include_url=True) + assert serialized == REST_VIDEO + assert list(serialized) == list(REST_VIDEO) + + +def test_rest_audio() -> None: + serialized = serialize_audio_track(audio(), include_url=True, is_original=True) + assert serialized == named(REST_AUDIO, audio()) + assert list(serialized) == list(REST_AUDIO) + + +def test_rest_subtitle() -> None: + serialized = serialize_subtitle_track(subtitle()) + assert serialized == named(REST_SUBTITLE, subtitle()) + assert list(serialized) == list(REST_SUBTITLE) + + +def test_rest_tracks_sort_by_bitrate_and_flag_the_original_audio() -> None: + tracks = Tracks( + [ + video(id_="v-low", bitrate=1000), + video(id_="v-high", bitrate=9000), + audio(id_="a-fr", language="fr", bitrate=1), + audio(id_="a-en", language="en", bitrate=2), + subtitle(), + ] + ) + lists = serialize_tracks(tracks, movie()) + assert list(lists) == ["video", "audio", "subtitles"] + assert [(v["id"], v["bitrate_bps"]) for v in lists["video"]] == [("v-high", 9000), ("v-low", 1000)] + assert [(a["id"], a["is_original"]) for a in lists["audio"]] == [("a-en", False), ("a-fr", True)] + assert lists["subtitles"] == [named(REST_SUBTITLE, subtitle())] + assert "url" not in lists["video"][0] + + +def test_export_video() -> None: + assert video().to_dict() == EXPORT_VIDEO + assert list(video().to_dict()) == list(EXPORT_VIDEO) + + +def test_export_audio() -> None: + assert audio().to_dict() == EXPORT_AUDIO + assert list(audio().to_dict()) == list(EXPORT_AUDIO) + + +def test_export_subtitle() -> None: + assert subtitle().to_dict() == EXPORT_SUBTITLE + assert list(subtitle().to_dict()) == list(EXPORT_SUBTITLE) + + +def test_deserialize_rest_tracks() -> None: + assert track_fields(deserialize_video(json_copy(REST_VIDEO))) == VIDEO_FIELDS + assert track_fields(deserialize_audio(json_copy(REST_AUDIO))) == AUDIO_FIELDS + assert track_fields(deserialize_subtitle(json_copy(REST_SUBTITLE))) == { + **SUBTITLE_FIELDS, + "url": "https://placeholder", + } + + +def test_deserialize_a_track_from_an_older_server() -> None: + old_video = deserialize_video( + {"id": "v-old", "codec": "AVC", "bitrate": 5000, "language": "en", "is_original": True} + ) + assert track_fields(old_video) == { + "class": "Video", + "id": "v-old", + "url": "https://placeholder", + "language": "en", + "is_original_lang": True, + "descriptor": "URL", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "AVC", + "drm": [], + "drm_preference": None, + "range": "SDR", + "bitrate": 5000000, + "width": None, + "height": None, + "fps": None, + "scan_type": None, + "closed_captions": [], + "dv_compatible_bitstream": False, + "hdr10plus": False, + "hdr10_base": False, + "stereo": False, + } + old_audio = deserialize_audio({"id": "a-old", "codec": "AAC", "atmos": True, "channels": 6}) + assert track_fields(old_audio) == { + "class": "Audio", + "id": "a-old", + "url": "https://placeholder", + "language": "und", + "is_original_lang": False, + "descriptor": "URL", + "needs_repack": False, + "name": None, + "edition": [], + "note": None, + "codec": "AAC", + "drm": [], + "drm_preference": None, + "bitrate": None, + "channels": 6.0, + "joc": None, + "atmos": True, + "descriptive": False, + } + odd_subtitle = deserialize_subtitle({"id": "s-old", "codec": "NOPE", "note": 5}) + assert track_fields(odd_subtitle) == { + **SUBTITLE_FIELDS, + "id": "s-old", + "url": "https://placeholder", + "language": "und", + "codec": None, + "sdh": False, + } + + +def test_export_tracks_decode() -> None: + assert track_fields(track_from_dict(json_copy(EXPORT_VIDEO))) == {**VIDEO_FIELDS, "closed_captions": []} + assert track_fields(track_from_dict(json_copy(EXPORT_AUDIO))) == AUDIO_FIELDS + assert track_fields(track_from_dict(json_copy(EXPORT_SUBTITLE))) == SUBTITLE_FIELDS + + +def test_export_track_of_an_unknown_kind_is_refused() -> None: + with pytest.raises(ValueError, match="unsupported track type: 'Chapter'"): + track_from_dict({**EXPORT_VIDEO, "type": "Chapter"}) + + +def test_build_tracks_attaches_drm_preference_and_attachments() -> None: + lists = serialize_tracks(Tracks([drm_track(), audio(), subtitle()]), movie(), include_url=True) + attachment = serialize_attachment(Attachment(url="https://img.example/p.jpg", name="P")) + tracks = build_tracks(json_copy({**lists, "attachments": [attachment]})) + assert track_fields(tracks.videos[0]) == { + **VIDEO_FIELDS, + "drm": [WIDEVINE_FIELDS, PLAYREADY_FIELDS], + "drm_preference": "pr", + } + assert track_fields(tracks.audio[0]) == AUDIO_FIELDS + assert track_fields(tracks.subtitles[0]) == SUBTITLE_FIELDS + assert [(a.name, a.url) for a in tracks.attachments] == [("P", "https://img.example/p.jpg")] + + +def test_rest_drm_of_each_system() -> None: + drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()] + assert serialize_drm(drm) == [ + *REST_VIDEO["drm"], + {"type": "blowfishstripe", "key": "000102030405060708090a0b0c0d0e0f"}, + {"type": "clearkeycenc", "kids": ["00112233-4455-6677-8899-aabbccddeeff"]}, + ] + + +def test_export_drm_of_each_system() -> None: + assert widevine(VIDEO_KID).to_dict() == { + "system": "Widevine", + "pssh_b64": WIDEVINE_PSSH, + "kids": [VIDEO_KID.hex], + } + assert playready(VIDEO_KID, AUDIO_KID).to_dict() == { + "system": "PlayReady", + "pssh_b64": PLAYREADY_PSSH, + "kids": [VIDEO_KID.hex, AUDIO_KID.hex], + } + assert clearkey().to_dict() == { + "system": "ClearKeyCENC", + "kids": [VIDEO_KID.hex], + "laurl": "https://licence.example/ck", + } + + +def test_reconstruct_rest_drm() -> None: + drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()] + rebuilt = reconstruct_drm(json_copy(serialize_drm(drm))) + assert [drm_fields(d) for d in rebuilt] == [ + WIDEVINE_FIELDS, + PLAYREADY_FIELDS, + {"class": "BlowfishStripe", "kids": [], "content_keys": {}, "key": "000102030405060708090a0b0c0d0e0f"}, + ] + + +def test_reconstruct_rest_drm_gives_a_kidless_pssh_the_first_kid() -> None: + rebuilt = reconstruct_drm([{"type": "widevine", "pssh": KIDLESS_PSSH, "kids": [str(VIDEO_KID)]}]) + assert [drm_fields(d) for d in rebuilt] == [{**WIDEVINE_FIELDS, "pssh": KIDLESS_WITH_KID_PSSH}] + + +def test_reconstruct_rest_drm_skips_what_it_cannot_parse(caplog: pytest.LogCaptureFixture) -> None: + entries = [{"type": "widevine"}, {"type": "playready", "pssh": "!!"}, {"type": "clearkeycenc", "kids": ["x"]}] + with caplog.at_level(logging.WARNING): + assert reconstruct_drm(entries) == [] + assert [(r.name, r.getMessage()) for r in caplog.records] == [ + ( + "remote_service", + "Skipping unparseable playready DRM entry from server: InvalidPssh('Data must not be empty')", + ) + ] + + +def test_export_drm_decode() -> None: + rebuilt = [drm_from_dict(json_copy(d.to_dict())) for d in (widevine(VIDEO_KID), playready(VIDEO_KID, AUDIO_KID))] + rebuilt.append(drm_from_dict(json_copy(clearkey().to_dict()))) + assert [drm_fields(d) for d in rebuilt] == [WIDEVINE_FIELDS, PLAYREADY_FIELDS, CLEARKEY_FIELDS] + + +def test_export_drm_decode_takes_the_stored_keys() -> None: + data = { + "system": "Widevine", + "pssh_b64": KIDLESS_PSSH, + "kids": [VIDEO_KID.hex], + "content_keys": {VIDEO_KID.hex: VIDEO_KEY}, + } + assert drm_fields(drm_from_dict(data)) == { + **WIDEVINE_FIELDS, + "content_keys": {VIDEO_KID.hex: VIDEO_KEY}, + "pssh": KIDLESS_WITH_KID_PSSH, + } + + +@pytest.mark.parametrize( + "data, message", + [ + ({"system": "Widevine"}, "Cannot reconstruct DRM without a stored PSSH."), + ({"system": "Nope", "pssh_b64": "x"}, "Unsupported DRM system for reconstruction: 'Nope'"), + ], +) +def test_export_drm_decode_refuses(data: dict[str, Any], message: str) -> None: + with pytest.raises(ValueError, match=re.escape(message)): + drm_from_dict(data) + + +def test_rest_attachment_by_url() -> None: + attachment = Attachment( + url="https://img.example/poster.jpg", name="Poster", mime_type="image/jpeg", description="Cover" + ) + expected = { + "url": "https://img.example/poster.jpg", + "name": "Poster", + "mime_type": "image/jpeg", + "description": "Cover", + } + assert serialize_attachment(attachment) == expected + assert attachment.to_dict() == expected + + +def test_rest_attachment_by_path_carries_the_bytes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(config.directories, "temp", tmp_path / "temp") + poster = tmp_path / "poster.jpg" + poster.write_bytes(b"jpeg-bytes") + serialized = serialize_attachment(Attachment(path=poster, name="Poster", description="Cover")) + assert serialized == { + "url": None, + "name": "Poster", + "mime_type": "image/jpeg", + "description": "Cover", + "content": "anBlZy1ieXRlcw==", + "file_name": "poster.jpg", + } + rebuilt = build_attachment(json_copy(serialized)) + assert rebuilt is not None + assert rebuilt.path == tmp_path / "temp" / "remote_attachments" / "poster.jpg" + assert rebuilt.path.read_bytes() == b"jpeg-bytes" + assert (rebuilt.url, rebuilt.name, rebuilt.mime_type, rebuilt.description) == ( + None, + "Poster", + "image/jpeg", + "Cover", + ) + + +def test_build_attachment_by_url_and_with_nothing() -> None: + rebuilt = build_attachment({"url": "https://img.example/p.jpg", "name": "P", "mime_type": "image/jpeg"}) + assert rebuilt is not None + assert (rebuilt.path, rebuilt.url, rebuilt.name, rebuilt.mime_type) == ( + None, + "https://img.example/p.jpg", + "P", + "image/jpeg", + ) + assert build_attachment({"name": "x"}) is None + + +def test_rest_titles_round_trip() -> None: + for title in (full_episode(), movie()): + assert title_fields(build_title(json_copy(serialize_title(title)), "EXAMPLE", "fallback-id")) == title_fields( + title + ) + rebuilt = title_fields(build_title(json_copy(serialize_title(song())), "EXAMPLE", "fallback-id")) + assert {**rebuilt, "data": None} == {**title_fields(song()), "data": None} + + +def test_export_meta_round_trips_the_fields_it_carries() -> None: + episode_meta = title_fields(build_title(json_copy(title_to_meta(full_episode())), "EXAMPLE", "fallback-id")) + assert episode_meta == {**title_fields(full_episode()), "data": None, "description": None} + movie_meta = title_fields(build_title(json_copy(title_to_meta(movie())), "EXAMPLE", "fallback-id")) + assert movie_meta == {**title_fields(movie()), "data": None, "description": None} + + +def test_rest_tracks_round_trip_with_their_drm() -> None: + track = video() + track.drm = [widevine(VIDEO_KID), playready(VIDEO_KID, AUDIO_KID)] + track.drm_preference = "pr" + lists = serialize_tracks(Tracks([track, audio(), subtitle()]), movie(), include_url=True) + rebuilt = build_tracks(json_copy(lists)) + assert [track_fields(t) for t in (*rebuilt.videos, *rebuilt.audio, *rebuilt.subtitles)] == [ + track_fields(t) for t in (track, audio(), subtitle()) + ] + + +def test_export_tracks_round_trip_without_closed_captions() -> None: + for track in (video(), audio(), subtitle()): + expected = track_fields(track) + if isinstance(track, Video): + expected["closed_captions"] = [] + assert track_fields(track_from_dict(json_copy(track_to_dict(track)))) == expected + + +def test_both_track_forms_decode_the_shared_fields_the_same_way() -> None: + shared = ("id", "url", "language", "is_original_lang", "descriptor", "needs_repack", "name", "edition", "note") + forms: list[tuple[Any, Any, Any]] = [ + (video(), serialize_video_track, deserialize_video), + (audio(), serialize_audio_track, deserialize_audio), + (subtitle(), serialize_subtitle_track, deserialize_subtitle), + ] + for track, encode, decode in forms: + rest = track_fields(decode(json_copy(encode(track, include_url=True)))) + export = track_fields(track_from_dict(json_copy(track_to_dict(track)))) + assert {key: rest[key] for key in shared} == {key: export[key] for key in shared} + + +URL_SUBTITLE = { + "type": "Subtitle", + "id": "good", + "url": "https://example.invalid/en.srt", + "language": "en", + "descriptor": "URL", + "codec": "SubRip", +} + + +@pytest.mark.parametrize( + "change, error", + [ + ({"descriptor": "NEW"}, "'NEW'"), + ({"url": None}, "'url'"), + ({"is_original_lang": "yes"}, "Expected is_original_lang to be a , not "), + ({"needs_repack": 1}, "Expected needs_repack to be a , not "), + ({"note": 5}, "Expected note to be a , not "), + ( + {"language": 5}, + "Expected language to be a or , not ", + ), + ({"codec": "NOPE"}, "'NOPE'"), + ], + ids=["descriptor", "no-url", "original-flag", "repack-flag", "note", "language", "codec"], +) +def test_an_import_skips_a_malformed_export_track( + tmp_path: Path, caplog: pytest.LogCaptureFixture, change: dict[str, Any], error: str +) -> None: + bad = {key: value for key, value in {**URL_SUBTITLE, "id": "bad", **change}.items() if value is not None} + entry = { + "meta": {"type": "movie", "id": "movie-1", "name": "Example Movie", "year": 2024, "language": "en"}, + "manifest_type": "DASH", + "tracks": {"good": URL_SUBTITLE, "bad": bad}, + } + path = tmp_path / "export.json" + path.write_text(json.dumps({"version": 2, "service": "EXAMPLE", "titles": {"movie-1": entry}}), encoding="utf8") + service = ImportService(click.Context(click.Command("dl")), "EXAMPLE", "movie-1", str(path)) + with caplog.at_level(logging.WARNING): + tracks = service.get_tracks(next(iter(service.get_titles()))) + assert [t.id for t in tracks.subtitles] == ["good"] + assert [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"] == [ + f"Skipping exported track 'bad': {error}" + ] + + +def test_drm_round_trips_in_both_forms() -> None: + drm = [widevine(VIDEO_KID), playready(VIDEO_KID, AUDIO_KID)] + assert [drm_fields(d) for d in reconstruct_drm(json_copy(serialize_drm(drm)))] == [drm_fields(d) for d in drm] + for one in (*drm, clearkey()): + assert drm_fields(drm_from_dict(json_copy(drm_to_dict(one)))) == drm_fields(one) + + +def test_attachments_round_trip_in_both_forms(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def fields(attachment: Attachment) -> tuple[Any, ...]: + return attachment.url, attachment.name, attachment.mime_type, attachment.description + + by_url = Attachment( + url="https://img.example/poster.jpg", name="Poster", mime_type="image/jpeg", description="Cover" + ) + for data in (serialize_attachment(by_url), attachment_to_dict(by_url)): + rebuilt = build_attachment(json_copy(data)) + assert rebuilt is not None + assert fields(rebuilt) == fields(by_url) + monkeypatch.setattr(config.directories, "temp", tmp_path / "temp") + poster = tmp_path / "poster.jpg" + poster.write_bytes(b"jpeg-bytes") + by_path = Attachment(path=poster, name="Poster", description="Cover") + rebuilt = build_attachment(json_copy(serialize_attachment(by_path))) + assert rebuilt is not None and rebuilt.path is not None + assert (fields(rebuilt), rebuilt.path.read_bytes()) == (fields(by_path), b"jpeg-bytes") + + +def test_an_attachment_over_the_inline_limit_is_skipped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(wire, "ATTACHMENT_INLINE_LIMIT", 4) + poster = tmp_path / "poster.jpg" + poster.write_bytes(b"jpeg-bytes") + assert serialize_attachment(Attachment(path=poster, name="Poster")) is None + + +def test_an_export_track_of_an_unhashable_type_is_refused_as_before() -> None: + with pytest.raises(TypeError, match=re.escape("cannot use 'dict' as a dict key")): + track_from_dict({**EXPORT_VIDEO, "type": {"a": 1}}) + + +RENAMED = {"range_": "range", "id_": "id", "title": "series_title"} +NOT_SENT = {"session", "downloader", "downloader_args", "from_file", "extra", "service", "data"} +NOT_EXPORTED = NOT_SENT | {"closed_captions", "drm", "description"} + + +def constructor_fields(cls: type) -> set[str]: + """The constructor parameters of a track or title class, under the name its wire form uses.""" + classes = [cls, Track] if issubclass(cls, Track) else [cls] + names = {name for c in classes for name in inspect.signature(c.__init__).parameters} + return {RENAMED.get(name, name) for name in names - {"self", "args", "kwargs"}} + + +@pytest.mark.parametrize( + "item, rest, export", + [ + (video, lambda t: serialize_video_track(t, include_url=True), track_to_dict), + (audio, lambda t: serialize_audio_track(t, include_url=True), track_to_dict), + (subtitle, lambda t: serialize_subtitle_track(t, include_url=True), track_to_dict), + (full_episode, serialize_title, title_to_meta), + (movie, serialize_title, title_to_meta), + (song, serialize_title, None), + ], + ids=["video", "audio", "subtitle", "episode", "movie", "song"], +) +def test_every_constructor_field_crosses_the_edge(item: Any, rest: Any, export: Any) -> None: + """A new constructor parameter fails here until a form carries it or a set above names it as not carried.""" + obj = item() + fields = constructor_fields(type(obj)) + assert fields - NOT_SENT - set(rest(obj)) == set() + if export is not None: + assert fields - NOT_EXPORTED - set(export(obj)) == set() + + +@pytest.mark.parametrize( + "module", + ["unshackle.core.wire", "unshackle.core.api", "unshackle.core.tracks", "unshackle.core.drm"], +) +def test_each_module_imports_first_in_a_new_interpreter(module: str) -> None: + """wire imports tracks, drm and titles, and they import wire inside their to_dict, so no order may cycle.""" + root = Path(__file__).resolve().parents[2] + result = subprocess.run([sys.executable, "-c", f"import {module}"], cwd=root, capture_output=True, check=False) + assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") diff --git a/tests/core/test_zero_kid_fallback.py b/tests/core/test_zero_kid_fallback.py index a91c3add..212e784e 100644 --- a/tests/core/test_zero_kid_fallback.py +++ b/tests/core/test_zero_kid_fallback.py @@ -8,8 +8,9 @@ import pytest from pyplayready.system.pssh import PSSH as PlayReadyPSSH from pywidevine.pssh import PSSH as WidevinePSSH -from unshackle.core.drm import PlayReady, Widevine, drm_from_dict, key_args +from unshackle.core.drm import PlayReady, Widevine, key_args from unshackle.core.drm.key_args import ZERO_KID +from unshackle.core.wire import drm_from_dict VIDEO_KID = UUID("00112233-4455-6677-8899-aabbccddeeff") AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100") diff --git a/tests/lang_selection/test_original_audio_ids.py b/tests/lang_selection/test_original_audio_ids.py index 2ad02f1e..c680617e 100644 --- a/tests/lang_selection/test_original_audio_ids.py +++ b/tests/lang_selection/test_original_audio_ids.py @@ -4,7 +4,7 @@ from typing import Optional import pytest -from unshackle.core.api.handlers import original_audio_ids +from unshackle.core.wire import original_audio_ids class FakeTrack: diff --git a/tests/remote/unit/test_api_availability.py b/tests/remote/unit/test_api_availability.py index 0d730d41..7260d65c 100644 --- a/tests/remote/unit/test_api_availability.py +++ b/tests/remote/unit/test_api_availability.py @@ -2,10 +2,9 @@ import pytest -from unshackle.core.api.handlers import serialize_title -from unshackle.core.remote_service import build_title from unshackle.core.titles.availability import availability_metadata from unshackle.core.titles.episode import Episode +from unshackle.core.wire import build_title, serialize_title pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_api_episode_part.py b/tests/remote/unit/test_api_episode_part.py index aa057869..5ba870e7 100644 --- a/tests/remote/unit/test_api_episode_part.py +++ b/tests/remote/unit/test_api_episode_part.py @@ -16,8 +16,8 @@ import pytest from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.api.handlers import serialize_title from unshackle.core.titles.episode import Episode +from unshackle.core.wire import build_title, serialize_title pytestmark = pytest.mark.unit @@ -116,8 +116,6 @@ def test_part_stays_out_of_the_name_field() -> None: def test_remote_build_title_round_trip() -> None: - from unshackle.core.remote_service import build_title - rebuilt = build_title(serialize_title(ep(1, 4, 2)), "FAKE", "fallback-id") assert (rebuilt.season, rebuilt.number, rebuilt.part, rebuilt.name) == (1, 4, 2, "Pilot") diff --git a/tests/remote/unit/test_api_title_fields.py b/tests/remote/unit/test_api_title_fields.py index e4e0b7b1..e66ad890 100644 --- a/tests/remote/unit/test_api_title_fields.py +++ b/tests/remote/unit/test_api_title_fields.py @@ -1,7 +1,7 @@ """The title fields that cross the remote wire: air_date, absolute, anime and daily. Covers serialize_title's conditional keys, the service-class ANIME/DAILY stamp, and the -serialize_title / title_to_meta round trips through remote_service.build_title. +serialize_title / title_to_meta round trips through wire.build_title. """ from __future__ import annotations @@ -16,11 +16,11 @@ from langcodes import Language from unshackle.commands.dl import dl from unshackle.core.api import handlers -from unshackle.core.api.handlers import serialize_title, stamp_service_flags -from unshackle.core.remote_service import build_title +from unshackle.core.api.handlers import stamp_service_flags from unshackle.core.titles.episode import Episode from unshackle.core.titles.movie import Movie from unshackle.core.titles.music import Song +from unshackle.core.wire import build_title, serialize_title pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_handlers_serialize.py b/tests/remote/unit/test_handlers_serialize.py index 98af0677..6541f78c 100644 --- a/tests/remote/unit/test_handlers_serialize.py +++ b/tests/remote/unit/test_handlers_serialize.py @@ -14,11 +14,6 @@ from unshackle.core.api.handlers import ( listed_titles, sanitize_log, search_handler, - serialize_audio_track, - serialize_drm, - serialize_subtitle_track, - serialize_title, - serialize_video_track, validate_download_parameters, validate_service, ) @@ -27,6 +22,13 @@ from unshackle.core.titles.episode import Episode from unshackle.core.titles.movie import Movie from unshackle.core.tracks import Audio, Subtitle, Video from unshackle.core.tracks.track import Track +from unshackle.core.wire import ( + serialize_audio_track, + serialize_drm, + serialize_subtitle_track, + serialize_title, + serialize_video_track, +) pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py index 8c984a02..6bf809ce 100644 --- a/tests/remote/unit/test_remote_service_helpers.py +++ b/tests/remote/unit/test_remote_service_helpers.py @@ -6,10 +6,12 @@ from enum import Enum import pytest -from unshackle.core.api.handlers import serialize_audio_track, serialize_subtitle_track, serialize_video_track from unshackle.core.manifests.snapshot import match_track -from unshackle.core.remote_service import ( - RemoteService, +from unshackle.core.remote_service import RemoteService +from unshackle.core.titles.episode import Episode +from unshackle.core.titles.movie import Movie +from unshackle.core.tracks import Audio, Subtitle, Video +from unshackle.core.wire import ( build_title, build_tracks, deserialize_audio, @@ -17,10 +19,12 @@ from unshackle.core.remote_service import ( deserialize_video, enum_get, reconstruct_drm, + serialize_audio_track, + serialize_subtitle_track, + serialize_video_track, + track_from_dict, + track_to_dict, ) -from unshackle.core.titles.episode import Episode -from unshackle.core.titles.movie import Movie -from unshackle.core.tracks import Audio, Subtitle, Video pytestmark = pytest.mark.unit @@ -64,14 +68,12 @@ def test_a_stereo_track_stays_3d_over_remote() -> None: def test_a_track_note_shows_over_remote_and_export_and_is_not_an_edition() -> None: - from unshackle.core.tracks.track import Track - v = Video(url="https://x/v.mp4", language="ja", codec=Video.Codec.AVC, note="h264mpl40-dash") a = Audio(url="https://x/a.mp4", language="ja", codec=Audio.Codec.AAC, note="heaac-2-dash") s = Subtitle(url="https://x/s.vtt", language="en", codec=Subtitle.Codec.WebVTT, note="webvtt-lssdh") copies = [deserialize_video(serialize_video_track(v)), deserialize_audio(serialize_audio_track(a))] copies += [deserialize_subtitle(serialize_subtitle_track(s))] - copies += [Track.from_dict(t.to_dict()) for t in (v, a, s)] + copies += [track_from_dict(track_to_dict(t)) for t in (v, a, s)] for copy in copies: assert copy.note and str(copy).endswith(f"| {copy.note}") assert copy.edition == [] diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index f862b0f8..f9dc8c8d 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -299,7 +299,7 @@ def test_reconstruct_drm_keeps_the_default_kid_of_a_pssh_without_kids(): from pywidevine.pssh import PSSH from unshackle.core.drm import real_kids - from unshackle.core.remote_service import reconstruct_drm + from unshackle.core.wire import reconstruct_drm content_id_only = PSSH.new(system_id=PSSH.SystemId.Widevine, init_data=b"\x22\x03abc") (drm,) = reconstruct_drm([{"type": "widevine", "pssh": content_id_only.dumps(), "kids": [str(KID)]}]) diff --git a/tests/remote/unit/test_session_reopen.py b/tests/remote/unit/test_session_reopen.py index 8af1a572..59b9468c 100644 --- a/tests/remote/unit/test_session_reopen.py +++ b/tests/remote/unit/test_session_reopen.py @@ -11,9 +11,10 @@ import requests import responses from langcodes import Language -from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, build_title, quiet +from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet from unshackle.core.tracks import Audio from unshackle.core.tracks.track import Track +from unshackle.core.wire import build_title pytestmark = pytest.mark.unit diff --git a/tests/tracks/test_audio_channel_layouts.py b/tests/tracks/test_audio_channel_layouts.py index 1dcded4b..ddffe119 100644 --- a/tests/tracks/test_audio_channel_layouts.py +++ b/tests/tracks/test_audio_channel_layouts.py @@ -10,6 +10,7 @@ from __future__ import annotations import pytest from unshackle.core.tracks import Audio +from unshackle.core.wire import track_from_dict, track_to_dict @pytest.mark.parametrize("layout", ["5.1.4", "7.1.2", "9.1.6"]) @@ -48,7 +49,7 @@ def test_a_value_that_is_no_layout_still_raises(value: str) -> None: def test_an_immersive_layout_round_trips_as_a_dict() -> None: """A remote download rebuilds every track from the dict the server sent.""" track = Audio(id_="a1", url="https://example.test/a", language="en", channels="5.1.4", bitrate=448000) - assert Audio.from_dict(track.to_dict()).channels == "5.1.4" + assert track_from_dict(track_to_dict(track)).channels == "5.1.4" @pytest.mark.parametrize( diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 2704c65c..2177b315 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -3726,40 +3726,9 @@ class dl: @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 datetime import date + from unshackle.core import wire - from unshackle.core.titles import Episode, Movie - - meta: dict[str, Any] = { - "id": str(title.id), - "language": str(title.language) if getattr(title, "language", None) else None, - } - if isinstance(title, Episode): - meta.update( - type="episode", - series_title=title.title, - season=title.season, - number=title.number, - name=title.name, - year=title.year, - air_date=title.air_date.isoformat() if isinstance(title.air_date, date) else title.air_date, - ) - # conditional, so meta for a title without them is unchanged - if title.part is not None: - meta["part"] = title.part - if title.absolute is not None: - meta["absolute"] = title.absolute - if getattr(title, "daily", None) is not None: - meta["daily"] = title.daily - if title.sport: - meta["sport"] = True - elif isinstance(title, Movie): - meta.update(type="movie", name=title.name, year=title.year) - else: - meta.update(type="movie", name=str(title)) - if getattr(title, "anime", None) is not None: - meta["anime"] = title.anime - return meta + 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. diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 08d8bcde..144aeb69 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -14,7 +14,6 @@ import zlib from collections import Counter from contextlib import suppress from dataclasses import dataclass, field -from datetime import date as date_ from functools import partial from http.cookiejar import CookieJar from pathlib import Path @@ -35,18 +34,15 @@ from unshackle.core.binaries import binary_version from unshackle.core.cacher import Cacher from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm from unshackle.core.config import config, load_yaml -from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP, AnyTrack +from unshackle.core.constants import AnyTrack from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key from unshackle.core.manifests.snapshot import capture from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.services import Services from unshackle.core.session import RnetSession, utf8_text -from unshackle.core.titles import Episode, Movie, Song, Title_T -from unshackle.core.titles.availability import availability_metadata -from unshackle.core.titles.music import MUSIC_DATA_KEYS, SONG_FIELDS, song_metadata -from unshackle.core.titles.title import rename -from unshackle.core.tracks import Audio, Subtitle, Tracks, Video +from unshackle.core.titles import Episode, Song +from unshackle.core.tracks import Video from unshackle.core.tunnel import ( HEARTBEAT, MAX_MESSAGE, @@ -57,12 +53,19 @@ from unshackle.core.tunnel import ( is_public_ip, tunnel_proxy, ) -from unshackle.core.utilities import declared_kwargs, kind_only_conflict, original_tag +from unshackle.core.utilities import declared_kwargs, kind_only_conflict from unshackle.core.utils.click_types import AUDIO_CODEC_LIST, QUALITY_LIST, VIDEO_CODEC_LIST from unshackle.core.utils.collections import ci_get, merge_dict from unshackle.core.utils.hdr10plus import probed_tracks from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options +from unshackle.core.wire import ( + descriptor_name, + serialize_attachment, + serialize_drm, + serialize_title, + serialize_tracks, +) log = logging.getLogger("api") @@ -1679,70 +1682,6 @@ def listed_titles(titles: Any) -> list[Any]: return list(titles) if hasattr(titles, "__iter__") and not isinstance(titles, str) else [titles] -def serialize_title(title: Title_T) -> Dict[str, Any]: - """Convert a title object to JSON-serializable dict.""" - title_language = str(title.language) if hasattr(title, "language") and title.language else None - # Optional display metadata a service may provide: a synopsis (title.description) and a - # release/air date or poster image URL stashed in title.data. Surfaced so a client can show - # a richer listing without re-fetching the page. - description = getattr(title, "description", None) or None - _data = getattr(title, "data", None) - availability = availability_metadata(_data.get("availability")) if isinstance(_data, dict) else None - date = _data.get("date") if isinstance(_data, dict) else None - cover_url = _data.get("cover_url") if isinstance(_data, dict) else None - - is_episode = isinstance(title, Episode) - is_song = isinstance(title, Song) - episode_part = title.part if isinstance(title, Episode) else None - if isinstance(title, Episode): - # no part suffix here: remote_service.build_title rebuilds the Episode from this dict, so a - # suffixed name plus the structural `part` below would render the part twice in the filename - name = title.name if title.name else f"Episode {title.number:02d}" - else: - name = str(title.name) if hasattr(title, "name") else str(title) - - result = { - "type": "episode" if is_episode else "movie" if isinstance(title, Movie) else "song" if is_song else "other", - "name": name, - "id": str(title.id) if hasattr(title, "id") else None, - "language": title_language, - "description": description, - "date": date, - "cover_url": cover_url, - } - # "other" titles carry no year; only Episode/Movie/Song do. - if isinstance(title, (Episode, Movie, Song)): - result["year"] = title.year - if isinstance(title, Episode): - result["series_title"] = str(title.title) - result["season"] = title.season - result["number"] = title.number - # every key below is conditional, so JSON for a title without them is unchanged - if episode_part is not None: - result["part"] = episode_part - if title.air_date is not None: - result["air_date"] = ( - title.air_date.isoformat() if isinstance(title.air_date, date_) else str(title.air_date) - ) - if title.absolute is not None: - result["absolute"] = title.absolute - if getattr(title, "daily", None) is not None: - result["daily"] = title.daily - if title.sport: - result["sport"] = True - if is_song: - for field in SONG_FIELDS: - result[field] = getattr(title, field, None) - metadata = song_metadata(title) - result["music_data"] = {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")} - if isinstance(title, (Episode, Movie)) and getattr(title, "anime", None) is not None: - result["anime"] = title.anime - - if availability is not None: - result["availability"] = availability - return result - - def stamp_service_flags(serialized: Dict[str, Any], service_instance: Any) -> Dict[str, Any]: """Fill anime/daily from the service class for titles that set neither. @@ -1757,68 +1696,6 @@ def stamp_service_flags(serialized: Dict[str, Any], service_instance: Any) -> Di return serialized -def serialize_drm(drm_list: Any) -> Optional[List[Dict[str, Any]]]: - """Serialise DRM objects to JSON-serializable list.""" - if not drm_list: - return None - - if not isinstance(drm_list, list): - drm_list = [drm_list] - - result = [] - for drm in drm_list: - drm_info = {} - drm_class = drm.__class__.__name__ - drm_info["type"] = drm_class.lower() - if isinstance(drm, BlowfishStripe): - drm_info["key"] = drm.key.hex() - - # pywidevine exposes dumps(); pyplayready's PSSH does not, so PlayReady falls back - # to the base64 it was built from. Without it the client drops every PlayReady - # entry and licenses the title with the wrong CDM. - pssh_obj = getattr(drm, "_pssh", None) - pssh_b64 = (getattr(drm, "data", None) or {}).get("pssh_b64") - if pssh_obj is not None and hasattr(pssh_obj, "dumps"): - try: - drm_info["pssh"] = pssh_obj.dumps() - except (ValueError, TypeError, KeyError): - log.warning( - "Failed to serialize PSSH for DRM type=%s pssh_type=%s", - drm_class, - type(pssh_obj).__name__, - exc_info=True, - ) - if not drm_info.get("pssh") and pssh_b64: - drm_info["pssh"] = pssh_b64 - - if hasattr(drm, "kids") and drm.kids: - drm_info["kids"] = [str(kid) for kid in drm.kids] - - if hasattr(drm, "content_keys") and drm.content_keys: - drm_info["content_keys"] = {str(k): v for k, v in drm.content_keys.items()} - - # Get license URL - essential for remote licensing - if hasattr(drm, "license_url") and drm.license_url: - drm_info["license_url"] = str(drm.license_url) - elif hasattr(drm, "_license_url") and drm._license_url: - drm_info["license_url"] = str(drm._license_url) - - result.append(drm_info) - - return result if result else None - - -def enum_name(value: Any) -> str: - """Return an enum-like value's .name, falling back to str().""" - return value.name if hasattr(value, "name") else str(value) - - -def descriptor_name(track: Any) -> Optional[str]: - """Manifest descriptor (HLS/DASH/URL) name for a track, or None.""" - descriptor = getattr(track, "descriptor", None) - return enum_name(descriptor) if descriptor else None - - def drm_preference_name(track: Any) -> Optional[str]: """The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset.""" preference = getattr(track, "drm_preference", None) @@ -1827,187 +1704,6 @@ def drm_preference_name(track: Any) -> Optional[str]: return {"wv": "widevine", "pr": "playready"}.get(preference, preference) -MANIFEST_DATA_KEYS = ("hls", "dash", "ism") - - -def serialize_track_data(track: Any) -> Optional[Dict[str, Any]]: - """The JSON-safe part of a service-set ``track.data``. - - This drops the manifest parsers' own keys: the client rebuilds those from the - ``manifests`` payload, and they hold live lxml and m3u8 objects that JSON cannot carry. - """ - data = getattr(track, "data", None) - if not isinstance(data, dict): - return None - safe: Dict[str, Any] = {} - for key, value in data.items(): - if key in MANIFEST_DATA_KEYS: - continue - try: - json.dumps(value) - except (TypeError, ValueError): - continue - safe[key] = value - return safe or None - - -def serialize_track_common(track: Any) -> Dict[str, Any]: - """The Track fields every track type shares, a superset of ``Track.to_dict()``.""" - return { - "id": str(track.id), - "language": str(track.language) if track.language else None, - "is_original_lang": bool(getattr(track, "is_original_lang", False)), - "name": getattr(track, "name", None), - "track_name": track.get_track_name(), - "needs_repack": bool(getattr(track, "needs_repack", False)), - "edition": list(getattr(track, "edition", None) or []), - "note": getattr(track, "note", None), - "descriptor": descriptor_name(track), - "drm": serialize_drm(track.drm) if getattr(track, "drm", None) else None, - "drm_preference": getattr(track, "drm_preference", None), - "data": serialize_track_data(track), - } - - -def serialize_tracks(tracks: Tracks, title: Any, include_url: bool = False) -> Dict[str, List[Dict[str, Any]]]: - """The ``video``, ``audio`` and ``subtitles`` lists of a title's tracks, video and audio highest bitrate first.""" - video_tracks = sorted(tracks.videos, key=lambda t: t.bitrate or 0, reverse=True) - audio_tracks = sorted(tracks.audio, key=lambda t: t.bitrate or 0, reverse=True) - original_ids = original_audio_ids(audio_tracks, title) - return { - "video": [serialize_video_track(t, include_url=include_url) for t in video_tracks], - "audio": [ - serialize_audio_track(t, include_url=include_url, is_original=t.id in original_ids) for t in audio_tracks - ], - "subtitles": [serialize_subtitle_track(t, include_url=include_url) for t in tracks.subtitles], - } - - -def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str, Any]: - """Convert video track to JSON-serializable dict.""" - codec_name = enum_name(track.codec) - codec_value = track.codec.value if track.codec else codec_name - range_name = enum_name(track.range) - - result = { - "id": str(track.id), - "codec": codec_name, - "codec_display": rename(VIDEO_CODEC_MAP.get(codec_name, codec_value)), - "bitrate": int(track.bitrate / 1000) if track.bitrate else None, - "bitrate_bps": track.bitrate or None, - "width": track.width, - "height": track.height, - "resolution": f"{track.width}x{track.height}" if track.width and track.height else None, - "fps": track.fps if track.fps else None, - "range": range_name, - "range_display": "+".join(rename(DYNAMIC_RANGE_MAP.get(p, p)) for p in track.range_label.split("+")), - "scan_type": enum_name(track.scan_type) if track.scan_type else None, - "closed_captions": list(getattr(track, "closed_captions", None) or []), - "dv_compatible_bitstream": bool(getattr(track, "dv_compatible_bitstream", False)), - "hdr10plus": bool(getattr(track, "hdr10plus", False)), - "hdr10_base": bool(getattr(track, "hdr10_base", False)), - "stereo": bool(getattr(track, "stereo", False)), - } - result.update(serialize_track_common(track)) - if include_url and hasattr(track, "url") and track.url: - result["url"] = str(track.url) - return result - - -def original_audio_ids(tracks: List[Audio], title: Title_T) -> set: - """Return the ids of the audio tracks 'orig' resolves to, empty when the title has no language. - - This defers to Tracks.by_language through original_tag, as 'orig' does, so the flag agrees - with the downloader: the title's own variant first, else its close regional forms. - """ - language = getattr(title, "language", None) - if not language: - return set() - return {t.id for t in Tracks.by_language(tracks, [original_tag(language)])} - - -def serialize_audio_track(track: Audio, include_url: bool = False, is_original: bool = False) -> Dict[str, Any]: - """Convert audio track to JSON-serializable dict. - - Get is_original from original_audio_ids so the flag always agrees with the - track 'orig' would download. - """ - codec_name = enum_name(track.codec) - codec_value = track.codec.value if track.codec else codec_name - - result = { - "id": str(track.id), - "codec": codec_name, - "codec_display": rename(AUDIO_CODEC_MAP.get(codec_value, codec_value)), - "bitrate": int(track.bitrate / 1000) if track.bitrate else None, - "bitrate_bps": track.bitrate or None, - "channels": track.channels if track.channels else None, - "is_original": is_original, - "atmos": track.atmos if hasattr(track, "atmos") else False, - "joc": getattr(track, "joc", 0), - "descriptive": track.descriptive if hasattr(track, "descriptive") else False, - } - result.update(serialize_track_common(track)) - if include_url and hasattr(track, "url") and track.url: - result["url"] = str(track.url) - return result - - -def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> Dict[str, Any]: - """Convert subtitle track to JSON-serializable dict.""" - result = { - "id": str(track.id), - "codec": enum_name(track.codec), - "forced": track.forced if hasattr(track, "forced") else False, - "sdh": track.sdh if hasattr(track, "sdh") else False, - "cc": track.cc if hasattr(track, "cc") else False, - } - result.update(serialize_track_common(track)) - if include_url and hasattr(track, "url") and track.url: - result["url"] = str(track.url) - return result - - -ATTACHMENT_INLINE_LIMIT = 20 * 1024 * 1024 - - -def serialize_attachment(attachment: Any) -> Optional[Dict[str, Any]]: - """One attachment as JSON, with a path-only attachment carried as base64 file bytes. - - A service can attach a file it already wrote to disk (a font, a poster). The client - has no access to the server's filesystem, so those bytes travel inline. - """ - result: Dict[str, Any] = { - "url": attachment.url, - "name": attachment.name, - "mime_type": attachment.mime_type, - "description": attachment.description, - } - if attachment.url: - return result - - path = getattr(attachment, "path", None) - if not path: - return None - path = Path(path) - try: - size = path.stat().st_size - if size > ATTACHMENT_INLINE_LIMIT: - log.warning( - "Skipping attachment %s: %d bytes is over the %d byte inline limit", - sanitize_log(path.name), - size, - ATTACHMENT_INLINE_LIMIT, - ) - return None - result["content"] = base64.b64encode(path.read_bytes()).decode("ascii") - except OSError as e: - log.warning("Skipping attachment %s: %s", sanitize_log(path.name), e) - return None - result["file_name"] = path.name - return result - - async def search_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response: """Answer the request to find titles.""" service_tag = data.get("service") diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index a81af995..cfbeec44 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -46,7 +46,6 @@ from unshackle.core.api.handlers import ( download_history_handler, download_job_events_handler, download_job_input_handler, - enum_name, env_check_handler, get_allowed_services, get_download_job_handler, @@ -89,6 +88,7 @@ from unshackle.core.tunnel import ROUTE as TUNNEL_ROUTE from unshackle.core.tunnel import close_tunnels from unshackle.core.update_checker import UpdateChecker from unshackle.core.utils.redact import redact_path +from unshackle.core.wire import enum_name @web.middleware diff --git a/unshackle/core/drm/__init__.py b/unshackle/core/drm/__init__.py index 22bcc3cd..cae582ad 100644 --- a/unshackle/core/drm/__init__.py +++ b/unshackle/core/drm/__init__.py @@ -1,4 +1,3 @@ -import base64 from typing import Any, Union from uuid import UUID @@ -14,43 +13,6 @@ from unshackle.core.vault import is_null_key DRM_T = Union[ClearKey, ClearKeyCENC, Widevine, PlayReady, MonaLisa] -def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady, ClearKeyCENC]: - """Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its ``to_dict()`` form. - - Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH) - and re-injects any saved content keys so the resulting object can decrypt without - contacting a license server. - """ - system = data.get("system") - pssh_b64 = data.get("pssh_b64") - kids = data.get("kids") or [] - content_keys = data.get("content_keys") or {} - - if system == "ClearKeyCENC": - drm: Union[Widevine, PlayReady, ClearKeyCENC] = ClearKeyCENC(kids=kids, laurl=data.get("laurl")) - elif not pssh_b64: - raise ValueError("Cannot reconstruct DRM without a stored PSSH.") - elif system == "PlayReady": - from pyplayready.system.pssh import PSSH as PlayReadyPSSH - - drm = PlayReady(pssh=PlayReadyPSSH(base64.b64decode(pssh_b64)), pssh_b64=pssh_b64) - elif system == "Widevine": - from pywidevine.pssh import PSSH as WidevinePSSH - - wv_pssh = WidevinePSSH(pssh_b64) - # kids repeats the PSSH KIDs, so kids[0] is not the track's own KID; only a PSSH - # without KIDs needs it - - drm = Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None) - else: - raise ValueError(f"Unsupported DRM system for reconstruction: {system!r}") - - for kid_hex, key in content_keys.items(): - drm.content_keys[UUID(hex=kid_hex)] = key - - return drm - - def drop_null_keys(drm: Any) -> None: """Remove the null keys from a DRM object's content keys. A read-only key view stays as it is.""" content_keys = getattr(drm, "content_keys", None) @@ -79,7 +41,6 @@ __all__ = ( "PlayReady", "MonaLisa", "DRM_T", - "drm_from_dict", "drop_null_keys", "is_null_key", "real_kids", diff --git a/unshackle/core/drm/clearkey_cenc.py b/unshackle/core/drm/clearkey_cenc.py index 543aa178..d93ac809 100644 --- a/unshackle/core/drm/clearkey_cenc.py +++ b/unshackle/core/drm/clearkey_cenc.py @@ -64,18 +64,10 @@ class ClearKeyCENC: return next(iter(self.kids), None) def to_dict(self) -> dict[str, Any]: - """Serialise this DRM instance for export/import (KIDs + license URL). + """This DRM in the export form; see ``wire.drm_to_dict``.""" + from unshackle.core.wire import drm_to_dict - unshackle stores the content keys once at the export's track level, and does not - duplicate them here. - """ - data: dict[str, Any] = { - "system": "ClearKeyCENC", - "kids": [kid.hex for kid in self.kids], - } - if self.laurl: - data["laurl"] = self.laurl - return data + return drm_to_dict(self) def get_license_challenge(self) -> bytes: """Assemble the W3C EME ClearKey JSON license request for the unkeyed KIDs.""" diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py index 29b2fa08..884fab9d 100644 --- a/unshackle/core/drm/playready.py +++ b/unshackle/core/drm/playready.py @@ -270,16 +270,10 @@ class PlayReady: return next(iter(self.kids), None) def to_dict(self) -> dict[str, Any]: - """Serialise this DRM instance for export/import (PSSH + KIDs). + """This DRM in the export form; see ``wire.drm_to_dict``.""" + from unshackle.core.wire import drm_to_dict - unshackle stores the content keys once at the export's track level, and does not - duplicate them here. - """ - return { - "system": "PlayReady", - "pssh_b64": self.pssh_b64, - "kids": [kid.hex for kid in self.kids], - } + return drm_to_dict(self) @property def kids(self) -> list[UUID]: diff --git a/unshackle/core/drm/widevine.py b/unshackle/core/drm/widevine.py index 68ed69be..d50a7d3a 100644 --- a/unshackle/core/drm/widevine.py +++ b/unshackle/core/drm/widevine.py @@ -200,16 +200,10 @@ class Widevine: return [] def to_dict(self) -> dict[str, Any]: - """Serialise this DRM instance for export/import (PSSH + KIDs). + """This DRM in the export form; see ``wire.drm_to_dict``.""" + from unshackle.core.wire import drm_to_dict - unshackle stores the content keys once at the export's track level, and does not - duplicate them here. - """ - return { - "system": "Widevine", - "pssh_b64": self.pssh.dumps(), - "kids": [kid.hex for kid in self.kids], - } + return drm_to_dict(self) def get_content_keys(self, cdm: WidevineCdm, certificate: Callable, licence: Callable) -> None: """ diff --git a/unshackle/core/import_service.py b/unshackle/core/import_service.py index 18c5ccac..597c4496 100644 --- a/unshackle/core/import_service.py +++ b/unshackle/core/import_service.py @@ -16,21 +16,16 @@ from langcodes import tag_is_valid from unshackle.core.config import config from unshackle.core.constants import AnyTrack from unshackle.core.credential import Credential -from unshackle.core.drm import ClearKey, MonaLisa, drm_from_dict, real_kids +from unshackle.core.drm import ClearKey, MonaLisa, real_kids from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot -from unshackle.core.remote_service import ( - RemoteService, - ServerKeySource, - build_title, - resolve_proxy_arg, - segment_uri_filter, -) +from unshackle.core.remote_service import RemoteService, ServerKeySource, resolve_proxy_arg, segment_uri_filter from unshackle.core.session import utf8_text from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video from unshackle.core.tracks.attachment import Attachment from unshackle.core.tracks.track import Track from unshackle.core.utils import run_proxy +from unshackle.core.wire import build_title, drm_from_dict, track_from_dict log = logging.getLogger("import") E = TypeVar("E", bound=Enum) @@ -465,7 +460,7 @@ class ImportService: for track_dict in track_dicts: try: - track = Track.from_dict(track_dict) + track = track_from_dict(track_dict) except Exception as e: self.log.warning(f"Skipping exported track {track_dict.get('id')!r}: {e}") continue diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 3c7777d2..30136967 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -20,10 +20,7 @@ import shlex import sys import time from collections import deque -from datetime import date as date_ -from enum import Enum from http.cookiejar import CookieJar -from pathlib import Path from threading import Event, Lock, Thread, local from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Protocol, TypeVar, Union from urllib.parse import urlencode, urlsplit @@ -32,7 +29,6 @@ from uuid import UUID import click import requests import urllib3 -from langcodes import Language from requests.adapters import HTTPAdapter, Retry from rich.padding import Padding from rich.rule import Rule @@ -42,18 +38,16 @@ from unshackle.core.config import config from unshackle.core.console import SyncLive, console, prompt_user, show_notice from unshackle.core.constants import AnyTrack from unshackle.core.credential import Credential -from unshackle.core.drm import BlowfishStripe, cbcs, real_kids +from unshackle.core.drm import cbcs, real_kids from unshackle.core.manifests.snapshot import match_track, restore from unshackle.core.proxies.resolve import is_loopback from unshackle.core.search_result import SearchResult from unshackle.core.session import MAX_BACKOFF from unshackle.core.titles import Title_T, Titles_T, remap_titles -from unshackle.core.titles.availability import availability_metadata from unshackle.core.titles.episode import Episode, Series -from unshackle.core.titles.movie import Movie, Movies -from unshackle.core.titles.music import MUSIC_DATA_KEYS, SONG_FIELDS, Album, Song -from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video -from unshackle.core.tracks.attachment import Attachment +from unshackle.core.titles.movie import Movies +from unshackle.core.titles.music import Album, Song +from unshackle.core.tracks import Chapter, Chapters, Tracks from unshackle.core.tracks.track import Track from unshackle.core.tunnel import PROXY_PORTS, TunnelClient, parse_retry_after from unshackle.core.utils import run_proxy @@ -61,6 +55,7 @@ from unshackle.core.utils.collections import ci_get from unshackle.core.utils.redact import redact_path, redact_text, safe_display_url from unshackle.core.utils.service_params import service_options from unshackle.core.vault import Vault +from unshackle.core.wire import apply_title_fields, build_title, build_tracks log = logging.getLogger("remote_service") @@ -306,16 +301,6 @@ class RemoteClient: return self.request("delete", endpoint) -def enum_get(enum_cls: type[Enum], name: Optional[str], default: Any = None) -> Any: - """Safely get an enum value by name.""" - if not name: - return default - try: - return enum_cls[name] - except KeyError: - return default - - def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]: """Split samples into consecutive batches of at most cbcs.SAMPLE_BATCH_BYTES (a larger sample goes alone).""" batch: list[bytes] = [] @@ -330,74 +315,6 @@ def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]: yield batch -def base_track_kwargs(data: Dict[str, Any]) -> Dict[str, Any]: - """The shared Track constructor kwargs a serialized track carries. - - An older server omits the newer keys, so each one falls back to the value a - locally-built track would have had. - """ - return { - "url": data.get("url") or "https://placeholder", - "language": Language.get(data.get("language") or "und"), - "is_original_lang": bool(data.get("is_original_lang", data.get("is_original", False))), - "descriptor": enum_get(Track.Descriptor, data.get("descriptor"), Track.Descriptor.URL), - "needs_repack": bool(data.get("needs_repack", False)), - "name": data.get("name"), - "edition": data.get("edition") or None, - "note": data["note"] if isinstance(data.get("note"), str) else None, - "id_": data.get("id"), - } - - -def deserialize_bitrate(data: Dict[str, Any]) -> int: - """Exact bits/s when the server sent it, otherwise the kb/s figure scaled back up.""" - exact = data.get("bitrate_bps") - if exact: - return int(exact) - return data["bitrate"] * 1000 if data.get("bitrate") else 0 - - -def deserialize_video(data: Dict[str, Any]) -> Video: - return Video( - **base_track_kwargs(data), - codec=enum_get(Video.Codec, data.get("codec")), - range_=enum_get(Video.Range, data.get("range"), Video.Range.SDR), - bitrate=deserialize_bitrate(data), - width=data.get("width") or 0, - height=data.get("height") or 0, - fps=data.get("fps"), - scan_type=enum_get(Video.ScanType, data.get("scan_type")), - closed_captions=data.get("closed_captions") or None, - dv_compatible_bitstream=bool(data.get("dv_compatible_bitstream", False)), - hdr10plus=bool(data.get("hdr10plus", False)), - hdr10_base=bool(data.get("hdr10_base", False)), - stereo=bool(data.get("stereo", False)), - ) - - -def deserialize_audio(data: Dict[str, Any]) -> Audio: - joc = data.get("joc") - return Audio( - **base_track_kwargs(data), - codec=enum_get(Audio.Codec, data.get("codec")), - bitrate=deserialize_bitrate(data), - channels=data.get("channels"), - joc=joc, - extra={"atmos": True} if joc is None and data.get("atmos") else None, - descriptive=data.get("descriptive", False), - ) - - -def deserialize_subtitle(data: Dict[str, Any]) -> Subtitle: - return Subtitle( - **base_track_kwargs(data), - codec=enum_get(Subtitle.Codec, data.get("codec")), - cc=data.get("cc", False), - sdh=data.get("sdh", False), - forced=data.get("forced", False), - ) - - def track_pssh(track: Any, drm_type: str) -> Optional[str]: """The base64 PSSH of the track's header for one DRM system; None when the track has none of it.""" for drm_obj in track.drm or []: @@ -409,91 +326,6 @@ def track_pssh(track: Any, drm_type: str) -> Optional[str]: return None -def reconstruct_drm(drm_list: Optional[list]) -> list: - """Reconstruct DRM objects from serialized API data.""" - if not drm_list: - return [] - result: list[Any] = [] - for drm_info in drm_list: - drm_type = drm_info.get("type", "") - pssh_str = drm_info.get("pssh") - if not pssh_str and drm_type != "blowfishstripe": - continue - try: - if drm_type == "blowfishstripe": - result.append(BlowfishStripe(drm_info["key"])) - elif drm_type == "widevine": - from pywidevine.pssh import PSSH as WidevinePSSH - - from unshackle.core.drm import Widevine - - wv_pssh = WidevinePSSH(pssh_str) - kids = drm_info.get("kids") - result.append(Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None)) - elif drm_type == "playready": - import base64 as b64 - - from pyplayready.system.pssh import PSSH as PlayReadyPSSH - - from unshackle.core.drm import PlayReady - - pr_pssh = PlayReadyPSSH(b64.b64decode(pssh_str)) - result.append(PlayReady(pssh=pr_pssh, pssh_b64=pssh_str)) - # a dropped entry can leave the track with no DRM, so never skip silently - except Exception as e: - log.warning(f"Skipping unparseable {drm_type} DRM entry from server: {e!r}") - continue - return result - - -def build_attachment(data: Dict[str, Any]) -> Optional[Attachment]: - """Rebuild one attachment. A path-only attachment arrives as base64, which this writes to temp.""" - kwargs = { - "name": data.get("name"), - "mime_type": data.get("mime_type"), - "description": data.get("description"), - } - if data.get("url"): - return Attachment(url=data["url"], **kwargs) - - content = data.get("content") - if not content: - return None - try: - file_name = Path(str(data.get("file_name") or data.get("name") or "attachment")).name - target = config.directories.temp / "remote_attachments" / file_name - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(base64.b64decode(content)) - return Attachment(path=target, **kwargs) - except (OSError, ValueError) as e: - log.warning(f"Skipping attachment {data.get('name')!r} sent by the server: {e}") - return None - - -def build_tracks(data: Dict[str, Any]) -> Tracks: - tracks = Tracks() - tracks.videos = [deserialize_video(v) for v in data.get("video", [])] - tracks.audio = [deserialize_audio(a) for a in data.get("audio", [])] - tracks.subtitles = [deserialize_subtitle(s) for s in data.get("subtitles", [])] - - for track_data, track_obj in [ - *zip(data.get("video", []), tracks.videos), - *zip(data.get("audio", []), tracks.audio), - *zip(data.get("subtitles", []), tracks.subtitles), - ]: - drm_objs = reconstruct_drm(track_data.get("drm")) - if drm_objs: - track_obj.drm = drm_objs - preference = track_data.get("drm_preference") - if preference: - try: - track_obj.drm_preference = preference - except ValueError: - log.warning(f"Ignoring unknown drm_preference {preference!r} from the server for track {track_obj.id}") - tracks.attachments = [a for a in map(build_attachment, data.get("attachments", [])) if a] - return tracks - - def apply_service_track_data(tracks: Tracks, data: Dict[str, Any]) -> None: """Overlay the service-set ``track.data`` the server sent. @@ -546,135 +378,6 @@ def segment_uri_filter(uris: Iterable[Any]) -> Callable[[Any], bool]: return segment_filter -EPISODE_PLACEHOLDER_NAME = re.compile(r"Episode ?#?\d+", re.IGNORECASE) - - -def episode_name(name: Optional[str], series_title: Optional[str]) -> Optional[str]: - """Drop a placeholder episode name the way ``Episode.__init__`` does. - - The server sends "Episode 04" for an unnamed episode, so the same filter has to run - again here, or the placeholder reaches the output file name. - """ - if not name: - return None - name = name.strip() - if EPISODE_PLACEHOLDER_NAME.match(name): - return None - if series_title and name.lower() == series_title.lower(): - return None - return name - - -def parse_air_date(value: Any) -> Any: - """ISO date string back to a date, as ``Episode.__init__`` does; anything else passes through.""" - if isinstance(value, str): - try: - return date_.fromisoformat(value[:10]) - except ValueError: - return value - return value - - -def apply_title_fields(title: Title_T, info: Dict[str, Any]) -> None: - """Copy the serialized metadata fields onto a local title. - - A service can change its title inside ``get_tracks`` (a corrected original language, - a real episode name, an air date), so the client re-applies the server's view of the - title after every call that returns one. Season, number and part are set only by - ``build_title``, as dl can renumber them after the listing. - """ - if info.get("language"): - title.language = Language.get(info["language"]) - if info.get("description") is not None and isinstance(title, (Episode, Movie)): - title.description = info["description"] - if info.get("year") is not None: - title.year = info["year"] - - if isinstance(title, Episode): - if info.get("series_title"): - title.title = info["series_title"] - if "name" in info: - title.name = episode_name(info["name"], title.title) - if info.get("absolute") is not None: - title.absolute = info["absolute"] - if info.get("air_date") is not None: - title.air_date = parse_air_date(info["air_date"]) - elif info.get("name"): - title.name = info["name"] - - for key in ("anime", "daily", "sport", *(SONG_FIELDS if isinstance(title, Song) else ())): - if info.get(key) is not None: - setattr(title, key, info[key]) - - extra = {k: info[k] for k in ("date", "cover_url") if info.get(k) is not None} - availability = availability_metadata(info.get("availability")) - if availability is not None: - extra["availability"] = availability - music_data = info.get("music_data") - if isinstance(music_data, dict): - extra.update({key: music_data[key] for key in MUSIC_DATA_KEYS if key in music_data}) - if extra: - if isinstance(title.data, dict): - title.data.update(extra) - else: - title.data = extra - - -def build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Title_T: - svc_class = type(service_tag, (), {}) - lang = Language.get(info["language"]) if info.get("language") else None - title_type = info.get("type") - title: Title_T - if title_type == "episode": - title = Episode( - id_=info.get("id", fallback_id), - service=svc_class, - title=info.get("series_title", "Unknown"), - season=info.get("season", 0), - number=info.get("number", 0), - part=info.get("part"), - language=lang, - ) - elif title_type == "movie": - title = Movie( - id_=info.get("id", fallback_id), - service=svc_class, - name=info.get("name") or "Unknown", - language=lang, - ) - elif title_type == "song": - title = Song( - id_=info.get("id", fallback_id), - service=svc_class, - name=info.get("name") or "Unknown", - artist=info.get("artist") or "Unknown", - album=info.get("album") or "Unknown", - track=info.get("track") or 1, - disc=info.get("disc") or 1, - language=lang, - album_artist=info.get("album_artist"), - release_type=info.get("release_type") or "album", - total_tracks=info.get("total_tracks"), - total_discs=info.get("total_discs"), - genre=info.get("genre"), - explicit=info.get("explicit"), - isrc=info.get("isrc"), - upc=info.get("upc"), - copyright=info.get("copyright"), - label=info.get("label"), - lyrics=info.get("lyrics"), - artwork_url=info.get("artwork_url"), - synced_lyrics=info.get("synced_lyrics"), - lyrics_suffix=info.get("lyrics_suffix"), - ) - else: - raise click.ClickException( - f"The remote server sent an unknown title type {title_type!r}; unshackle versions differ" - ) - apply_title_fields(title, info) - return title - - def title_key(title: Title_T) -> tuple: """What tells a title apart from the others in one listing, other than its id: a service may vary the id per listing.""" if isinstance(title, Episode): diff --git a/unshackle/core/tracks/attachment.py b/unshackle/core/tracks/attachment.py index 158239fb..3279fd67 100644 --- a/unshackle/core/tracks/attachment.py +++ b/unshackle/core/tracks/attachment.py @@ -136,8 +136,10 @@ class Attachment: return " | ".join(filter(None, ["ATT", self.name, self.mime_type, self.description])) def to_dict(self) -> dict[str, Optional[str]]: - """Serialise a URL-backed attachment for export/import.""" - return {"url": self.url, "name": self.name, "mime_type": self.mime_type, "description": self.description} + """The attachment in the export form; see ``wire.attachment_to_dict``.""" + from unshackle.core.wire import attachment_to_dict + + return attachment_to_dict(self) @property def id(self) -> str: diff --git a/unshackle/core/tracks/audio.py b/unshackle/core/tracks/audio.py index 4aacba87..1a2eca48 100644 --- a/unshackle/core/tracks/audio.py +++ b/unshackle/core/tracks/audio.py @@ -184,31 +184,6 @@ class Audio(Track): self.joc = joc self.descriptive = bool(descriptive) - def to_dict(self) -> dict[str, Any]: - data = super().to_dict() - data.update( - { - "codec": self.codec.name if self.codec else None, - "bitrate": self.bitrate, - "channels": self.channels, - "joc": self.joc, - "descriptive": self.descriptive, - } - ) - return data - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Audio: - kwargs = Track.base_kwargs_from_dict(data) - return cls( - **kwargs, - codec=Audio.Codec[data["codec"]] if data.get("codec") else None, - bitrate=data.get("bitrate"), - channels=data.get("channels"), - joc=data.get("joc"), - descriptive=data.get("descriptive", False), - ) - @property def atmos(self) -> bool: """Return True if the audio track contains Atmos.""" diff --git a/unshackle/core/tracks/subtitle.py b/unshackle/core/tracks/subtitle.py index 2bf21599..0af9686b 100644 --- a/unshackle/core/tracks/subtitle.py +++ b/unshackle/core/tracks/subtitle.py @@ -199,29 +199,6 @@ class Subtitle(Track): # Called after Track has been converted to another format self.OnConverted: Optional[Callable[[Subtitle.Codec], None]] = None - def to_dict(self) -> dict[str, Any]: - data = super().to_dict() - data.update( - { - "codec": self.codec.name if self.codec else None, - "cc": self.cc, - "sdh": self.sdh, - "forced": self.forced, - } - ) - return data - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Subtitle: - kwargs = Track.base_kwargs_from_dict(data) - return cls( - **kwargs, - codec=Subtitle.Codec[data["codec"]] if data.get("codec") else None, - cc=data.get("cc", False), - sdh=data.get("sdh", False), - forced=data.get("forced", False), - ) - @property def mux_language(self) -> Language: """The language tag written to the output file, with the script its region implies.""" diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 19b1dfc4..453ffc29 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -975,57 +975,10 @@ class Track: return target def to_dict(self) -> dict[str, Any]: - """Serialise the track for export/import (identity/URL/descriptor/language). + """The track in the export form; see ``wire.track_to_dict``.""" + from unshackle.core.wire import track_to_dict - DRM is not serialised here. The export writer attaches the licensed DRM + keys. - Subclasses add their own codec/quality fields. - """ - data: dict[str, Any] = { - "type": self.__class__.__name__, - "id": self.id, - "url": self.url, - "language": str(self.language), - "is_original_lang": self.is_original_lang, - "descriptor": self.descriptor.name, - "needs_repack": self.needs_repack, - "name": self.name, - "edition": self.edition, - "note": self.note, - } - return data - - @staticmethod - def base_kwargs_from_dict(data: dict[str, Any]) -> dict[str, Any]: - """Assemble the shared Track constructor kwargs from a ``to_dict()`` payload. - - DRM is not reconstructed here: ``to_dict`` does not serialise it, and the import - flow attaches the licensed DRM + content keys separately. - """ - return { - "url": data["url"], - "language": data.get("language") or "und", - "is_original_lang": data.get("is_original_lang", False), - "descriptor": Track.Descriptor[data.get("descriptor", "URL")], - "needs_repack": data.get("needs_repack", False), - "name": data.get("name"), - "edition": data.get("edition") or None, - "note": data.get("note"), - "id_": data.get("id"), - } - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> "Track": - """Reconstruct the correct Track subclass from a ``to_dict()`` payload.""" - from unshackle.core.tracks.audio import Audio - from unshackle.core.tracks.subtitle import Subtitle - from unshackle.core.tracks.video import Video - - track_type = data.get("type") - builders: dict[Optional[str], type[Track]] = {"Video": Video, "Audio": Audio, "Subtitle": Subtitle} - builder = builders.get(track_type) - if builder is None: - raise ValueError(f"Cannot reconstruct unsupported track type: {track_type!r}") - return builder.from_dict(data) + return track_to_dict(self) @property def mux_language(self) -> Language: diff --git a/unshackle/core/tracks/video.py b/unshackle/core/tracks/video.py index 0333e18a..f30b36d6 100644 --- a/unshackle/core/tracks/video.py +++ b/unshackle/core/tracks/video.py @@ -307,43 +307,6 @@ class Video(Track): self.hybrid_ingredient = False self.native_hybrid = False - def to_dict(self) -> dict[str, Any]: - data = super().to_dict() - data.update( - { - "codec": self.codec.name if self.codec else None, - "range": self.range.name if self.range else None, - "bitrate": self.bitrate, - "width": self.width, - "height": self.height, - "fps": str(self.fps) if self.fps else None, - "scan_type": self.scan_type.name if self.scan_type else None, - "dv_compatible_bitstream": self.dv_compatible_bitstream, - "hdr10plus": self.hdr10plus, - "hdr10_base": self.hdr10_base, - "stereo": self.stereo, - } - ) - return data - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Video: - kwargs = Track.base_kwargs_from_dict(data) - return cls( - **kwargs, - codec=Video.Codec[data["codec"]] if data.get("codec") else None, - range_=Video.Range[data["range"]] if data.get("range") else None, - bitrate=data.get("bitrate"), - width=data.get("width"), - height=data.get("height"), - fps=data.get("fps"), - scan_type=Video.ScanType[data["scan_type"]] if data.get("scan_type") else None, - dv_compatible_bitstream=data.get("dv_compatible_bitstream", False), - hdr10plus=data.get("hdr10plus", False), - hdr10_base=data.get("hdr10_base", False), - stereo=data.get("stereo", False), - ) - @staticmethod def dv_fourccs(codecs: Optional[str]) -> set[str]: """The Dolby Vision fourccs in a codecs list (comma or space separated, ``/brand`` suffixes allowed).""" diff --git a/unshackle/core/wire.py b/unshackle/core/wire.py new file mode 100644 index 00000000..0fce9744 --- /dev/null +++ b/unshackle/core/wire.py @@ -0,0 +1,854 @@ +"""The wire form of a title, its tracks, their DRM and attachments: what crosses a process edge. + +Two forms cross it. The REST form is the JSON of the REST API and ``--remote``. The export form is the +``x-unshackle`` block of an export file. Each encoder sits next to its decoder. The REST form also carries +display labels, licence data and service data, and the export form only constructor values, so each +form keeps its own field names, field order and value formats. The title and a PSSH have one decoder for +both forms, and the export form of an attachment is the REST form of a URL attachment. Of the Track +constructor fields, only the name, edition and id decode the same way: the REST form tolerates a peer of +another version, and the export form refuses a malformed value. +""" + +from __future__ import annotations + +import base64 +import json +import logging +import re +from datetime import date as date_ +from enum import Enum +from pathlib import Path +from typing import Any, Dict, List, Optional, Union +from uuid import UUID + +import click +from langcodes import Language +from pyplayready.system.pssh import PSSH as PlayReadyPSSH +from pywidevine.pssh import PSSH as WidevinePSSH + +from unshackle.core.config import config +from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP +from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine +from unshackle.core.titles import Episode, Movie, Song, Title_T +from unshackle.core.titles.availability import availability_metadata +from unshackle.core.titles.music import MUSIC_DATA_KEYS, SONG_FIELDS, song_metadata +from unshackle.core.titles.title import rename +from unshackle.core.tracks import Audio, Subtitle, Tracks, Video +from unshackle.core.tracks.attachment import Attachment +from unshackle.core.tracks.track import Track +from unshackle.core.utilities import original_tag + +# the encoders run on the server and the decoders on the client: each keeps the logger it had +server_log = logging.getLogger("api") +client_log = logging.getLogger("remote_service") + +EPISODE_PLACEHOLDER_NAME = re.compile(r"Episode ?#?\d+", re.IGNORECASE) +MANIFEST_DATA_KEYS = ("hls", "dash", "ism") +ATTACHMENT_INLINE_LIMIT = 20 * 1024 * 1024 + + +def enum_name(value: Any) -> str: + """Return an enum-like value's .name, falling back to str().""" + return value.name if hasattr(value, "name") else str(value) + + +def enum_get(enum_cls: type[Enum], name: Optional[str], default: Any = None) -> Any: + """Safely get an enum value by name.""" + if not name: + return default + try: + return enum_cls[name] + except KeyError: + return default + + +def descriptor_name(track: Any) -> Optional[str]: + """Manifest descriptor (HLS/DASH/URL) name for a track, or None.""" + descriptor = getattr(track, "descriptor", None) + return enum_name(descriptor) if descriptor else None + + +def episode_flags(title: Episode) -> Dict[str, Any]: + """The optional Episode keys both forms write only when set, so the JSON of a title without them stays the same.""" + flags: Dict[str, Any] = {} + if title.absolute is not None: + flags["absolute"] = title.absolute + if getattr(title, "daily", None) is not None: + flags["daily"] = title.daily + if title.sport: + flags["sport"] = True + return flags + + +def serialize_title(title: Title_T) -> Dict[str, Any]: + """Convert a title object to JSON-serializable dict.""" + title_language = str(title.language) if hasattr(title, "language") and title.language else None + # Optional display metadata a service may provide: a synopsis (title.description) and a + # release/air date or poster image URL stashed in title.data. Surfaced so a client can show + # a richer listing without re-fetching the page. + description = getattr(title, "description", None) or None + _data = getattr(title, "data", None) + availability = availability_metadata(_data.get("availability")) if isinstance(_data, dict) else None + date = _data.get("date") if isinstance(_data, dict) else None + cover_url = _data.get("cover_url") if isinstance(_data, dict) else None + + is_episode = isinstance(title, Episode) + is_song = isinstance(title, Song) + episode_part = title.part if isinstance(title, Episode) else None + if isinstance(title, Episode): + # no part suffix here: build_title rebuilds the Episode from this dict, so a suffixed + # name plus the structural `part` below would render the part twice in the filename + name = title.name if title.name else f"Episode {title.number:02d}" + else: + name = str(title.name) if hasattr(title, "name") else str(title) + + result = { + "type": "episode" if is_episode else "movie" if isinstance(title, Movie) else "song" if is_song else "other", + "name": name, + "id": str(title.id) if hasattr(title, "id") else None, + "language": title_language, + "description": description, + "date": date, + "cover_url": cover_url, + } + # "other" titles carry no year; only Episode/Movie/Song do. + if isinstance(title, (Episode, Movie, Song)): + result["year"] = title.year + if isinstance(title, Episode): + result["series_title"] = str(title.title) + result["season"] = title.season + result["number"] = title.number + if episode_part is not None: + result["part"] = episode_part + if title.air_date is not None: + result["air_date"] = ( + title.air_date.isoformat() if isinstance(title.air_date, date_) else str(title.air_date) + ) + result.update(episode_flags(title)) + if is_song: + for field in SONG_FIELDS: + result[field] = getattr(title, field, None) + metadata = song_metadata(title) + result["music_data"] = {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")} + if isinstance(title, (Episode, Movie)) and getattr(title, "anime", None) is not None: + result["anime"] = title.anime + + if availability is not None: + result["availability"] = availability + return result + + +def title_to_meta(title: Title_T) -> dict[str, Any]: + """The export form of a title: the fields an import needs to rebuild it for output naming. + + build_title decodes it, as it decodes the REST form. + """ + meta: dict[str, Any] = { + "id": str(title.id), + "language": str(title.language) if getattr(title, "language", None) else None, + } + if isinstance(title, Episode): + meta.update( + type="episode", + series_title=title.title, + season=title.season, + number=title.number, + name=title.name, + year=title.year, + air_date=title.air_date.isoformat() if isinstance(title.air_date, date_) else title.air_date, + ) + if title.part is not None: + meta["part"] = title.part + meta.update(episode_flags(title)) + elif isinstance(title, Movie): + meta.update(type="movie", name=title.name, year=title.year) + else: + meta.update(type="movie", name=str(title)) + if getattr(title, "anime", None) is not None: + meta["anime"] = title.anime + return meta + + +def episode_name(name: Optional[str], series_title: Optional[str]) -> Optional[str]: + """Drop a placeholder episode name the way ``Episode.__init__`` does. + + The server sends "Episode 04" for an unnamed episode, so the same filter has to run + again here, or the placeholder reaches the output file name. + """ + if not name: + return None + name = name.strip() + if EPISODE_PLACEHOLDER_NAME.match(name): + return None + if series_title and name.lower() == series_title.lower(): + return None + return name + + +def parse_air_date(value: Any) -> Any: + """ISO date string back to a date, as ``Episode.__init__`` does; anything else passes through.""" + if isinstance(value, str): + try: + return date_.fromisoformat(value[:10]) + except ValueError: + return value + return value + + +def apply_title_fields(title: Title_T, info: Dict[str, Any]) -> None: + """Copy the serialized metadata fields onto a local title. + + A service can change its title inside ``get_tracks`` (a corrected original language, + a real episode name, an air date), so the client re-applies the server's view of the + title after every call that returns one. Season, number and part are set only by + ``build_title``, as dl can renumber them after the listing. + """ + if info.get("language"): + title.language = Language.get(info["language"]) + if info.get("description") is not None and isinstance(title, (Episode, Movie)): + title.description = info["description"] + if info.get("year") is not None: + title.year = info["year"] + + if isinstance(title, Episode): + if info.get("series_title"): + title.title = info["series_title"] + if "name" in info: + title.name = episode_name(info["name"], title.title) + if info.get("absolute") is not None: + title.absolute = info["absolute"] + if info.get("air_date") is not None: + title.air_date = parse_air_date(info["air_date"]) + elif info.get("name"): + title.name = info["name"] + + for key in ("anime", "daily", "sport", *(SONG_FIELDS if isinstance(title, Song) else ())): + if info.get(key) is not None: + setattr(title, key, info[key]) + + extra = {k: info[k] for k in ("date", "cover_url") if info.get(k) is not None} + availability = availability_metadata(info.get("availability")) + if availability is not None: + extra["availability"] = availability + music_data = info.get("music_data") + if isinstance(music_data, dict): + extra.update({key: music_data[key] for key in MUSIC_DATA_KEYS if key in music_data}) + if extra: + if isinstance(title.data, dict): + title.data.update(extra) + else: + title.data = extra + + +def build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Title_T: + """Rebuild a title from its REST form or its export form, under a stand-in class named for the service.""" + svc_class = type(service_tag, (), {}) + lang = Language.get(info["language"]) if info.get("language") else None + title_type = info.get("type") + title: Title_T + if title_type == "episode": + title = Episode( + id_=info.get("id", fallback_id), + service=svc_class, + title=info.get("series_title", "Unknown"), + season=info.get("season", 0), + number=info.get("number", 0), + part=info.get("part"), + language=lang, + ) + elif title_type == "movie": + title = Movie( + id_=info.get("id", fallback_id), + service=svc_class, + name=info.get("name") or "Unknown", + language=lang, + ) + elif title_type == "song": + title = Song( + id_=info.get("id", fallback_id), + service=svc_class, + name=info.get("name") or "Unknown", + artist=info.get("artist") or "Unknown", + album=info.get("album") or "Unknown", + track=info.get("track") or 1, + disc=info.get("disc") or 1, + language=lang, + album_artist=info.get("album_artist"), + release_type=info.get("release_type") or "album", + total_tracks=info.get("total_tracks"), + total_discs=info.get("total_discs"), + genre=info.get("genre"), + explicit=info.get("explicit"), + isrc=info.get("isrc"), + upc=info.get("upc"), + copyright=info.get("copyright"), + label=info.get("label"), + lyrics=info.get("lyrics"), + artwork_url=info.get("artwork_url"), + synced_lyrics=info.get("synced_lyrics"), + lyrics_suffix=info.get("lyrics_suffix"), + ) + else: + raise click.ClickException( + f"The remote server sent an unknown title type {title_type!r}; unshackle versions differ" + ) + apply_title_fields(title, info) + return title + + +def serialize_drm(drm_list: Any) -> Optional[List[Dict[str, Any]]]: + """Serialise DRM objects to JSON-serializable list.""" + if not drm_list: + return None + + if not isinstance(drm_list, list): + drm_list = [drm_list] + + result = [] + for drm in drm_list: + drm_info = {} + drm_class = drm.__class__.__name__ + drm_info["type"] = drm_class.lower() + if isinstance(drm, BlowfishStripe): + drm_info["key"] = drm.key.hex() + + # pywidevine exposes dumps(); pyplayready's PSSH does not, so PlayReady falls back + # to the base64 it was built from. Without it the client drops every PlayReady + # entry and licenses the title with the wrong CDM. + pssh_obj = getattr(drm, "_pssh", None) + pssh_b64 = (getattr(drm, "data", None) or {}).get("pssh_b64") + if pssh_obj is not None and hasattr(pssh_obj, "dumps"): + try: + drm_info["pssh"] = pssh_obj.dumps() + except (ValueError, TypeError, KeyError): + server_log.warning( + "Failed to serialize PSSH for DRM type=%s pssh_type=%s", + drm_class, + type(pssh_obj).__name__, + exc_info=True, + ) + if not drm_info.get("pssh") and pssh_b64: + drm_info["pssh"] = pssh_b64 + + if hasattr(drm, "kids") and drm.kids: + drm_info["kids"] = [str(kid) for kid in drm.kids] + + if hasattr(drm, "content_keys") and drm.content_keys: + drm_info["content_keys"] = {str(k): v for k, v in drm.content_keys.items()} + + # Get license URL - essential for remote licensing + if hasattr(drm, "license_url") and drm.license_url: + drm_info["license_url"] = str(drm.license_url) + elif hasattr(drm, "_license_url") and drm._license_url: + drm_info["license_url"] = str(drm._license_url) + + result.append(drm_info) + + return result if result else None + + +def reconstruct_drm(drm_list: Optional[list]) -> list: + """Reconstruct DRM objects from the REST form.""" + if not drm_list: + return [] + result: list[Any] = [] + for drm_info in drm_list: + drm_type = drm_info.get("type", "") + pssh_str = drm_info.get("pssh") + if not pssh_str and drm_type != "blowfishstripe": + continue + try: + if drm_type == "blowfishstripe": + result.append(BlowfishStripe(drm_info["key"])) + elif drm_type in ("widevine", "playready"): + result.append(pssh_drm(drm_type, pssh_str, drm_info.get("kids"))) + # a dropped entry can leave the track with no DRM, so never skip silently + except Exception as e: + client_log.warning(f"Skipping unparseable {drm_type} DRM entry from server: {e!r}") + continue + return result + + +def pssh_drm(system: str, pssh_b64: str, kids: Optional[List[str]]) -> Union[Widevine, PlayReady]: + """A Widevine or PlayReady DRM rebuilt from its base64 PSSH, as both forms carry it (system in lower case). + + kids repeats the PSSH KIDs, so kids[0] is not the track's own KID; only a PSSH without KIDs needs it. + """ + if system == "playready": + return PlayReady(pssh=PlayReadyPSSH(base64.b64decode(pssh_b64)), pssh_b64=pssh_b64) + wv_pssh = WidevinePSSH(pssh_b64) + return Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None) + + +def drm_to_dict(drm: Union[Widevine, PlayReady, ClearKeyCENC]) -> dict[str, Any]: + """A DRM in the export form: its system, PSSH and KIDs. + + The export keeps the content keys once at title level, not here. + """ + if isinstance(drm, ClearKeyCENC): + data: dict[str, Any] = { + "system": "ClearKeyCENC", + "kids": [kid.hex for kid in drm.kids], + } + if drm.laurl: + data["laurl"] = drm.laurl + return data + if isinstance(drm, Widevine): + return { + "system": "Widevine", + "pssh_b64": drm.pssh.dumps(), + "kids": [kid.hex for kid in drm.kids], + } + return { + "system": "PlayReady", + "pssh_b64": drm.pssh_b64, + "kids": [kid.hex for kid in drm.kids], + } + + +def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady, ClearKeyCENC]: + """Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its export form. + + Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH) + and re-injects any saved content keys so the resulting object can decrypt without + contacting a license server. + """ + system = data.get("system") + pssh_b64 = data.get("pssh_b64") + kids = data.get("kids") or [] + content_keys = data.get("content_keys") or {} + + if system == "ClearKeyCENC": + drm: Union[Widevine, PlayReady, ClearKeyCENC] = ClearKeyCENC(kids=kids, laurl=data.get("laurl")) + elif not pssh_b64: + raise ValueError("Cannot reconstruct DRM without a stored PSSH.") + elif system in ("PlayReady", "Widevine"): + drm = pssh_drm(system.lower(), pssh_b64, kids) + else: + raise ValueError(f"Unsupported DRM system for reconstruction: {system!r}") + + for kid_hex, key in content_keys.items(): + drm.content_keys[UUID(hex=kid_hex)] = key + + return drm + + +def serialize_track_data(track: Any) -> Optional[Dict[str, Any]]: + """The JSON-safe part of a service-set ``track.data``. + + This drops the manifest parsers' own keys: the client rebuilds those from the + ``manifests`` payload, and they hold live lxml and m3u8 objects that JSON cannot carry. + """ + data = getattr(track, "data", None) + if not isinstance(data, dict): + return None + safe: Dict[str, Any] = {} + for key, value in data.items(): + if key in MANIFEST_DATA_KEYS: + continue + try: + json.dumps(value) + except (TypeError, ValueError): + continue + safe[key] = value + return safe or None + + +def serialize_track_common(track: Any) -> Dict[str, Any]: + """The Track fields every track type shares, a superset of ``Track.to_dict()``.""" + return { + "id": str(track.id), + "language": str(track.language) if track.language else None, + "is_original_lang": bool(getattr(track, "is_original_lang", False)), + "name": getattr(track, "name", None), + "track_name": track.get_track_name(), + "needs_repack": bool(getattr(track, "needs_repack", False)), + "edition": list(getattr(track, "edition", None) or []), + "note": getattr(track, "note", None), + "descriptor": descriptor_name(track), + "drm": serialize_drm(track.drm) if getattr(track, "drm", None) else None, + "drm_preference": getattr(track, "drm_preference", None), + "data": serialize_track_data(track), + } + + +def serialize_tracks(tracks: Tracks, title: Any, include_url: bool = False) -> Dict[str, List[Dict[str, Any]]]: + """The ``video``, ``audio`` and ``subtitles`` lists of a title's tracks, video and audio highest bitrate first.""" + video_tracks = sorted(tracks.videos, key=lambda t: t.bitrate or 0, reverse=True) + audio_tracks = sorted(tracks.audio, key=lambda t: t.bitrate or 0, reverse=True) + original_ids = original_audio_ids(audio_tracks, title) + return { + "video": [serialize_video_track(t, include_url=include_url) for t in video_tracks], + "audio": [ + serialize_audio_track(t, include_url=include_url, is_original=t.id in original_ids) for t in audio_tracks + ], + "subtitles": [serialize_subtitle_track(t, include_url=include_url) for t in tracks.subtitles], + } + + +def original_audio_ids(tracks: List[Audio], title: Title_T) -> set: + """Return the ids of the audio tracks 'orig' resolves to, empty when the title has no language. + + This defers to Tracks.by_language through original_tag, as 'orig' does, so the flag agrees + with the downloader: the title's own variant first, else its close regional forms. + """ + language = getattr(title, "language", None) + if not language: + return set() + return {t.id for t in Tracks.by_language(tracks, [original_tag(language)])} + + +def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str, Any]: + """Convert video track to JSON-serializable dict.""" + codec_name = enum_name(track.codec) + codec_value = track.codec.value if track.codec else codec_name + range_name = enum_name(track.range) + + result = { + "id": str(track.id), + "codec": codec_name, + "codec_display": rename(VIDEO_CODEC_MAP.get(codec_name, codec_value)), + "bitrate": int(track.bitrate / 1000) if track.bitrate else None, + "bitrate_bps": track.bitrate or None, + "width": track.width, + "height": track.height, + "resolution": f"{track.width}x{track.height}" if track.width and track.height else None, + "fps": track.fps if track.fps else None, + "range": range_name, + "range_display": "+".join(rename(DYNAMIC_RANGE_MAP.get(p, p)) for p in track.range_label.split("+")), + "scan_type": enum_name(track.scan_type) if track.scan_type else None, + "closed_captions": list(getattr(track, "closed_captions", None) or []), + "dv_compatible_bitstream": bool(getattr(track, "dv_compatible_bitstream", False)), + "hdr10plus": bool(getattr(track, "hdr10plus", False)), + "hdr10_base": bool(getattr(track, "hdr10_base", False)), + "stereo": bool(getattr(track, "stereo", False)), + } + result.update(serialize_track_common(track)) + if include_url and hasattr(track, "url") and track.url: + result["url"] = str(track.url) + return result + + +def serialize_audio_track(track: Audio, include_url: bool = False, is_original: bool = False) -> Dict[str, Any]: + """Convert audio track to JSON-serializable dict. + + Get is_original from original_audio_ids so the flag always agrees with the + track 'orig' would download. + """ + codec_name = enum_name(track.codec) + codec_value = track.codec.value if track.codec else codec_name + + result = { + "id": str(track.id), + "codec": codec_name, + "codec_display": rename(AUDIO_CODEC_MAP.get(codec_value, codec_value)), + "bitrate": int(track.bitrate / 1000) if track.bitrate else None, + "bitrate_bps": track.bitrate or None, + "channels": track.channels if track.channels else None, + "is_original": is_original, + "atmos": track.atmos if hasattr(track, "atmos") else False, + "joc": getattr(track, "joc", 0), + "descriptive": track.descriptive if hasattr(track, "descriptive") else False, + } + result.update(serialize_track_common(track)) + if include_url and hasattr(track, "url") and track.url: + result["url"] = str(track.url) + return result + + +def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> Dict[str, Any]: + """Convert subtitle track to JSON-serializable dict.""" + result = { + "id": str(track.id), + "codec": enum_name(track.codec), + "forced": track.forced if hasattr(track, "forced") else False, + "sdh": track.sdh if hasattr(track, "sdh") else False, + "cc": track.cc if hasattr(track, "cc") else False, + } + result.update(serialize_track_common(track)) + if include_url and hasattr(track, "url") and track.url: + result["url"] = str(track.url) + return result + + +def base_track_kwargs(data: Dict[str, Any]) -> Dict[str, Any]: + """The Track constructor kwargs that both forms decode the same way.""" + return {"name": data.get("name"), "edition": data.get("edition") or None, "id_": data.get("id")} + + +def rest_track_kwargs(data: Dict[str, Any]) -> Dict[str, Any]: + """The shared Track constructor kwargs of the REST form. + + An older server omits the newer keys, so each one falls back to the value a + locally-built track would have had. + """ + return { + "url": data.get("url") or "https://placeholder", + "language": Language.get(data.get("language") or "und"), + "is_original_lang": bool(data.get("is_original_lang", data.get("is_original", False))), + "descriptor": enum_get(Track.Descriptor, data.get("descriptor"), Track.Descriptor.URL), + "needs_repack": bool(data.get("needs_repack", False)), + "note": data["note"] if isinstance(data.get("note"), str) else None, + **base_track_kwargs(data), + } + + +def export_track_kwargs(data: dict[str, Any]) -> dict[str, Any]: + """The shared Track constructor kwargs of the export form, as stored. + + A malformed value reaches the Track constructor, which refuses it, so the import skips that track. + """ + return { + "url": data["url"], + "language": data.get("language") or "und", + "is_original_lang": data.get("is_original_lang", False), + "descriptor": Track.Descriptor[data.get("descriptor", "URL")], + "needs_repack": data.get("needs_repack", False), + "note": data.get("note"), + **base_track_kwargs(data), + } + + +def deserialize_bitrate(data: Dict[str, Any]) -> int: + """Exact bits/s when the server sent it, otherwise the kb/s figure scaled back up.""" + exact = data.get("bitrate_bps") + if exact: + return int(exact) + return data["bitrate"] * 1000 if data.get("bitrate") else 0 + + +def deserialize_video(data: Dict[str, Any]) -> Video: + """A video track from its REST form.""" + return Video( + **rest_track_kwargs(data), + codec=enum_get(Video.Codec, data.get("codec")), + range_=enum_get(Video.Range, data.get("range"), Video.Range.SDR), + bitrate=deserialize_bitrate(data), + width=data.get("width") or 0, + height=data.get("height") or 0, + fps=data.get("fps"), + scan_type=enum_get(Video.ScanType, data.get("scan_type")), + closed_captions=data.get("closed_captions") or None, + dv_compatible_bitstream=bool(data.get("dv_compatible_bitstream", False)), + hdr10plus=bool(data.get("hdr10plus", False)), + hdr10_base=bool(data.get("hdr10_base", False)), + stereo=bool(data.get("stereo", False)), + ) + + +def deserialize_audio(data: Dict[str, Any]) -> Audio: + """An audio track from its REST form.""" + joc = data.get("joc") + return Audio( + **rest_track_kwargs(data), + codec=enum_get(Audio.Codec, data.get("codec")), + bitrate=deserialize_bitrate(data), + channels=data.get("channels"), + joc=joc, + extra={"atmos": True} if joc is None and data.get("atmos") else None, + descriptive=data.get("descriptive", False), + ) + + +def deserialize_subtitle(data: Dict[str, Any]) -> Subtitle: + """A subtitle track from its REST form.""" + return Subtitle( + **rest_track_kwargs(data), + codec=enum_get(Subtitle.Codec, data.get("codec")), + cc=data.get("cc", False), + sdh=data.get("sdh", False), + forced=data.get("forced", False), + ) + + +def build_tracks(data: Dict[str, Any]) -> Tracks: + """A title's tracks, their DRM and its attachments from the REST form.""" + tracks = Tracks() + tracks.videos = [deserialize_video(v) for v in data.get("video", [])] + tracks.audio = [deserialize_audio(a) for a in data.get("audio", [])] + tracks.subtitles = [deserialize_subtitle(s) for s in data.get("subtitles", [])] + + for track_data, track_obj in [ + *zip(data.get("video", []), tracks.videos), + *zip(data.get("audio", []), tracks.audio), + *zip(data.get("subtitles", []), tracks.subtitles), + ]: + drm_objs = reconstruct_drm(track_data.get("drm")) + if drm_objs: + track_obj.drm = drm_objs + preference = track_data.get("drm_preference") + if preference: + try: + track_obj.drm_preference = preference + except ValueError: + client_log.warning( + f"Ignoring unknown drm_preference {preference!r} from the server for track {track_obj.id}" + ) + tracks.attachments = [a for a in map(build_attachment, data.get("attachments", [])) if a] + return tracks + + +def track_to_dict(track: Track) -> dict[str, Any]: + """A track in the export form: its class name and constructor values. + + DRM is not serialised here. The export writer attaches the licensed DRM + keys. + """ + data: dict[str, Any] = { + "type": track.__class__.__name__, + "id": track.id, + "url": track.url, + "language": str(track.language), + "is_original_lang": track.is_original_lang, + "descriptor": track.descriptor.name, + "needs_repack": track.needs_repack, + "name": track.name, + "edition": track.edition, + "note": track.note, + } + if isinstance(track, Video): + data.update( + { + "codec": track.codec.name if track.codec else None, + "range": track.range.name if track.range else None, + "bitrate": track.bitrate, + "width": track.width, + "height": track.height, + "fps": str(track.fps) if track.fps else None, + "scan_type": track.scan_type.name if track.scan_type else None, + "dv_compatible_bitstream": track.dv_compatible_bitstream, + "hdr10plus": track.hdr10plus, + "hdr10_base": track.hdr10_base, + "stereo": track.stereo, + } + ) + elif isinstance(track, Audio): + data.update( + { + "codec": track.codec.name if track.codec else None, + "bitrate": track.bitrate, + "channels": track.channels, + "joc": track.joc, + "descriptive": track.descriptive, + } + ) + elif isinstance(track, Subtitle): + data.update( + { + "codec": track.codec.name if track.codec else None, + "cc": track.cc, + "sdh": track.sdh, + "forced": track.forced, + } + ) + return data + + +def track_from_dict(data: dict[str, Any]) -> Union[Video, Audio, Subtitle]: + """Reconstruct the correct Track subclass from its export form. + + DRM is not reconstructed here: the import flow attaches the licensed DRM + content keys separately. + """ + track_type = data.get("type") + kinds: dict[Optional[str], type[Track]] = {"Video": Video, "Audio": Audio, "Subtitle": Subtitle} + kind = kinds.get(track_type) + if kind is None: + raise ValueError(f"Cannot reconstruct unsupported track type: {track_type!r}") + if kind is Video: + return Video( + **export_track_kwargs(data), + codec=Video.Codec[data["codec"]] if data.get("codec") else None, + range_=Video.Range[data["range"]] if data.get("range") else None, + bitrate=data.get("bitrate"), + width=data.get("width"), + height=data.get("height"), + fps=data.get("fps"), + scan_type=Video.ScanType[data["scan_type"]] if data.get("scan_type") else None, + dv_compatible_bitstream=data.get("dv_compatible_bitstream", False), + hdr10plus=data.get("hdr10plus", False), + hdr10_base=data.get("hdr10_base", False), + stereo=data.get("stereo", False), + ) + if kind is Audio: + return Audio( + **export_track_kwargs(data), + codec=Audio.Codec[data["codec"]] if data.get("codec") else None, + bitrate=data.get("bitrate"), + channels=data.get("channels"), + joc=data.get("joc"), + descriptive=data.get("descriptive", False), + ) + return Subtitle( + **export_track_kwargs(data), + codec=Subtitle.Codec[data["codec"]] if data.get("codec") else None, + cc=data.get("cc", False), + sdh=data.get("sdh", False), + forced=data.get("forced", False), + ) + + +def attachment_to_dict(attachment: Attachment) -> Dict[str, Any]: + """An attachment in the export form, which is also the REST form of a URL-backed attachment.""" + return { + "url": attachment.url, + "name": attachment.name, + "mime_type": attachment.mime_type, + "description": attachment.description, + } + + +def serialize_attachment(attachment: Any) -> Optional[Dict[str, Any]]: + """One attachment as JSON, with a path-only attachment carried as base64 file bytes. + + A service can attach a file it already wrote to disk (a font, a poster). The client + has no access to the server's filesystem, so those bytes travel inline. + """ + result = attachment_to_dict(attachment) + if attachment.url: + return result + + path = getattr(attachment, "path", None) + if not path: + return None + from unshackle.core.api.sanitize import sanitize_log + + path = Path(path) + try: + size = path.stat().st_size + if size > ATTACHMENT_INLINE_LIMIT: + server_log.warning( + "Skipping attachment %s: %d bytes is over the %d byte inline limit", + sanitize_log(path.name), + size, + ATTACHMENT_INLINE_LIMIT, + ) + return None + result["content"] = base64.b64encode(path.read_bytes()).decode("ascii") + except OSError as e: + server_log.warning("Skipping attachment %s: %s", sanitize_log(path.name), e) + return None + result["file_name"] = path.name + return result + + +def build_attachment(data: Dict[str, Any]) -> Optional[Attachment]: + """Rebuild one attachment. A path-only attachment arrives as base64, which this writes to temp.""" + kwargs = { + "name": data.get("name"), + "mime_type": data.get("mime_type"), + "description": data.get("description"), + } + if data.get("url"): + return Attachment(url=data["url"], **kwargs) + + content = data.get("content") + if not content: + return None + try: + file_name = Path(str(data.get("file_name") or data.get("name") or "attachment")).name + target = config.directories.temp / "remote_attachments" / file_name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(base64.b64decode(content)) + return Attachment(path=target, **kwargs) + except (OSError, ValueError) as e: + client_log.warning(f"Skipping attachment {data.get('name')!r} sent by the server: {e}") + return None