mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-30 13:05:08 +00:00
refactor(wire): put the tracks reply codec in wire and stamp service flags in serialize_title
This commit is contained in:
@@ -311,7 +311,7 @@ These keys are sent only when the title carries them, so a title without them se
|
|||||||
|
|
||||||
### `POST /api/list-tracks`
|
### `POST /api/list-tracks`
|
||||||
|
|
||||||
Show the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes.
|
Show the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes. Each `title` in the response has the form of a [`list-titles`](#post-apilist-titles) title, with the same service flags (`anime`, `daily`, `metadata_provider`).
|
||||||
|
|
||||||
!!! tip "Spotting the original-language audio"
|
!!! tip "Spotting the original-language audio"
|
||||||
Each audio track carries `is_original`, which marks the track the default `lang` of `orig` selects. unshackle finds it with the same language matcher the downloader uses. Thus it stays correct for regional variants a client cannot separate from tag text alone (`pt` marks `pt-BR` rather than `pt-PT`). Services need not report a title's language, so every track can legitimately come back `false`.
|
Each audio track carries `is_original`, which marks the track the default `lang` of `orig` selects. unshackle finds it with the same language matcher the downloader uses. Thus it stays correct for regional variants a client cannot separate from tag text alone (`pt` marks `pt-BR` rather than `pt-PT`). Services need not report a title's language, so every track can legitimately come back `false`.
|
||||||
@@ -1151,7 +1151,7 @@ Get tracks and chapters for a specific title within the remote session. Body: `{
|
|||||||
|
|
||||||
### `POST /api/session/{session_id}/segments`
|
### `POST /api/session/{session_id}/segments`
|
||||||
|
|
||||||
Get the download URL, DRM info, headers, cookies, and raw track data for the selected tracks. Body: `{ "track_ids": ["v-1", "a-1"] }` (required). A track that the tracks response sent with `resolve_url` gets its URL from the service here. The server makes one service call at a time per remote session, so parallel requests wait for each other. A slow answer arrives as described in [Slow responses](#slow-responses).
|
Get the download URL, DRM info, headers, cookies, and track data for the selected tracks. Body: `{ "track_ids": ["v-1", "a-1"] }` (required). A track that the tracks response sent with `resolve_url` gets its URL from the service here. The server makes one service call at a time per remote session, so parallel requests wait for each other. A slow answer arrives as described in [Slow responses](#slow-responses).
|
||||||
|
|
||||||
=== "Response `200`"
|
=== "Response `200`"
|
||||||
|
|
||||||
@@ -1163,7 +1163,7 @@ Get the download URL, DRM info, headers, cookies, and raw track data for the sel
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`cookies` gives names and values only. `cookie_jar` gives the same cookies with their domain, path and `secure` flag, in the `session_cookie_jar` form of the tracks response.
|
`data` has the form of the track `data` in `list-tracks`: the JSON-safe part of the service-set `track.data`, without the `hls`, `dash`, and `ism` parser keys. `cookies` gives names and values only. `cookie_jar` gives the same cookies with their domain, path and `secure` flag, in the `session_cookie_jar` form of the tracks response.
|
||||||
|
|
||||||
| Status | Error code | Meaning |
|
| Status | Error code | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ def test_a_non_sport_episode_ignores_the_sports_template(templates):
|
|||||||
|
|
||||||
|
|
||||||
def test_the_sport_flag_survives_the_remote_round_trip():
|
def test_the_sport_flag_survives_the_remote_round_trip():
|
||||||
rebuilt = build_title(serialize_title(make_episode()), "TEST", fallback_id="x")
|
rebuilt = build_title(serialize_title(make_episode(), None), "TEST", fallback_id="x")
|
||||||
assert isinstance(rebuilt, Episode) and rebuilt.sport
|
assert isinstance(rebuilt, Episode) and rebuilt.sport
|
||||||
|
|
||||||
|
|
||||||
@@ -95,7 +95,7 @@ def test_the_sport_flag_survives_the_export_round_trip():
|
|||||||
|
|
||||||
|
|
||||||
def test_a_non_sport_episode_sends_no_sport_key():
|
def test_a_non_sport_episode_sends_no_sport_key():
|
||||||
assert "sport" not in serialize_title(make_episode(sport=False))
|
assert "sport" not in serialize_title(make_episode(sport=False), None)
|
||||||
|
|
||||||
|
|
||||||
def test_sports_templates_validate_without_warnings(recwarn):
|
def test_sports_templates_validate_without_warnings(recwarn):
|
||||||
|
|||||||
+92
-17
@@ -25,13 +25,15 @@ from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayRe
|
|||||||
from unshackle.core.import_service import ImportService
|
from unshackle.core.import_service import ImportService
|
||||||
from unshackle.core.titles import Episode, Movie, Song
|
from unshackle.core.titles import Episode, Movie, Song
|
||||||
from unshackle.core.titles.music import SONG_FIELDS
|
from unshackle.core.titles.music import SONG_FIELDS
|
||||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video
|
||||||
from unshackle.core.tracks.attachment import Attachment
|
from unshackle.core.tracks.attachment import Attachment
|
||||||
from unshackle.core.tracks.track import Track
|
from unshackle.core.tracks.track import Track
|
||||||
from unshackle.core.wire import (
|
from unshackle.core.wire import (
|
||||||
apply_title_fields,
|
apply_title_fields,
|
||||||
|
apply_tracks_reply,
|
||||||
attachment_to_dict,
|
attachment_to_dict,
|
||||||
build_attachment,
|
build_attachment,
|
||||||
|
build_chapters,
|
||||||
build_title,
|
build_title,
|
||||||
build_tracks,
|
build_tracks,
|
||||||
deserialize_audio,
|
deserialize_audio,
|
||||||
@@ -46,6 +48,7 @@ from unshackle.core.wire import (
|
|||||||
serialize_subtitle_track,
|
serialize_subtitle_track,
|
||||||
serialize_title,
|
serialize_title,
|
||||||
serialize_tracks,
|
serialize_tracks,
|
||||||
|
serialize_tracks_reply,
|
||||||
serialize_video_track,
|
serialize_video_track,
|
||||||
title_to_meta,
|
title_to_meta,
|
||||||
track_from_dict,
|
track_from_dict,
|
||||||
@@ -666,11 +669,11 @@ EPISODE_FIELDS = {
|
|||||||
|
|
||||||
|
|
||||||
def test_rest_episode() -> None:
|
def test_rest_episode() -> None:
|
||||||
assert serialize_title(full_episode()) == REST_EPISODE
|
assert serialize_title(full_episode(), None) == REST_EPISODE
|
||||||
|
|
||||||
|
|
||||||
def test_rest_episode_without_a_name_gets_a_placeholder_and_no_optional_keys() -> None:
|
def test_rest_episode_without_a_name_gets_a_placeholder_and_no_optional_keys() -> None:
|
||||||
assert serialize_title(episode(name=None)) == {
|
assert serialize_title(episode(name=None), None) == {
|
||||||
"type": "episode",
|
"type": "episode",
|
||||||
"name": "Episode 05",
|
"name": "Episode 05",
|
||||||
"id": "ep-0001",
|
"id": "ep-0001",
|
||||||
@@ -687,15 +690,15 @@ def test_rest_episode_without_a_name_gets_a_placeholder_and_no_optional_keys() -
|
|||||||
|
|
||||||
|
|
||||||
def test_rest_movie() -> None:
|
def test_rest_movie() -> None:
|
||||||
assert serialize_title(movie()) == REST_MOVIE
|
assert serialize_title(movie(), None) == REST_MOVIE
|
||||||
|
|
||||||
|
|
||||||
def test_rest_song() -> None:
|
def test_rest_song() -> None:
|
||||||
assert serialize_title(song()) == REST_SONG
|
assert serialize_title(song(), None) == REST_SONG
|
||||||
|
|
||||||
|
|
||||||
def test_rest_title_of_no_known_kind() -> None:
|
def test_rest_title_of_no_known_kind() -> None:
|
||||||
assert serialize_title(OtherTitle()) == {
|
assert serialize_title(OtherTitle(), None) == {
|
||||||
"type": "other",
|
"type": "other",
|
||||||
"name": "Other Thing",
|
"name": "Other Thing",
|
||||||
"id": "other-0001",
|
"id": "other-0001",
|
||||||
@@ -707,8 +710,8 @@ def test_rest_title_of_no_known_kind() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_rest_title_key_order_is_stable() -> None:
|
def test_rest_title_key_order_is_stable() -> None:
|
||||||
assert list(serialize_title(full_episode())) == list(REST_EPISODE)
|
assert list(serialize_title(full_episode(), None)) == list(REST_EPISODE)
|
||||||
assert list(serialize_title(song())) == list(REST_SONG)
|
assert list(serialize_title(song(), None)) == list(REST_SONG)
|
||||||
|
|
||||||
|
|
||||||
def test_export_episode_meta() -> None:
|
def test_export_episode_meta() -> None:
|
||||||
@@ -741,7 +744,7 @@ def test_build_title_from_rest_episode() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_build_title_drops_the_placeholder_name() -> None:
|
def test_build_title_drops_the_placeholder_name() -> None:
|
||||||
title = build_title(json_copy(serialize_title(episode(name=None))), "EXAMPLE", "fallback-id")
|
title = build_title(json_copy(serialize_title(episode(name=None), None)), "EXAMPLE", "fallback-id")
|
||||||
assert title_fields(title) == {
|
assert title_fields(title) == {
|
||||||
**EPISODE_FIELDS,
|
**EPISODE_FIELDS,
|
||||||
"name": None,
|
"name": None,
|
||||||
@@ -810,7 +813,7 @@ def test_build_title_from_a_bare_episode_uses_the_fallbacks() -> None:
|
|||||||
|
|
||||||
def test_build_title_refuses_an_unknown_kind() -> None:
|
def test_build_title_refuses_an_unknown_kind() -> None:
|
||||||
with pytest.raises(click.ClickException, match="unknown title type 'other'"):
|
with pytest.raises(click.ClickException, match="unknown title type 'other'"):
|
||||||
build_title(json_copy(serialize_title(OtherTitle())), "EXAMPLE", "fallback-id")
|
build_title(json_copy(serialize_title(OtherTitle(), None)), "EXAMPLE", "fallback-id")
|
||||||
|
|
||||||
|
|
||||||
def test_apply_title_fields_keeps_season_and_number() -> None:
|
def test_apply_title_fields_keeps_season_and_number() -> None:
|
||||||
@@ -1149,10 +1152,10 @@ def test_build_attachment_by_url_and_with_nothing() -> None:
|
|||||||
|
|
||||||
def test_rest_titles_round_trip() -> None:
|
def test_rest_titles_round_trip() -> None:
|
||||||
for title in (full_episode(), movie()):
|
for title in (full_episode(), movie()):
|
||||||
assert title_fields(build_title(json_copy(serialize_title(title)), "EXAMPLE", "fallback-id")) == title_fields(
|
assert title_fields(
|
||||||
title
|
build_title(json_copy(serialize_title(title, None)), "EXAMPLE", "fallback-id")
|
||||||
)
|
) == title_fields(title)
|
||||||
rebuilt = title_fields(build_title(json_copy(serialize_title(song())), "EXAMPLE", "fallback-id"))
|
rebuilt = title_fields(build_title(json_copy(serialize_title(song(), None)), "EXAMPLE", "fallback-id"))
|
||||||
assert {**rebuilt, "data": None} == {**title_fields(song()), "data": None}
|
assert {**rebuilt, "data": None} == {**title_fields(song()), "data": None}
|
||||||
|
|
||||||
|
|
||||||
@@ -1285,6 +1288,10 @@ NOT_SENT = {"session", "downloader", "downloader_args", "from_file", "extra", "s
|
|||||||
NOT_EXPORTED = NOT_SENT | {"closed_captions", "drm", "description"}
|
NOT_EXPORTED = NOT_SENT | {"closed_captions", "drm", "description"}
|
||||||
|
|
||||||
|
|
||||||
|
def rest_title(title: Any) -> dict[str, Any]:
|
||||||
|
return serialize_title(title, None)
|
||||||
|
|
||||||
|
|
||||||
def constructor_fields(cls: type) -> set[str]:
|
def constructor_fields(cls: type) -> set[str]:
|
||||||
"""The constructor parameters of a track or title class, under the name its wire form uses."""
|
"""The constructor parameters of a track or title class, under the name its wire form uses."""
|
||||||
classes = [cls, Track] if issubclass(cls, Track) else [cls]
|
classes = [cls, Track] if issubclass(cls, Track) else [cls]
|
||||||
@@ -1298,9 +1305,9 @@ def constructor_fields(cls: type) -> set[str]:
|
|||||||
(video, lambda t: serialize_video_track(t, include_url=True), track_to_dict),
|
(video, lambda t: serialize_video_track(t, include_url=True), track_to_dict),
|
||||||
(audio, lambda t: serialize_audio_track(t, include_url=True), track_to_dict),
|
(audio, lambda t: serialize_audio_track(t, include_url=True), track_to_dict),
|
||||||
(subtitle, lambda t: serialize_subtitle_track(t, include_url=True), track_to_dict),
|
(subtitle, lambda t: serialize_subtitle_track(t, include_url=True), track_to_dict),
|
||||||
(full_episode, serialize_title, title_to_meta),
|
(full_episode, rest_title, title_to_meta),
|
||||||
(movie, serialize_title, title_to_meta),
|
(movie, rest_title, title_to_meta),
|
||||||
(song, serialize_title, None),
|
(song, rest_title, None),
|
||||||
],
|
],
|
||||||
ids=["video", "audio", "subtitle", "episode", "movie", "song"],
|
ids=["video", "audio", "subtitle", "episode", "movie", "song"],
|
||||||
)
|
)
|
||||||
@@ -1322,3 +1329,71 @@ def test_each_module_imports_first_in_a_new_interpreter(module: str) -> None:
|
|||||||
root = Path(__file__).resolve().parents[2]
|
root = Path(__file__).resolve().parents[2]
|
||||||
result = subprocess.run([sys.executable, "-c", f"import {module}"], cwd=root, capture_output=True, check=False)
|
result = subprocess.run([sys.executable, "-c", f"import {module}"], cwd=root, capture_output=True, check=False)
|
||||||
assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
|
assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
class FLAGGED:
|
||||||
|
ANIME = True
|
||||||
|
METADATA_PROVIDER = "tmdb"
|
||||||
|
|
||||||
|
|
||||||
|
def tracks_reply(scrub_data: Any = lambda data: data) -> dict[str, Any]:
|
||||||
|
tracks = Tracks([video(), audio(), subtitle()])
|
||||||
|
tracks.attachments.append(Attachment(url="https://img.example/p.jpg", name="P"))
|
||||||
|
chapters = [Chapter("00:00:00.000"), Chapter("00:05:00.000", "Story")]
|
||||||
|
reply = serialize_tracks_reply(movie(), tracks, chapters, FLAGGED(), scrub_data)
|
||||||
|
return json_copy(
|
||||||
|
{
|
||||||
|
**reply,
|
||||||
|
"session_headers": {"X-Token": "t", "Host": "h"},
|
||||||
|
"session_cookie_jar": [{"name": "sid", "value": "s", "domain": ".example.com", "path": "/"}],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_tracks_reply_carries_the_title_with_the_service_flags_and_no_parser_data() -> None:
|
||||||
|
reply = tracks_reply()
|
||||||
|
assert list(reply)[:6] == ["title", "video", "audio", "subtitles", "attachments", "chapters"]
|
||||||
|
assert (reply["title"]["anime"], reply["title"]["metadata_provider"]) == (True, "tmdb")
|
||||||
|
assert reply["video"][0]["data"] == {"service_value": {"a": 1}}
|
||||||
|
assert reply["video"][0]["url"] == "https://cdn.example/video.mpd"
|
||||||
|
assert reply["chapters"] == [
|
||||||
|
{"timestamp": "00:00:00.000", "name": None},
|
||||||
|
{"timestamp": "00:05:00.000", "name": "Story"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_tracks_reply_scrubs_each_track_data() -> None:
|
||||||
|
reply = tracks_reply(lambda data: None)
|
||||||
|
assert [d["data"] for d in reply["video"] + reply["audio"] + reply["subtitles"]] == [None, None, None]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_tracks_reply_round_trips() -> None:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
reply = tracks_reply()
|
||||||
|
title = build_title({"type": "movie", "id": "movie-0001"}, "EXAMPLE", "movie-0001")
|
||||||
|
session = requests.Session()
|
||||||
|
tracks = apply_tracks_reply(reply, title, session)
|
||||||
|
assert [str(t.id) for t in tracks] == ["video-0001", "audio-0001", "sub-0001"]
|
||||||
|
assert tracks.videos[0].data == {"service_value": {"a": 1}}
|
||||||
|
assert [(a.name, a.url) for a in tracks.attachments] == [("P", "https://img.example/p.jpg")]
|
||||||
|
assert (title.anime, title.metadata_provider) == (True, "tmdb")
|
||||||
|
assert session.headers["X-Token"] == "t"
|
||||||
|
assert session.headers.get("Host") is None
|
||||||
|
assert session.cookies.get("sid", domain=".example.com") == "s"
|
||||||
|
assert [(c.timestamp, c.name) for c in build_chapters(reply["chapters"])] == [
|
||||||
|
("00:00:00.000", None),
|
||||||
|
("00:05:00.000", "Story"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_tracks_reply_restores_the_manifest_snapshot() -> None:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from tests.core.test_manifest_snapshot import service_tracks
|
||||||
|
from unshackle.core.manifests.snapshot import capture
|
||||||
|
|
||||||
|
tracks = service_tracks()
|
||||||
|
reply = json_copy({**serialize_tracks_reply(movie(), tracks, [], None, lambda data: data), **capture(tracks)})
|
||||||
|
decoded = apply_tracks_reply(reply, movie(), requests.Session())
|
||||||
|
assert [str(t.id) for t in decoded if "dash" in t.data] == [str(t.id) for t in tracks]
|
||||||
|
|||||||
@@ -20,31 +20,31 @@ def episode(data=None):
|
|||||||
@pytest.mark.parametrize("value", [None, [], "denied", {}, {"paid": 1}, {"access": "false"}, {"access": []}])
|
@pytest.mark.parametrize("value", [None, [], "denied", {}, {"paid": 1}, {"access": "false"}, {"access": []}])
|
||||||
def test_invalid_metadata_is_omitted(value):
|
def test_invalid_metadata_is_omitted(value):
|
||||||
assert availability_metadata(value) is None
|
assert availability_metadata(value) is None
|
||||||
assert "availability" not in serialize_title(episode({"availability": value}))
|
assert "availability" not in serialize_title(episode({"availability": value}), None)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("access", ["granted", "denied", "unknown"])
|
@pytest.mark.parametrize("access", ["granted", "denied", "unknown"])
|
||||||
def test_paid_and_access_are_independent_and_round_trip(access):
|
def test_paid_and_access_are_independent_and_round_trip(access):
|
||||||
data = {"paid": True, "access": access}
|
data = {"paid": True, "access": access}
|
||||||
serialized = serialize_title(episode({"availability": data}))
|
serialized = serialize_title(episode({"availability": data}), None)
|
||||||
assert serialized["availability"] == data
|
assert serialized["availability"] == data
|
||||||
assert build_title(serialized, "EXAMPLE", "fallback").data["availability"] == data
|
assert build_title(serialized, "EXAMPLE", "fallback").data["availability"] == data
|
||||||
|
|
||||||
|
|
||||||
def test_private_data_and_unknown_fields_never_leak():
|
def test_private_data_and_unknown_fields_never_leak():
|
||||||
data = {"availability": {"paid": False, "access": "unknown", "token": "secret"}, "cookies": "secret"}
|
data = {"availability": {"paid": False, "access": "unknown", "token": "secret"}, "cookies": "secret"}
|
||||||
result = serialize_title(episode(data))
|
result = serialize_title(episode(data), None)
|
||||||
assert result["availability"] == {"paid": False, "access": "unknown"}
|
assert result["availability"] == {"paid": False, "access": "unknown"}
|
||||||
assert "secret" not in str(result)
|
assert "secret" not in str(result)
|
||||||
assert data["availability"]["token"] == "secret"
|
assert data["availability"]["token"] == "secret"
|
||||||
|
|
||||||
|
|
||||||
def test_missing_metadata_keeps_response_unchanged():
|
def test_missing_metadata_keeps_response_unchanged():
|
||||||
assert "availability" not in serialize_title(episode())
|
assert "availability" not in serialize_title(episode(), None)
|
||||||
|
|
||||||
|
|
||||||
def test_remote_input_is_also_allowlisted():
|
def test_remote_input_is_also_allowlisted():
|
||||||
info = serialize_title(episode())
|
info = serialize_title(episode(), None)
|
||||||
info["availability"] = {"paid": True, "access": "denied", "cookies": "secret"}
|
info["availability"] = {"paid": True, "access": "denied", "cookies": "secret"}
|
||||||
rebuilt = build_title(info, "EXAMPLE", "fallback")
|
rebuilt = build_title(info, "EXAMPLE", "fallback")
|
||||||
assert rebuilt.data["availability"] == {"paid": True, "access": "denied"}
|
assert rebuilt.data["availability"] == {"paid": True, "access": "denied"}
|
||||||
@@ -54,8 +54,8 @@ def test_availability_appends_without_reordering_existing_fields():
|
|||||||
title = episode()
|
title = episode()
|
||||||
title.part = 2
|
title.part = 2
|
||||||
title.anime = True
|
title.anime = True
|
||||||
original = serialize_title(title)
|
original = serialize_title(title, None)
|
||||||
title.data = {"availability": {"paid": True, "access": "granted"}}
|
title.data = {"availability": {"paid": True, "access": "granted"}}
|
||||||
serialized = serialize_title(title)
|
serialized = serialize_title(title, None)
|
||||||
assert list(serialized) == [*original, "availability"]
|
assert list(serialized) == [*original, "availability"]
|
||||||
assert {key: serialized[key] for key in original} == original
|
assert {key: serialized[key] for key in original} == original
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ def selected(result: dict[str, Any]) -> list[str]:
|
|||||||
|
|
||||||
|
|
||||||
def test_partless_episode_json_has_no_part_key() -> None:
|
def test_partless_episode_json_has_no_part_key() -> None:
|
||||||
d = serialize_title(ep(part=None))
|
d = serialize_title(ep(part=None), None)
|
||||||
assert "part" not in d
|
assert "part" not in d
|
||||||
assert list(d.keys()) == [
|
assert list(d.keys()) == [
|
||||||
"type",
|
"type",
|
||||||
@@ -103,24 +103,24 @@ def test_partless_episode_json_has_no_part_key() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_partful_episode_json_carries_part_last() -> None:
|
def test_partful_episode_json_carries_part_last() -> None:
|
||||||
d = serialize_title(ep(part=2))
|
d = serialize_title(ep(part=2), None)
|
||||||
assert d["part"] == 2
|
assert d["part"] == 2
|
||||||
# additive: `part` is appended, every pre-existing key keeps its position
|
# additive: `part` is appended, every pre-existing key keeps its position
|
||||||
assert list(d.keys())[:11] == list(serialize_title(ep(part=None)).keys())
|
assert list(d.keys())[:11] == list(serialize_title(ep(part=None), None).keys())
|
||||||
assert list(d.keys())[11] == "part"
|
assert list(d.keys())[11] == "part"
|
||||||
|
|
||||||
|
|
||||||
def test_part_stays_out_of_the_name_field() -> None:
|
def test_part_stays_out_of_the_name_field() -> None:
|
||||||
"""`name` is a reconstruction input for build_title, not a display string."""
|
"""`name` is a reconstruction input for build_title, not a display string."""
|
||||||
assert serialize_title(ep(part=2))["name"] == "Pilot"
|
assert serialize_title(ep(part=2), None)["name"] == "Pilot"
|
||||||
assert serialize_title(ep(part=3, name=None))["name"] == "Episode 01"
|
assert serialize_title(ep(part=3, name=None), None)["name"] == "Episode 01"
|
||||||
|
|
||||||
|
|
||||||
def test_remote_build_title_round_trip() -> None:
|
def test_remote_build_title_round_trip() -> None:
|
||||||
rebuilt = build_title(serialize_title(ep(1, 4, 2)), "FAKE", "fallback-id")
|
rebuilt = build_title(serialize_title(ep(1, 4, 2), None), "FAKE", "fallback-id")
|
||||||
assert (rebuilt.season, rebuilt.number, rebuilt.part, rebuilt.name) == (1, 4, 2, "Pilot")
|
assert (rebuilt.season, rebuilt.number, rebuilt.part, rebuilt.name) == (1, 4, 2, "Pilot")
|
||||||
|
|
||||||
partless = build_title(serialize_title(ep(1, 4, None)), "FAKE", "fallback-id")
|
partless = build_title(serialize_title(ep(1, 4, None), None), "FAKE", "fallback-id")
|
||||||
assert partless.part is None
|
assert partless.part is None
|
||||||
|
|
||||||
|
|
||||||
@@ -129,7 +129,9 @@ def test_movie_json_unaffected() -> None:
|
|||||||
|
|
||||||
from unshackle.core.titles.movie import Movie
|
from unshackle.core.titles.movie import Movie
|
||||||
|
|
||||||
d = serialize_title(Movie(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en")))
|
d = serialize_title(
|
||||||
|
Movie(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en")), None
|
||||||
|
)
|
||||||
assert "part" not in d
|
assert "part" not in d
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ from unshackle.core.api import handlers
|
|||||||
from unshackle.core.titles.episode import Episode
|
from unshackle.core.titles.episode import Episode
|
||||||
from unshackle.core.titles.movie import Movie
|
from unshackle.core.titles.movie import Movie
|
||||||
from unshackle.core.titles.music import Song
|
from unshackle.core.titles.music import Song
|
||||||
from unshackle.core.wire import build_title, serialize_title, stamp_service_flags
|
from unshackle.core.tracks import Tracks
|
||||||
|
from unshackle.core.wire import build_title, serialize_title
|
||||||
|
|
||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
@@ -53,25 +54,25 @@ NEW_KEYS = ("air_date", "absolute", "daily", "anime", "metadata_provider")
|
|||||||
|
|
||||||
|
|
||||||
def test_a_plain_episode_gains_no_new_keys() -> None:
|
def test_a_plain_episode_gains_no_new_keys() -> None:
|
||||||
d = serialize_title(ep())
|
d = serialize_title(ep(), None)
|
||||||
assert not [k for k in NEW_KEYS if k in d]
|
assert not [k for k in NEW_KEYS if k in d]
|
||||||
|
|
||||||
|
|
||||||
def test_a_plain_movie_gains_no_new_keys() -> None:
|
def test_a_plain_movie_gains_no_new_keys() -> None:
|
||||||
d = serialize_title(_movie())
|
d = serialize_title(_movie(), None)
|
||||||
assert not [k for k in NEW_KEYS if k in d]
|
assert not [k for k in NEW_KEYS if k in d]
|
||||||
|
|
||||||
|
|
||||||
def test_air_date_is_serialized_as_an_iso_string() -> None:
|
def test_air_date_is_serialized_as_an_iso_string() -> None:
|
||||||
assert serialize_title(ep(air_date=date(2026, 8, 11)))["air_date"] == "2026-08-11"
|
assert serialize_title(ep(air_date=date(2026, 8, 11)), None)["air_date"] == "2026-08-11"
|
||||||
|
|
||||||
|
|
||||||
def test_an_unparseable_air_date_is_serialized_as_text() -> None:
|
def test_an_unparseable_air_date_is_serialized_as_text() -> None:
|
||||||
assert serialize_title(ep(air_date="soon"))["air_date"] == "soon"
|
assert serialize_title(ep(air_date="soon"), None)["air_date"] == "soon"
|
||||||
|
|
||||||
|
|
||||||
def test_absolute_is_serialized() -> None:
|
def test_absolute_is_serialized() -> None:
|
||||||
assert serialize_title(ep(absolute=57))["absolute"] == 57
|
assert serialize_title(ep(absolute=57), None)["absolute"] == 57
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value", [True, False])
|
@pytest.mark.parametrize("value", [True, False])
|
||||||
@@ -79,14 +80,14 @@ def test_per_title_daily_and_anime_are_serialized_both_ways(value: bool) -> None
|
|||||||
episode = ep()
|
episode = ep()
|
||||||
episode.daily = value
|
episode.daily = value
|
||||||
episode.anime = value
|
episode.anime = value
|
||||||
d = serialize_title(episode)
|
d = serialize_title(episode, None)
|
||||||
assert (d["daily"], d["anime"]) == (value, value)
|
assert (d["daily"], d["anime"]) == (value, value)
|
||||||
|
|
||||||
|
|
||||||
def test_a_movie_carries_the_anime_flag_but_never_daily() -> None:
|
def test_a_movie_carries_the_anime_flag_but_never_daily() -> None:
|
||||||
movie = _movie()
|
movie = _movie()
|
||||||
movie.anime = True
|
movie.anime = True
|
||||||
d = serialize_title(movie)
|
d = serialize_title(movie, None)
|
||||||
assert d["anime"] is True
|
assert d["anime"] is True
|
||||||
assert "daily" not in d
|
assert "daily" not in d
|
||||||
|
|
||||||
@@ -101,7 +102,7 @@ class _PlainSvc:
|
|||||||
|
|
||||||
|
|
||||||
def test_the_stamp_fills_both_flags_from_the_service_class() -> None:
|
def test_the_stamp_fills_both_flags_from_the_service_class() -> None:
|
||||||
d = stamp_service_flags(serialize_title(ep()), _AnimeDailySvc())
|
d = serialize_title(ep(), _AnimeDailySvc())
|
||||||
assert (d["anime"], d["daily"]) == (True, True)
|
assert (d["anime"], d["daily"]) == (True, True)
|
||||||
|
|
||||||
|
|
||||||
@@ -109,12 +110,12 @@ def test_the_stamp_never_overrides_a_per_title_false() -> None:
|
|||||||
episode = ep()
|
episode = ep()
|
||||||
episode.anime = False
|
episode.anime = False
|
||||||
episode.daily = False
|
episode.daily = False
|
||||||
d = stamp_service_flags(serialize_title(episode), _AnimeDailySvc())
|
d = serialize_title(episode, _AnimeDailySvc())
|
||||||
assert (d["anime"], d["daily"]) == (False, False)
|
assert (d["anime"], d["daily"]) == (False, False)
|
||||||
|
|
||||||
|
|
||||||
def test_a_plain_service_stamps_nothing() -> None:
|
def test_a_plain_service_stamps_nothing() -> None:
|
||||||
d = stamp_service_flags(serialize_title(ep()), _PlainSvc())
|
d = serialize_title(ep(), _PlainSvc())
|
||||||
assert not [k for k in NEW_KEYS if k in d]
|
assert not [k for k in NEW_KEYS if k in d]
|
||||||
|
|
||||||
|
|
||||||
@@ -124,13 +125,13 @@ class _ProviderSvc:
|
|||||||
|
|
||||||
@pytest.mark.parametrize("make", [ep, _movie], ids=["episode", "movie"])
|
@pytest.mark.parametrize("make", [ep, _movie], ids=["episode", "movie"])
|
||||||
def test_the_stamp_fills_the_metadata_provider_from_the_service_class(make: Any) -> None:
|
def test_the_stamp_fills_the_metadata_provider_from_the_service_class(make: Any) -> None:
|
||||||
assert stamp_service_flags(serialize_title(make()), _ProviderSvc())["metadata_provider"] == "tmdb"
|
assert serialize_title(make(), _ProviderSvc())["metadata_provider"] == "tmdb"
|
||||||
|
|
||||||
|
|
||||||
def test_the_stamp_keeps_a_per_title_metadata_provider() -> None:
|
def test_the_stamp_keeps_a_per_title_metadata_provider() -> None:
|
||||||
episode = ep()
|
episode = ep()
|
||||||
episode.metadata_provider = "tvdb"
|
episode.metadata_provider = "tvdb"
|
||||||
assert stamp_service_flags(serialize_title(episode), _ProviderSvc())["metadata_provider"] == "tvdb"
|
assert serialize_title(episode, _ProviderSvc())["metadata_provider"] == "tvdb"
|
||||||
|
|
||||||
|
|
||||||
def test_the_metadata_provider_survives_the_round_trip() -> None:
|
def test_the_metadata_provider_survives_the_round_trip() -> None:
|
||||||
@@ -145,7 +146,7 @@ def test_title_to_meta_round_trip_keeps_the_metadata_provider() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_a_movie_is_never_stamped_daily() -> None:
|
def test_a_movie_is_never_stamped_daily() -> None:
|
||||||
d = stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
|
d = serialize_title(_movie(), _AnimeDailySvc())
|
||||||
assert d["anime"] is True
|
assert d["anime"] is True
|
||||||
assert "daily" not in d
|
assert "daily" not in d
|
||||||
|
|
||||||
@@ -160,6 +161,20 @@ class _FakeService:
|
|||||||
def get_titles(self) -> list[Episode]:
|
def get_titles(self) -> list[Episode]:
|
||||||
return self._titles
|
return self._titles
|
||||||
|
|
||||||
|
def get_tracks(self, title: Episode) -> Tracks:
|
||||||
|
return Tracks()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("wanted", [None, "S01"], ids=["one-title", "episodes"])
|
||||||
|
def test_list_tracks_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch, wanted: str | None) -> None:
|
||||||
|
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
||||||
|
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([ep(), ep(number=2)]))
|
||||||
|
response = asyncio.run(handlers.list_tracks_handler({"service": "FAKE", "title_id": "t1", "wanted": wanted}))
|
||||||
|
body = json.loads(response.body)
|
||||||
|
titles = [e["title"] for e in body["episodes"]] if wanted else [body["title"]]
|
||||||
|
assert len(titles) == (2 if wanted else 1)
|
||||||
|
assert all((t["anime"], t["daily"]) == (True, True) for t in titles)
|
||||||
|
|
||||||
|
|
||||||
def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
||||||
@@ -170,10 +185,7 @@ def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -
|
|||||||
|
|
||||||
|
|
||||||
def round_trip(episode: Episode, stamp: Any | None = None) -> Episode:
|
def round_trip(episode: Episode, stamp: Any | None = None) -> Episode:
|
||||||
info = serialize_title(episode)
|
return build_title(serialize_title(episode, stamp), "FAKE", "fallback-id")
|
||||||
if stamp is not None:
|
|
||||||
info = stamp_service_flags(info, stamp)
|
|
||||||
return build_title(info, "FAKE", "fallback-id")
|
|
||||||
|
|
||||||
|
|
||||||
def test_serialize_round_trip_keeps_the_new_fields() -> None:
|
def test_serialize_round_trip_keeps_the_new_fields() -> None:
|
||||||
@@ -208,7 +220,7 @@ def test_a_per_title_false_survives_the_round_trip() -> None:
|
|||||||
def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
|
def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
|
||||||
movie = _movie()
|
movie = _movie()
|
||||||
movie.anime = True
|
movie.anime = True
|
||||||
rebuilt = build_title(serialize_title(movie), "FAKE", "fallback-id")
|
rebuilt = build_title(serialize_title(movie, None), "FAKE", "fallback-id")
|
||||||
assert isinstance(rebuilt, Movie)
|
assert isinstance(rebuilt, Movie)
|
||||||
assert rebuilt.anime is True
|
assert rebuilt.anime is True
|
||||||
|
|
||||||
@@ -259,7 +271,7 @@ def test_song_tag_data_survives_the_remote_round_trip() -> None:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
rebuilt = build_title(json.loads(json.dumps(serialize_title(song))), "EXAMPLE", "song-0001")
|
rebuilt = build_title(json.loads(json.dumps(serialize_title(song, None))), "EXAMPLE", "song-0001")
|
||||||
|
|
||||||
assert rebuilt.data["release_date"] == "2020-01-02"
|
assert rebuilt.data["release_date"] == "2020-01-02"
|
||||||
assert rebuilt.data["composer"] == "C"
|
assert rebuilt.data["composer"] == "C"
|
||||||
@@ -275,7 +287,7 @@ def test_song_tag_data_survives_the_remote_round_trip() -> None:
|
|||||||
)
|
)
|
||||||
def test_the_client_keeps_only_known_music_data_keys(music_data: Any) -> None:
|
def test_the_client_keeps_only_known_music_data_keys(music_data: Any) -> None:
|
||||||
song = Song(id_="song-0001", service=_FakeSvc, name="Track 1", artist="A", album="B", track=1)
|
song = Song(id_="song-0001", service=_FakeSvc, name="Track 1", artist="A", album="B", track=1)
|
||||||
info = json.loads(json.dumps(serialize_title(song)))
|
info = json.loads(json.dumps(serialize_title(song, None)))
|
||||||
info["music_data"] = music_data
|
info["music_data"] = music_data
|
||||||
|
|
||||||
rebuilt = build_title(info, "EXAMPLE", "song-0001")
|
rebuilt = build_title(info, "EXAMPLE", "song-0001")
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ def test_sanitize_log(raw, expected: str) -> None:
|
|||||||
|
|
||||||
def test_serialize_title_movie() -> None:
|
def test_serialize_title_movie() -> None:
|
||||||
movie = Movie(id_="movie-0001", service=_FakeSvc, name="Title X", year=2024, language=Language.get("en"))
|
movie = Movie(id_="movie-0001", service=_FakeSvc, name="Title X", year=2024, language=Language.get("en"))
|
||||||
d = serialize_title(movie)
|
d = serialize_title(movie, None)
|
||||||
assert d["type"] == "movie"
|
assert d["type"] == "movie"
|
||||||
assert d["name"] == "Title X"
|
assert d["name"] == "Title X"
|
||||||
assert d["year"] == 2024
|
assert d["year"] == 2024
|
||||||
@@ -121,7 +121,7 @@ def test_serialize_title_episode_named() -> None:
|
|||||||
year=2024,
|
year=2024,
|
||||||
language=Language.get("en"),
|
language=Language.get("en"),
|
||||||
)
|
)
|
||||||
d = serialize_title(ep)
|
d = serialize_title(ep, None)
|
||||||
assert d["type"] == "episode"
|
assert d["type"] == "episode"
|
||||||
assert d["series_title"] == "My Show"
|
assert d["series_title"] == "My Show"
|
||||||
assert d["season"] == 2
|
assert d["season"] == 2
|
||||||
@@ -140,7 +140,7 @@ def test_serialize_title_episode_unnamed_falls_back_to_number() -> None:
|
|||||||
year=None,
|
year=None,
|
||||||
language=Language.get("en"),
|
language=Language.get("en"),
|
||||||
)
|
)
|
||||||
d = serialize_title(ep)
|
d = serialize_title(ep, None)
|
||||||
assert d["name"] == "Episode 05"
|
assert d["name"] == "Episode 05"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from tests.remote.sessions import session_entry
|
|||||||
from unshackle.core.api import server_keys
|
from unshackle.core.api import server_keys
|
||||||
from unshackle.core.api.errors import APIError
|
from unshackle.core.api.errors import APIError
|
||||||
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data
|
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data
|
||||||
from unshackle.core.remote_service import apply_session_cookies
|
from unshackle.core.wire import apply_session_cookies
|
||||||
|
|
||||||
|
|
||||||
def _session(client_auth):
|
def _session(client_auth):
|
||||||
@@ -75,44 +75,92 @@ def test_rnet_session_sends_client_and_set_cookies():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def test_tracks_response_carries_the_cookie_jar():
|
def call_session_handler(handler, body, service, **entry_fields):
|
||||||
|
"""The JSON body that a session route handler answers for a remote session with these fields."""
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from unshackle.core.api import session_store as store_mod
|
from unshackle.core.api import session_store as store_mod
|
||||||
from unshackle.core.api.handlers import session_tracks_handler
|
|
||||||
from unshackle.core.tracks import Tracks
|
|
||||||
|
|
||||||
cookie = SimpleNamespace(name="sid", value="secret", domain=".example.com", path="/", secure=True)
|
|
||||||
|
|
||||||
class StubService:
|
|
||||||
session = SimpleNamespace(headers={}, cookies=[cookie])
|
|
||||||
|
|
||||||
def get_tracks(self, title):
|
|
||||||
return Tracks()
|
|
||||||
|
|
||||||
def get_chapters(self, title):
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
async def run():
|
async def run():
|
||||||
store = store_mod.get_session_store()
|
store = store_mod.get_session_store()
|
||||||
entry = await store.create(
|
entry = await store.create(service_tag="EXAMPLE", service_instance=service, session_id="s", owner_key=None)
|
||||||
service_tag="EXAMPLE", service_instance=StubService(), session_id="jar", owner_key=None
|
for name, value in entry_fields.items():
|
||||||
)
|
setattr(entry, name, value)
|
||||||
entry.title_map = {"t1": "Example Title"}
|
|
||||||
entry.client_auth = True
|
|
||||||
try:
|
try:
|
||||||
return json.loads((await session_tracks_handler({"title_id": "t1"}, "jar")).body)
|
return json.loads((await handler(body, "s")).body)
|
||||||
finally:
|
finally:
|
||||||
await store.delete("jar")
|
await store.delete("s")
|
||||||
|
|
||||||
body = asyncio.run(run())
|
return asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
class StubService:
|
||||||
|
def __init__(self, tracks=(), cookies=()):
|
||||||
|
self.session = SimpleNamespace(headers={}, cookies=list(cookies))
|
||||||
|
self.tracks = list(tracks)
|
||||||
|
|
||||||
|
def get_tracks(self, title):
|
||||||
|
from unshackle.core.tracks import Tracks
|
||||||
|
|
||||||
|
return Tracks(self.tracks)
|
||||||
|
|
||||||
|
def get_chapters(self, title):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def decrypts_samples(self, track):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def stub_video():
|
||||||
|
from unshackle.core.tracks import Video
|
||||||
|
|
||||||
|
return Video(url="https://cdn.example.com/v.mp4", language="en", codec=Video.Codec.AVC, id_="v1")
|
||||||
|
|
||||||
|
|
||||||
|
def test_tracks_response_carries_the_cookie_jar():
|
||||||
|
from unshackle.core.api.handlers import session_tracks_handler
|
||||||
|
|
||||||
|
cookie = SimpleNamespace(name="sid", value="secret", domain=".example.com", path="/", secure=True)
|
||||||
|
body = call_session_handler(
|
||||||
|
session_tracks_handler,
|
||||||
|
{"title_id": "t1"},
|
||||||
|
StubService(cookies=[cookie]),
|
||||||
|
title_map={"t1": "Example Title"},
|
||||||
|
client_auth=True,
|
||||||
|
)
|
||||||
assert body["session_cookies"] == {"sid": "secret"}
|
assert body["session_cookies"] == {"sid": "secret"}
|
||||||
assert body["session_cookie_jar"] == [
|
assert body["session_cookie_jar"] == [
|
||||||
{"name": "sid", "value": "secret", "domain": ".example.com", "path": "/", "secure": True}
|
{"name": "sid", "value": "secret", "domain": ".example.com", "path": "/", "secure": True}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_tracks_reply_scrubs_track_data_on_a_server_login():
|
||||||
|
from unshackle.core.api.handlers import session_tracks_handler
|
||||||
|
|
||||||
|
track = stub_video()
|
||||||
|
track.data.update(api_token="secret", keep=1)
|
||||||
|
body = call_session_handler(
|
||||||
|
session_tracks_handler,
|
||||||
|
{"title_id": "t1"},
|
||||||
|
StubService(tracks=[track]),
|
||||||
|
title_map={"t1": "Example Title"},
|
||||||
|
client_auth=False,
|
||||||
|
)
|
||||||
|
assert body["video"][0]["data"] == {"keep": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_segments_data_drops_the_parser_keys():
|
||||||
|
from unshackle.core.api.handlers import session_segments_handler
|
||||||
|
|
||||||
|
track = stub_video()
|
||||||
|
track.data.update(dash={"representation": object()}, hls={"playlist": object()}, service_value={"a": 1})
|
||||||
|
body = call_session_handler(
|
||||||
|
session_segments_handler, {"track_ids": ["v1"]}, StubService(), tracks={"v1": track}, client_auth=True
|
||||||
|
)
|
||||||
|
assert body["tracks"]["v1"]["data"] == {"service_value": {"a": 1}}
|
||||||
|
|
||||||
|
|
||||||
def test_remote_get_tracks_scopes_server_cookies():
|
def test_remote_get_tracks_scopes_server_cookies():
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
|||||||
@@ -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.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.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
||||||
from unshackle.core.wire import (
|
from unshackle.core.wire import (
|
||||||
serialize_attachment,
|
cookie_values,
|
||||||
serialize_drm,
|
serialize_drm,
|
||||||
serialize_title,
|
serialize_title,
|
||||||
|
serialize_track_data,
|
||||||
serialize_tracks,
|
serialize_tracks,
|
||||||
|
serialize_tracks_reply,
|
||||||
served_url,
|
served_url,
|
||||||
stamp_service_flags,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
log = logging.getLogger("api")
|
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)
|
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})
|
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:
|
for title in sorted_titles:
|
||||||
try:
|
try:
|
||||||
tracks = await call(probed_tracks, service_instance, title)
|
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}")
|
log.debug(f"Successfully got tracks for {title.season}x{title.number}")
|
||||||
except SystemExit:
|
except SystemExit:
|
||||||
# Service calls sys.exit() for unavailable episodes - catch and skip
|
# 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
|
first_title = titles
|
||||||
|
|
||||||
tracks = await call(probed_tracks, service_instance, first_title)
|
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)
|
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:
|
for t in titles_list:
|
||||||
tid = str(t.id) if hasattr(t, "id") else str(id(t))
|
tid = str(t.id) if hasattr(t, "id") else str(id(t))
|
||||||
session.title_map[tid] = 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)
|
SessionStore.publish_update(session)
|
||||||
|
|
||||||
return web.json_response(TitlesReply(session_id=session_id, titles=serialized_titles))
|
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
|
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:
|
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.
|
"""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"
|
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_fields = TracksReply(
|
||||||
session_headers=session_headers,
|
session_headers=session_headers,
|
||||||
session_cookies=cookie_values(session_cookies),
|
session_cookies=cookie_values(session_cookies),
|
||||||
@@ -3149,18 +3140,15 @@ async def session_tracks_handler(
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
return web.json_response(
|
reply = await asyncio.to_thread(
|
||||||
{
|
serialize_tracks_reply,
|
||||||
"title": stamp_service_flags(serialize_title(title), service_instance),
|
title,
|
||||||
**await asyncio.to_thread(serialize),
|
tracks,
|
||||||
"chapters": [
|
session.chapters_by_title.get(str(title_id), []),
|
||||||
{"timestamp": ch.timestamp, "name": ch.name}
|
service_instance,
|
||||||
for ch in session.chapters_by_title.get(str(title_id), [])
|
lambda data: scrub_track_data(data, session),
|
||||||
],
|
|
||||||
**snapshot,
|
|
||||||
**session_fields,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
return web.json_response({**reply, **snapshot, **session_fields})
|
||||||
|
|
||||||
except (Exception, SystemExit) as e:
|
except (Exception, SystemExit) as e:
|
||||||
log.exception(f"Error getting tracks for title {sanitize_log(title_id)}")
|
log.exception(f"Error getting tracks for title {sanitize_log(title_id)}")
|
||||||
@@ -3219,14 +3207,7 @@ async def session_segments_handler(
|
|||||||
"cookie_jar": cookies,
|
"cookie_jar": cookies,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Include manifest-specific data for segment resolution. Round-trip through
|
track_info["data"] = scrub_track_data(serialize_track_data(track), session) or {}
|
||||||
# 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"] = {}
|
|
||||||
|
|
||||||
result[track_id] = track_info
|
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.cenc import drm_stub
|
||||||
from unshackle.core.drm.discovery import track_pssh
|
from unshackle.core.drm.discovery import track_pssh
|
||||||
from unshackle.core.launch import launch_keys
|
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.proxies.resolve import is_loopback
|
||||||
from unshackle.core.remote_protocol import (
|
from unshackle.core.remote_protocol import (
|
||||||
BAD_KEY_ROUTE,
|
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.episode import Episode, Series
|
||||||
from unshackle.core.titles.movie import Movies
|
from unshackle.core.titles.movie import Movies
|
||||||
from unshackle.core.titles.music import Album, Song
|
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.tracks.track import Track
|
||||||
from unshackle.core.tunnel import PROXY_PORTS, TunnelClient, parse_retry_after
|
from unshackle.core.tunnel import PROXY_PORTS, TunnelClient, parse_retry_after
|
||||||
from unshackle.core.utils import run_proxy
|
from unshackle.core.utils import run_proxy
|
||||||
from unshackle.core.utils.collections import ci_get
|
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.redact import redact_path, redact_text, safe_display_url
|
||||||
from unshackle.core.utils.service_params import service_options
|
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:
|
if TYPE_CHECKING:
|
||||||
from unshackle.core.remote_channel import Channel
|
from unshackle.core.remote_channel import Channel
|
||||||
@@ -429,42 +429,6 @@ def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]:
|
|||||||
yield batch
|
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]:
|
def segment_uri_filter(uris: Iterable[Any]) -> Callable[[Any], bool]:
|
||||||
"""Return an HLS ``OnSegmentFilter`` that drops the segments with these URIs.
|
"""Return an HLS ``OnSegmentFilter`` that drops the segments with these URIs.
|
||||||
|
|
||||||
@@ -1428,21 +1392,8 @@ class RemoteService(TitleSource):
|
|||||||
finally:
|
finally:
|
||||||
self.drain_server_logs()
|
self.drain_server_logs()
|
||||||
with malformed_answer("tracks"):
|
with malformed_answer("tracks"):
|
||||||
tracks = build_tracks(result)
|
tracks = apply_tracks_reply(result, title, self.session)
|
||||||
|
session_fields = cast(TracksReply, 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)
|
|
||||||
|
|
||||||
server_cdm = bool(session_fields.get("server_cdm", False))
|
server_cdm = bool(session_fields.get("server_cdm", False))
|
||||||
if self.licensing is None:
|
if self.licensing is None:
|
||||||
request = self._server_cdm_request
|
request = self._server_cdm_request
|
||||||
@@ -1721,7 +1672,7 @@ class RemoteService(TitleSource):
|
|||||||
self.get_tracks(title)
|
self.get_tracks(title)
|
||||||
raw = self._chapters_by_title.get(title_id, [])
|
raw = self._chapters_by_title.get(title_id, [])
|
||||||
with malformed_answer("chapters"):
|
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:
|
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
|
||||||
return self.proxy_license(challenge, track, "widevine")
|
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
|
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
|
``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 json
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
from collections.abc import Callable, Iterable
|
||||||
from datetime import date as date_
|
from datetime import date as date_
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -22,17 +23,19 @@ from typing import Any
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import click
|
import click
|
||||||
|
import requests
|
||||||
from langcodes import Language
|
from langcodes import Language
|
||||||
from pywidevine.pssh import PSSH as WidevinePSSH
|
from pywidevine.pssh import PSSH as WidevinePSSH
|
||||||
|
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
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.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 import Episode, Movie, Song, Title_T
|
||||||
from unshackle.core.titles.availability import availability_metadata
|
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.music import MUSIC_DATA_KEYS, SONG_FIELDS, song_metadata
|
||||||
from unshackle.core.titles.title import rename
|
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.attachment import Attachment
|
||||||
from unshackle.core.tracks.track import Track
|
from unshackle.core.tracks.track import Track
|
||||||
from unshackle.core.utilities import original_tag
|
from unshackle.core.utilities import original_tag
|
||||||
@@ -79,8 +82,8 @@ def episode_flags(title: Episode) -> dict[str, Any]:
|
|||||||
return flags
|
return flags
|
||||||
|
|
||||||
|
|
||||||
def serialize_title(title: Title_T) -> dict[str, Any]:
|
def serialize_title(title: Title_T, service: Any) -> dict[str, Any]:
|
||||||
"""Convert a title object to JSON-serializable dict."""
|
"""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
|
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
|
# 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
|
# 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:
|
if availability is not None:
|
||||||
result["availability"] = availability
|
result["availability"] = availability
|
||||||
return result
|
return stamp_service_flags(result, service)
|
||||||
|
|
||||||
|
|
||||||
def title_to_meta(title: Title_T) -> dict[str, Any]:
|
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
|
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]:
|
def serialize_track_common(track: Any) -> dict[str, Any]:
|
||||||
"""The Track fields every track type shares, a superset of ``Track.to_dict()``."""
|
"""The Track fields every track type shares, a superset of ``Track.to_dict()``."""
|
||||||
return {
|
return {
|
||||||
|
|||||||
Reference in New Issue
Block a user