forked from kenzuya/unshackle
refactor(wire): put the tracks reply codec in wire and stamp service flags in serialize_title
This commit is contained in:
@@ -96,12 +96,13 @@ 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 (
|
||||
serialize_attachment,
|
||||
cookie_values,
|
||||
serialize_drm,
|
||||
serialize_title,
|
||||
serialize_track_data,
|
||||
serialize_tracks,
|
||||
serialize_tracks_reply,
|
||||
served_url,
|
||||
stamp_service_flags,
|
||||
)
|
||||
|
||||
log = logging.getLogger("api")
|
||||
@@ -1380,7 +1381,7 @@ async def list_titles_handler(data: dict[str, Any], request: web.Request | None
|
||||
)
|
||||
titles = await asyncio.to_thread(service_instance.get_titles)
|
||||
|
||||
title_list = [stamp_service_flags(serialize_title(t), service_instance) for t in listed_titles(titles)]
|
||||
title_list = [serialize_title(t, service_instance) for t in listed_titles(titles)]
|
||||
|
||||
return await request_cache.json_response({"titles": title_list})
|
||||
|
||||
@@ -1497,7 +1498,9 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
|
||||
for title in sorted_titles:
|
||||
try:
|
||||
tracks = await call(probed_tracks, service_instance, title)
|
||||
episodes_data.append({"title": serialize_title(title), **serialize_tracks(tracks, title)})
|
||||
episodes_data.append(
|
||||
{"title": serialize_title(title, service_instance), **serialize_tracks(tracks, title)}
|
||||
)
|
||||
log.debug(f"Successfully got tracks for {title.season}x{title.number}")
|
||||
except SystemExit:
|
||||
# Service calls sys.exit() for unavailable episodes - catch and skip
|
||||
@@ -1532,7 +1535,7 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
|
||||
first_title = titles
|
||||
|
||||
tracks = await call(probed_tracks, service_instance, first_title)
|
||||
response = {"title": serialize_title(first_title), **serialize_tracks(tracks, first_title)}
|
||||
response = {"title": serialize_title(first_title, service_instance), **serialize_tracks(tracks, first_title)}
|
||||
|
||||
return await request_cache.json_response(response)
|
||||
|
||||
@@ -2984,7 +2987,7 @@ async def session_titles_handler(session_id: str, request: web.Request | None =
|
||||
for t in titles_list:
|
||||
tid = str(t.id) if hasattr(t, "id") else str(id(t))
|
||||
session.title_map[tid] = t
|
||||
serialized_titles.append(stamp_service_flags(serialize_title(t), service_instance))
|
||||
serialized_titles.append(serialize_title(t, service_instance))
|
||||
SessionStore.publish_update(session)
|
||||
|
||||
return web.json_response(TitlesReply(session_id=session_id, titles=serialized_titles))
|
||||
@@ -3029,11 +3032,6 @@ def client_session_auth(session: Any) -> tuple[dict[str, str], list[dict[str, An
|
||||
return headers, cookies
|
||||
|
||||
|
||||
def cookie_values(cookies: list[dict[str, Any]]) -> dict[str, str]:
|
||||
"""The ``{name: value}`` form of :func:`client_session_auth` cookies, for clients that predate the jar."""
|
||||
return {c["name"]: c["value"] for c in cookies}
|
||||
|
||||
|
||||
def session_policy(session: Any, request: web.Request | None) -> KeyPolicy:
|
||||
"""The API key policy a remote session was created with, so a reload cannot change it for that session.
|
||||
|
||||
@@ -3131,13 +3129,6 @@ async def session_tracks_handler(
|
||||
)
|
||||
server_cdm_type = candidates[0] if candidates else "playready"
|
||||
|
||||
def serialize() -> dict[str, list]:
|
||||
"""The track and attachment lists, 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_track_data(d.get("data"), session)
|
||||
return {**lists, "attachments": [a for a in map(serialize_attachment, tracks.attachments) if a]}
|
||||
|
||||
session_fields = TracksReply(
|
||||
session_headers=session_headers,
|
||||
session_cookies=cookie_values(session_cookies),
|
||||
@@ -3149,18 +3140,15 @@ async def session_tracks_handler(
|
||||
],
|
||||
)
|
||||
|
||||
return web.json_response(
|
||||
{
|
||||
"title": stamp_service_flags(serialize_title(title), service_instance),
|
||||
**await asyncio.to_thread(serialize),
|
||||
"chapters": [
|
||||
{"timestamp": ch.timestamp, "name": ch.name}
|
||||
for ch in session.chapters_by_title.get(str(title_id), [])
|
||||
],
|
||||
**snapshot,
|
||||
**session_fields,
|
||||
}
|
||||
reply = await asyncio.to_thread(
|
||||
serialize_tracks_reply,
|
||||
title,
|
||||
tracks,
|
||||
session.chapters_by_title.get(str(title_id), []),
|
||||
service_instance,
|
||||
lambda data: scrub_track_data(data, session),
|
||||
)
|
||||
return web.json_response({**reply, **snapshot, **session_fields})
|
||||
|
||||
except (Exception, SystemExit) as e:
|
||||
log.exception(f"Error getting tracks for title {sanitize_log(title_id)}")
|
||||
@@ -3219,14 +3207,7 @@ async def session_segments_handler(
|
||||
"cookie_jar": cookies,
|
||||
}
|
||||
|
||||
# Include manifest-specific data for segment resolution. Round-trip through
|
||||
# JSON so any non-serializable value becomes its str() (default=str).
|
||||
if hasattr(track, "data") and track.data:
|
||||
import json
|
||||
|
||||
track_info["data"] = scrub_track_data(json.loads(json.dumps(track.data, default=str)), session)
|
||||
else:
|
||||
track_info["data"] = {}
|
||||
track_info["data"] = scrub_track_data(serialize_track_data(track), session) or {}
|
||||
|
||||
result[track_id] = track_info
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.cenc import drm_stub
|
||||
from unshackle.core.drm.discovery import track_pssh
|
||||
from unshackle.core.launch import launch_keys
|
||||
from unshackle.core.manifests.snapshot import match_track, restore
|
||||
from unshackle.core.manifests.snapshot import match_track
|
||||
from unshackle.core.proxies.resolve import is_loopback
|
||||
from unshackle.core.remote_protocol import (
|
||||
BAD_KEY_ROUTE,
|
||||
@@ -95,14 +95,14 @@ from unshackle.core.titles import Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.titles.episode import Episode, Series
|
||||
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 import 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
|
||||
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.wire import apply_title_fields, build_title, build_tracks
|
||||
from unshackle.core.wire import apply_tracks_reply, build_chapters, build_title
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.remote_channel import Channel
|
||||
@@ -429,42 +429,6 @@ def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]:
|
||||
yield batch
|
||||
|
||||
|
||||
def apply_service_track_data(tracks: Tracks, data: dict[str, Any]) -> None:
|
||||
"""Overlay the service-set ``track.data`` the server 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 list(tracks.videos) + list(tracks.audio) + list(tracks.subtitles)}
|
||||
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 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 segment_uri_filter(uris: Iterable[Any]) -> Callable[[Any], bool]:
|
||||
"""Return an HLS ``OnSegmentFilter`` that drops the segments with these URIs.
|
||||
|
||||
@@ -1428,21 +1392,8 @@ class RemoteService(TitleSource):
|
||||
finally:
|
||||
self.drain_server_logs()
|
||||
with malformed_answer("tracks"):
|
||||
tracks = build_tracks(result)
|
||||
|
||||
remote_title = result.get("title") or {}
|
||||
if remote_title:
|
||||
apply_title_fields(title, remote_title)
|
||||
|
||||
session_fields = cast(TracksReply, result)
|
||||
for k, v in session_fields.get("session_headers", {}).items():
|
||||
if k.lower() not in ("host", "content-length", "content-type"):
|
||||
self.session.headers[k] = v
|
||||
apply_session_cookies(self.session, result)
|
||||
|
||||
restore(tracks, result)
|
||||
apply_service_track_data(tracks, result)
|
||||
|
||||
tracks = apply_tracks_reply(result, title, self.session)
|
||||
session_fields = cast(TracksReply, result)
|
||||
server_cdm = bool(session_fields.get("server_cdm", False))
|
||||
if self.licensing is None:
|
||||
request = self._server_cdm_request
|
||||
@@ -1721,7 +1672,7 @@ class RemoteService(TitleSource):
|
||||
self.get_tracks(title)
|
||||
raw = self._chapters_by_title.get(title_id, [])
|
||||
with malformed_answer("chapters"):
|
||||
return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in raw])
|
||||
return build_chapters(raw)
|
||||
|
||||
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "widevine")
|
||||
|
||||
+91
-5
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user