refactor(core): move the title, track and DRM wire form into core/wire.py

This commit is contained in:
imSp4rky
2026-11-24 14:37:51 -07:00
parent e385234a92
commit 55138f95c2
36 changed files with 2250 additions and 907 deletions
+1 -2
View File
@@ -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
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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:
+1 -2
View File
@@ -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?}"
+1 -1
View File
@@ -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")
+3 -2
View File
@@ -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:
+1 -1
View File
@@ -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", (), {})
+4 -3
View File
@@ -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")
+2 -1
View File
@@ -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()
+2 -1
View File
@@ -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:
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -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")
@@ -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:
+1 -2
View File
@@ -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
+1 -3
View File
@@ -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")
+3 -3
View File
@@ -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
+7 -5
View File
@@ -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
@@ -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 == []
@@ -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)]}])
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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(
+2 -33
View File
@@ -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.
+11 -315
View File
@@ -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")
+1 -1
View File
@@ -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
-39
View File
@@ -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",
+3 -11
View File
@@ -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."""
+3 -9
View File
@@ -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]:
+3 -9
View File
@@ -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:
"""
+4 -9
View File
@@ -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
+5 -302
View File
@@ -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):
+4 -2
View File
@@ -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:
-25
View File
@@ -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."""
-23
View File
@@ -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."""
+3 -50
View File
@@ -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:
-37
View File
@@ -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)."""
+854
View File
@@ -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