mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 19:35:06 +00:00
feat(tracks): resolve a track url on use, locally and over remote
This commit is contained in:
@@ -954,7 +954,7 @@ POST /api/session/create → returns session_id, status "authenticating"
|
|||||||
GET /api/session/{id}/channel → WebSocket: prompts, CDM calls, logs, login state, drain
|
GET /api/session/{id}/channel → WebSocket: prompts, CDM calls, logs, login state, drain
|
||||||
GET /api/session/{id}/prompt → without the channel: poll until authenticated (submit answers via POST)
|
GET /api/session/{id}/prompt → without the channel: poll until authenticated (submit answers via POST)
|
||||||
GET /api/session/{id}/titles → list titles
|
GET /api/session/{id}/titles → list titles
|
||||||
POST /api/session/{id}/tracks → tracks + chapters (with URLs) for one title
|
POST /api/session/{id}/tracks → tracks + chapters (with URLs) for one title; a track that resolves its URL on use has resolve_url true and no URL
|
||||||
POST /api/session/{id}/segments → resolve segment URLs / DRM / headers per track
|
POST /api/session/{id}/segments → resolve segment URLs / DRM / headers per track
|
||||||
POST /api/session/{id}/segment_filter → HLS segments the service drops (ads, bumpers)
|
POST /api/session/{id}/segment_filter → HLS segments the service drops (ads, bumpers)
|
||||||
POST /api/session/{id}/samples → decrypt cbcs samples of a track on the server
|
POST /api/session/{id}/samples → decrypt cbcs samples of a track on the server
|
||||||
|
|||||||
@@ -272,6 +272,12 @@ The main attributes include `url` (a string or list of strings), `language` (a
|
|||||||
descriptor-specific state stashed in `track.data["hls"]` / `track.data["dash"]`. If you
|
descriptor-specific state stashed in `track.data["hls"]` / `track.data["dash"]`. If you
|
||||||
do not give a `name`, unshackle derives a human-readable name from the language.
|
do not give a `name`, unshackle derives a human-readable name from the language.
|
||||||
|
|
||||||
|
When each URL of a `URL` track costs a request, give the track an empty `url` and set
|
||||||
|
`track.resolve_url` to a callable that returns the URL. unshackle calls it only for a
|
||||||
|
track that it downloads. Over `--remote`, the client asks the server for the URL of
|
||||||
|
each track it downloads, and the server calls the callable then. A track whose callable
|
||||||
|
fails gets no URL, and its download fails.
|
||||||
|
|
||||||
### `Video`
|
### `Video`
|
||||||
|
|
||||||
`Video` adds `codec`, `range`, `bitrate`, `width`, `height`, `fps`, `scan_type`, and
|
`Video` adds `codec`, `range`, `bitrate`, `width`, `height`, `fps`, `scan_type`, and
|
||||||
|
|||||||
@@ -326,6 +326,46 @@ def test_a_cipher_the_server_does_not_license_raises(grants, answer, message):
|
|||||||
assert stopped.value.error_code == "DRM_ERROR"
|
assert stopped.value.error_code == "DRM_ERROR"
|
||||||
|
|
||||||
|
|
||||||
|
def test_track_url_asks_the_segments_route_for_the_url_of_one_track():
|
||||||
|
"""A track the server sent with resolve_url gets its URL from the server when it is downloaded."""
|
||||||
|
svc = remote_service()
|
||||||
|
svc.drain_server_logs = lambda: None
|
||||||
|
sent = []
|
||||||
|
svc.client = SimpleNamespace(
|
||||||
|
post=lambda ep, data, **kw: sent.append((ep, data)) or {"tracks": {"a-1": {"url": "https://cdn.example/a"}}}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert svc.track_url(SimpleNamespace(id="a-1")) == "https://cdn.example/a"
|
||||||
|
|
||||||
|
assert [data for _, data in sent] == [{"track_ids": ["a-1"]}]
|
||||||
|
assert sent[0][0].endswith("/segments")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"answer",
|
||||||
|
[
|
||||||
|
{"tracks": {"a-1": {"url": None}}},
|
||||||
|
{"tracks": {}},
|
||||||
|
RemoteError("Track not found in session: a-1", "TRACK_NOT_FOUND"),
|
||||||
|
],
|
||||||
|
ids=["no-url", "no-track", "refused"],
|
||||||
|
)
|
||||||
|
def test_a_track_the_server_gives_no_url_raises(answer):
|
||||||
|
"""A track with no URL from the server stops at its download with one line."""
|
||||||
|
svc = remote_service()
|
||||||
|
svc.drain_server_logs = lambda: None
|
||||||
|
|
||||||
|
def post(ep, data, **kw):
|
||||||
|
if isinstance(answer, BaseException):
|
||||||
|
raise answer
|
||||||
|
return answer
|
||||||
|
|
||||||
|
svc.client = SimpleNamespace(post=post)
|
||||||
|
|
||||||
|
with pytest.raises(click.ClickException, match="no URL for track a-1|Track not found"):
|
||||||
|
svc.track_url(SimpleNamespace(id="a-1"))
|
||||||
|
|
||||||
|
|
||||||
def resolve(manifest_drm, drm_type="widevine"):
|
def resolve(manifest_drm, drm_type="widevine"):
|
||||||
"""Run resolve_server_keys for one track the server answers with its own key and a sibling."""
|
"""Run resolve_server_keys for one track the server answers with its own key and a sibling."""
|
||||||
svc = remote_service()
|
svc = remote_service()
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from unshackle.core.tracks import Audio
|
||||||
|
from unshackle.core.wire import build_tracks, serialize_audio_track, served_url
|
||||||
|
|
||||||
|
|
||||||
|
def audio(url: str = "") -> Audio:
|
||||||
|
return Audio(url=url, id_="a1", language="en", codec=Audio.Codec.AAC, bitrate=24000, channels=2.0)
|
||||||
|
|
||||||
|
|
||||||
|
def counted(calls: list[int]) -> str:
|
||||||
|
calls.append(1)
|
||||||
|
return "https://cdn.example/a"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ensure_url_resolves_once() -> None:
|
||||||
|
track, calls = audio(), list[int]()
|
||||||
|
track.resolve_url = lambda: counted(calls)
|
||||||
|
track.ensure_url()
|
||||||
|
track.ensure_url()
|
||||||
|
assert track.url == "https://cdn.example/a"
|
||||||
|
assert calls == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ensure_url_keeps_a_given_url() -> None:
|
||||||
|
track = audio("https://cdn.example/given")
|
||||||
|
track.resolve_url = lambda: pytest.fail("a track with a URL must not resolve one")
|
||||||
|
track.ensure_url()
|
||||||
|
assert track.url == "https://cdn.example/given"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_track_with_no_url_and_no_resolver_stays_empty() -> None:
|
||||||
|
track = audio()
|
||||||
|
track.ensure_url()
|
||||||
|
assert track.url == ""
|
||||||
|
assert served_url(track) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_track_list_marks_a_track_that_resolves_its_url_on_use() -> None:
|
||||||
|
track, calls = audio(), list[int]()
|
||||||
|
track.resolve_url = lambda: counted(calls)
|
||||||
|
sent = serialize_audio_track(track, include_url=True)
|
||||||
|
assert sent["resolve_url"] is True and "url" not in sent
|
||||||
|
assert calls == []
|
||||||
|
assert serialize_audio_track(audio("https://cdn.example/b"), include_url=True)["url"] == "https://cdn.example/b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_marked_track_arrives_with_no_url_and_others_keep_theirs() -> None:
|
||||||
|
tracks = build_tracks(
|
||||||
|
{
|
||||||
|
"audio": [
|
||||||
|
{"id": "a1", "codec": "AAC", "resolve_url": True},
|
||||||
|
{"id": "a2", "codec": "AAC", "url": "https://x/2"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert [track.url for track in tracks.audio] == ["", "https://x/2"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_segments_route_resolves_the_url() -> None:
|
||||||
|
track, calls = audio(), list[int]()
|
||||||
|
track.resolve_url = lambda: counted(calls)
|
||||||
|
assert served_url(track) == "https://cdn.example/a"
|
||||||
|
assert calls == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_failed_resolve_gives_no_url(caplog: pytest.LogCaptureFixture) -> None:
|
||||||
|
track = audio()
|
||||||
|
|
||||||
|
def refuse() -> str:
|
||||||
|
raise RuntimeError("HTTP 404")
|
||||||
|
|
||||||
|
track.resolve_url = refuse
|
||||||
|
with caplog.at_level(logging.WARNING, logger="api"):
|
||||||
|
assert served_url(track) is None
|
||||||
|
assert "Could not resolve the URL of track a1: HTTP 404" in caplog.text
|
||||||
@@ -99,6 +99,7 @@ from unshackle.core.wire import (
|
|||||||
serialize_drm,
|
serialize_drm,
|
||||||
serialize_title,
|
serialize_title,
|
||||||
serialize_tracks,
|
serialize_tracks,
|
||||||
|
served_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
log = logging.getLogger("api")
|
log = logging.getLogger("api")
|
||||||
@@ -3287,7 +3288,7 @@ async def session_segments_handler(
|
|||||||
|
|
||||||
track_info: dict[str, Any] = {
|
track_info: dict[str, Any] = {
|
||||||
"descriptor": descriptor_name,
|
"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,
|
"drm": serialize_drm(track.drm) if hasattr(track, "drm") and track.drm else None,
|
||||||
"headers": headers,
|
"headers": headers,
|
||||||
"cookies": cookie_values(cookies),
|
"cookies": cookie_values(cookies),
|
||||||
|
|||||||
@@ -173,6 +173,10 @@ class TracksReply(TypedDict, total=False):
|
|||||||
sample_decrypt_tracks: list[str]
|
sample_decrypt_tracks: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
class SegmentsRequest(TypedDict):
|
||||||
|
track_ids: list[str]
|
||||||
|
|
||||||
|
|
||||||
class SegmentFilterRequest(TypedDict):
|
class SegmentFilterRequest(TypedDict):
|
||||||
track_id: str
|
track_id: str
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import shlex
|
|||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from collections.abc import Callable, Iterable, Iterator, Mapping
|
from collections.abc import Callable, Iterable, Iterator, Mapping
|
||||||
|
from functools import partial
|
||||||
from http.cookiejar import CookieJar
|
from http.cookiejar import CookieJar
|
||||||
from threading import Lock, local
|
from threading import Lock, local
|
||||||
from typing import (
|
from typing import (
|
||||||
@@ -58,6 +59,7 @@ from unshackle.core.remote_protocol import (
|
|||||||
SAMPLES_ROUTE,
|
SAMPLES_ROUTE,
|
||||||
SEARCH_ROUTE,
|
SEARCH_ROUTE,
|
||||||
SEGMENT_FILTER_ROUTE,
|
SEGMENT_FILTER_ROUTE,
|
||||||
|
SEGMENTS_ROUTE,
|
||||||
SERVICES_ROUTE,
|
SERVICES_ROUTE,
|
||||||
SESSION_CREATE_ROUTE,
|
SESSION_CREATE_ROUTE,
|
||||||
SESSION_ROUTE,
|
SESSION_ROUTE,
|
||||||
@@ -72,6 +74,7 @@ from unshackle.core.remote_protocol import (
|
|||||||
LicenseRequest,
|
LicenseRequest,
|
||||||
SegmentFilterReply,
|
SegmentFilterReply,
|
||||||
SegmentFilterRequest,
|
SegmentFilterRequest,
|
||||||
|
SegmentsRequest,
|
||||||
SessionClosed,
|
SessionClosed,
|
||||||
SessionCreate,
|
SessionCreate,
|
||||||
SessionCreated,
|
SessionCreated,
|
||||||
@@ -1439,6 +1442,8 @@ class RemoteService(TitleSource):
|
|||||||
for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]:
|
for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]:
|
||||||
if track.descriptor == Track.Descriptor.HLS:
|
if track.descriptor == Track.Descriptor.HLS:
|
||||||
track.OnSegmentFilter = self.remote_segment_filter(str(track.id))
|
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._tracks_by_title[title_id] = tracks
|
||||||
self._chapters_by_title[title_id] = result.get("chapters", [])
|
self._chapters_by_title[title_id] = result.get("chapters", [])
|
||||||
@@ -1794,6 +1799,24 @@ class RemoteService(TitleSource):
|
|||||||
)
|
)
|
||||||
return str(key)
|
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:
|
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."""
|
"""Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it."""
|
||||||
if isinstance(challenge, str):
|
if isinstance(challenge, str):
|
||||||
|
|||||||
@@ -480,6 +480,7 @@ class Track:
|
|||||||
|
|
||||||
self.path: Path | None = None
|
self.path: Path | None = None
|
||||||
self.url = url
|
self.url = url
|
||||||
|
self.resolve_url: Callable[[], str] | None = None
|
||||||
self.language = language
|
self.language = language
|
||||||
self.is_original_lang = is_original_lang
|
self.is_original_lang = is_original_lang
|
||||||
self.descriptor = descriptor
|
self.descriptor = descriptor
|
||||||
@@ -704,6 +705,15 @@ class Track:
|
|||||||
continue
|
continue
|
||||||
log.debug(f"No {systems[0].__name__} or {systems[1].__name__} PSSH was found for this track, is it DRM free?")
|
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(
|
def download(
|
||||||
self,
|
self,
|
||||||
session: AnySession,
|
session: AnySession,
|
||||||
@@ -820,6 +830,7 @@ class Track:
|
|||||||
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
||||||
elif self.descriptor == self.Descriptor.URL:
|
elif self.descriptor == self.Descriptor.URL:
|
||||||
try:
|
try:
|
||||||
|
self.ensure_url()
|
||||||
if (
|
if (
|
||||||
DOWNLOAD_ALL_DRM.is_set()
|
DOWNLOAD_ALL_DRM.is_set()
|
||||||
and track_type in ("Video", "Audio")
|
and track_type in ("Video", "Audio")
|
||||||
|
|||||||
+31
-6
@@ -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)])}
|
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]:
|
def serialize_video_track(track: Video, include_url: bool = False) -> dict[str, Any]:
|
||||||
"""Convert video track to JSON-serializable dict."""
|
"""Convert video track to JSON-serializable dict."""
|
||||||
codec_name = enum_name(track.codec)
|
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)),
|
"stereo": bool(getattr(track, "stereo", False)),
|
||||||
}
|
}
|
||||||
result.update(serialize_track_common(track))
|
result.update(serialize_track_common(track))
|
||||||
if include_url and hasattr(track, "url") and track.url:
|
if include_url:
|
||||||
result["url"] = str(track.url)
|
result.update(url_fields(track))
|
||||||
return result
|
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,
|
"descriptive": track.descriptive if hasattr(track, "descriptive") else False,
|
||||||
}
|
}
|
||||||
result.update(serialize_track_common(track))
|
result.update(serialize_track_common(track))
|
||||||
if include_url and hasattr(track, "url") and track.url:
|
if include_url:
|
||||||
result["url"] = str(track.url)
|
result.update(url_fields(track))
|
||||||
return result
|
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,
|
"cc": track.cc if hasattr(track, "cc") else False,
|
||||||
}
|
}
|
||||||
result.update(serialize_track_common(track))
|
result.update(serialize_track_common(track))
|
||||||
if include_url and hasattr(track, "url") and track.url:
|
if include_url:
|
||||||
result["url"] = str(track.url)
|
result.update(url_fields(track))
|
||||||
return result
|
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("audio", []), tracks.audio, strict=False),
|
||||||
*zip(data.get("subtitles", []), tracks.subtitles, 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"))
|
drm_objs = reconstruct_drm(track_data.get("drm"))
|
||||||
if drm_objs:
|
if drm_objs:
|
||||||
track_obj.drm = drm_objs
|
track_obj.drm = drm_objs
|
||||||
|
|||||||
Reference in New Issue
Block a user