refactor(wire): put the tracks reply codec in wire and stamp service flags in serialize_title

This commit is contained in:
imSp4rky
2026-11-29 13:56:29 -07:00
parent b429f612fb
commit dcbc9de7ba
11 changed files with 336 additions and 181 deletions
+91 -5
View File
@@ -1,4 +1,4 @@
"""The wire form of a title, its tracks, their DRM and attachments: what crosses a process edge.
"""The wire form of a title, its tracks, their DRM and attachments, and the tracks reply: 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
@@ -15,6 +15,7 @@ import base64
import json
import logging
import re
from collections.abc import Callable, Iterable
from datetime import date as date_
from enum import Enum
from pathlib import Path
@@ -22,17 +23,19 @@ from typing import Any
from uuid import UUID
import click
import requests
from langcodes import Language
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 WHOLE_FILE_DRM, BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.manifests.snapshot import restore
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 import Audio, Chapter, Chapters, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.track import Track
from unshackle.core.utilities import original_tag
@@ -79,8 +82,8 @@ def episode_flags(title: Episode) -> dict[str, Any]:
return flags
def serialize_title(title: Title_T) -> dict[str, Any]:
"""Convert a title object to JSON-serializable dict."""
def serialize_title(title: Title_T, service: Any) -> dict[str, Any]:
"""The REST form of a title, with the class flags of ``service`` (the service instance) stamped in."""
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
@@ -136,7 +139,7 @@ def serialize_title(title: Title_T) -> dict[str, Any]:
if availability is not None:
result["availability"] = availability
return result
return stamp_service_flags(result, service)
def title_to_meta(title: Title_T) -> dict[str, Any]:
@@ -480,6 +483,89 @@ def serialize_track_data(track: Any) -> dict[str, Any] | None:
return safe or None
def apply_service_track_data(tracks: Tracks, data: dict[str, Any]) -> None:
"""Overlay the service-set ``track.data`` that :func:`serialize_track_data` sent.
Runs after the manifest re-parse so a service value wins over the parser's own for
the same key, as it does on the server.
"""
by_id = {str(t.id): t for t in tracks}
for key in ("video", "audio", "subtitles"):
for entry in data.get(key, []):
track = by_id.get(str(entry.get("id")))
extra = entry.get("data")
if track is not None and isinstance(extra, dict):
track.data.update(extra)
def cookie_values(cookies: list[dict[str, Any]]) -> dict[str, str]:
"""The ``{name: value}`` form of a cookie jar list, for clients that predate the jar."""
return {c["name"]: c["value"] for c in cookies}
def apply_session_cookies(session: requests.Session, result: dict) -> None:
"""Copy the server's session cookies into ``session``, each scoped to its own domain.
An older server sends only ``session_cookies`` names and values, so those cookies go to every host.
It skips malformed entries.
"""
jar = result.get("session_cookie_jar")
if not isinstance(jar, list):
old = result.get("session_cookies")
jar = [{"name": k, "value": v} for k, v in old.items()] if isinstance(old, dict) else []
for c in jar:
if isinstance(c, dict) and isinstance(c.get("name"), str) and isinstance(c.get("value"), str):
session.cookies.set(
c["name"],
c["value"],
domain=str(c.get("domain") or ""),
path=str(c.get("path") or "/"),
secure=bool(c.get("secure")),
)
def serialize_tracks_reply(
title: Title_T,
tracks: Tracks,
chapters: Iterable[Chapter],
service: Any,
scrub_data: Callable[[dict[str, Any] | None], dict[str, Any] | None],
) -> dict[str, Any]:
"""The title, tracks with URLs, attachments and chapters of a remote session tracks reply.
``scrub_data`` filters each track's ``data``. The remote session fields and the manifest snapshot go beside it.
Run it off the event loop: an attachment can be a 20 MB file.
"""
lists = serialize_tracks(tracks, title, include_url=True)
for d in lists["video"] + lists["audio"] + lists["subtitles"]:
d["data"] = scrub_data(d.get("data"))
return {
"title": serialize_title(title, service),
**lists,
"attachments": [a for a in map(serialize_attachment, tracks.attachments) if a],
"chapters": [{"timestamp": ch.timestamp, "name": ch.name} for ch in chapters],
}
def apply_tracks_reply(reply: dict[str, Any], title: Title_T, session: requests.Session) -> Tracks:
"""Decode a tracks reply: the tracks, plus the title fields, headers and cookies it applies to ``title`` and ``session``."""
tracks = build_tracks(reply)
if remote_title := reply.get("title"):
apply_title_fields(title, remote_title)
for k, v in (reply.get("session_headers") or {}).items():
if k.lower() not in ("host", "content-length", "content-type"):
session.headers[k] = v
apply_session_cookies(session, reply)
restore(tracks, reply)
apply_service_track_data(tracks, reply)
return tracks
def build_chapters(chapters: list[dict[str, Any]]) -> Chapters:
"""Decode the ``chapters`` list of a tracks reply."""
return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in chapters])
def serialize_track_common(track: Any) -> dict[str, Any]:
"""The Track fields every track type shares, a superset of ``Track.to_dict()``."""
return {