feat(tracks): resolve a track url on use, locally and over remote

This commit is contained in:
imSp4rky
2026-11-27 01:45:49 -07:00
parent 736f1cc731
commit 9901b62347
9 changed files with 198 additions and 8 deletions
+2 -1
View File
@@ -99,6 +99,7 @@ from unshackle.core.wire import (
serialize_drm,
serialize_title,
serialize_tracks,
served_url,
)
log = logging.getLogger("api")
@@ -3287,7 +3288,7 @@ async def session_segments_handler(
track_info: dict[str, Any] = {
"descriptor": descriptor_name,
"url": str(track.url) if track.url else None,
"url": await asyncio.to_thread(served_url, track),
"drm": serialize_drm(track.drm) if hasattr(track, "drm") and track.drm else None,
"headers": headers,
"cookies": cookie_values(cookies),
+4
View File
@@ -173,6 +173,10 @@ class TracksReply(TypedDict, total=False):
sample_decrypt_tracks: list[str]
class SegmentsRequest(TypedDict):
track_ids: list[str]
class SegmentFilterRequest(TypedDict):
track_id: str
+23
View File
@@ -19,6 +19,7 @@ import shlex
import sys
import time
from collections.abc import Callable, Iterable, Iterator, Mapping
from functools import partial
from http.cookiejar import CookieJar
from threading import Lock, local
from typing import (
@@ -58,6 +59,7 @@ from unshackle.core.remote_protocol import (
SAMPLES_ROUTE,
SEARCH_ROUTE,
SEGMENT_FILTER_ROUTE,
SEGMENTS_ROUTE,
SERVICES_ROUTE,
SESSION_CREATE_ROUTE,
SESSION_ROUTE,
@@ -72,6 +74,7 @@ from unshackle.core.remote_protocol import (
LicenseRequest,
SegmentFilterReply,
SegmentFilterRequest,
SegmentsRequest,
SessionClosed,
SessionCreate,
SessionCreated,
@@ -1439,6 +1442,8 @@ class RemoteService(TitleSource):
for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]:
if track.descriptor == Track.Descriptor.HLS:
track.OnSegmentFilter = self.remote_segment_filter(str(track.id))
if not track.url:
track.resolve_url = partial(self.track_url, track)
self._tracks_by_title[title_id] = tracks
self._chapters_by_title[title_id] = result.get("chapters", [])
@@ -1794,6 +1799,24 @@ class RemoteService(TitleSource):
)
return str(key)
def track_url(self, track: Track) -> str:
"""The URL that the server looks up for a track it sent with ``resolve_url``, or raise ClickException."""
server_id = self.server_track_id(track.id)
try:
with quiet():
resp = self.session_call(
lambda sid: self.client.post(
SEGMENTS_ROUTE.format(session_id=sid), SegmentsRequest(track_ids=[server_id])
)
)
except RemoteError as e:
raise click.ClickException(e.message) from None
finally:
self.drain_server_logs()
if not (url := ((resp.get("tracks") or {}).get(server_id) or {}).get("url")):
raise click.ClickException(f"The server sent no URL for track {track.id}")
return str(url)
def proxy_license(self, challenge: bytes | str, track: AnyTrack, drm_type: str) -> bytes:
"""Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it."""
if isinstance(challenge, str):
+11
View File
@@ -480,6 +480,7 @@ class Track:
self.path: Path | None = None
self.url = url
self.resolve_url: Callable[[], str] | None = None
self.language = language
self.is_original_lang = is_original_lang
self.descriptor = descriptor
@@ -704,6 +705,15 @@ class Track:
continue
log.debug(f"No {systems[0].__name__} or {systems[1].__name__} PSSH was found for this track, is it DRM free?")
def ensure_url(self) -> None:
"""Set the URL from ``resolve_url`` when the track has none.
A service sets ``resolve_url`` when each URL costs a request, so only a track that is downloaded or sent to a
remote client asks for its URL.
"""
if not self.url and self.resolve_url:
self.url = self.resolve_url()
def download(
self,
session: AnySession,
@@ -820,6 +830,7 @@ class Track:
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
elif self.descriptor == self.Descriptor.URL:
try:
self.ensure_url()
if (
DOWNLOAD_ALL_DRM.is_set()
and track_type in ("Video", "Audio")
+31 -6
View File
@@ -506,6 +506,29 @@ def original_audio_ids(tracks: list[Audio], title: Title_T) -> set:
return {t.id for t in Tracks.by_language(tracks, [original_tag(language)])}
def url_fields(track: Any) -> dict[str, Any]:
"""The URL of a track for the track list, or ``resolve_url`` for a track that resolves its URL on use.
Such a track keeps its lookup until a client asks the segments route for its URL.
"""
url = getattr(track, "url", None)
if not url and getattr(track, "resolve_url", None):
return {"resolve_url": True}
return {"url": str(url)} if url else {}
def served_url(track: Any) -> str | None:
"""The URL of a track for the segments route; a track that resolves its URL on use resolves it here."""
if hasattr(track, "ensure_url"):
try:
track.ensure_url()
except Exception as e:
server_log.warning(f"Could not resolve the URL of track {track.id}: {e}")
return None
url = getattr(track, "url", None)
return str(url) if url else None
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)
@@ -532,8 +555,8 @@ def serialize_video_track(track: Video, include_url: bool = False) -> dict[str,
"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)
if include_url:
result.update(url_fields(track))
return result
@@ -559,8 +582,8 @@ def serialize_audio_track(track: Audio, include_url: bool = False, is_original:
"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)
if include_url:
result.update(url_fields(track))
return result
@@ -574,8 +597,8 @@ def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> dict
"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)
if include_url:
result.update(url_fields(track))
return result
@@ -681,6 +704,8 @@ def build_tracks(data: dict[str, Any]) -> Tracks:
*zip(data.get("audio", []), tracks.audio, strict=False),
*zip(data.get("subtitles", []), tracks.subtitles, strict=False),
]:
if track_data.get("resolve_url"):
track_obj.url = ""
drm_objs = reconstruct_drm(track_data.get("drm"))
if drm_objs:
track_obj.drm = drm_objs