fix(music): show a collection's own facts in the listing and over --remote

This commit is contained in:
imSp4rky
2026-11-30 13:33:31 -07:00
parent 70ace41201
commit 3634fc5686
18 changed files with 575 additions and 65 deletions
+2
View File
@@ -1113,6 +1113,8 @@ A slow answer arrives as a [slow response](#slow-responses).
}
```
`collection` is present only when the service returned a music collection. It holds the facts of the collection itself: `kind`, `title`, `artist`, `year`, `total_tracks`, `total_discs`, `artwork_url`, `total_duration`, `owner` and `description`, for example `"collection": { "kind": "playlist", "title": "Example Playlist", "total_tracks": 93 }`. A fact that the collection does not have is absent.
Requires an authenticated remote session. Otherwise it returns `404 SESSION_NOT_FOUND`.
### `POST /api/session/{session_id}/tracks`
+6
View File
@@ -220,6 +220,12 @@ hood the client walks a remote session through its lifecycle.
domain, path and `secure` flag, so it goes only to its own hosts. `session_cookies` carries
the same cookies as names and values only, for older clients.
For a music collection (an album, a playlist, an artist listing), the title list reply also
has `collection`, with the facts of the collection itself, such as its kind, title, artist
and totals. The client builds its collection with them. It ignores the keys of
`collection` that it does not know, and stops with an error on a value of the wrong type.
Without `collection`, for example from an older server, the client has the songs only.
The tracks response repeats the title. A service can rewrite title fields inside
`get_tracks`, so the client takes this copy in place of the one from the title
list. Each track carries the full local field set. After the manifest re-parse the
+8
View File
@@ -210,6 +210,14 @@ Each subclass adds its own required fields on top of `id_` and `service`:
because a remote client does not read it again after the listing. Such a song also needs an `id` that
stays the same in each listing: `position` does not identify it.
`Album` and `Music` take the facts of the collection itself: `kind`, `title`, `artist`, `year`,
`total_tracks`, `total_discs`, `artwork_url`, `total_duration`, `owner` and `description`. A
remote client gets all of them. When every song has the same `album` and `album_artist`, the listing
takes a `title`, `artist` or `year` that you do not give, and the release date, quality, genre and
label, from the first song. The listing of any other collection, such as a playlist of single songs,
has no line for them. `build_music_from_songs` uses the same test before it takes the title, artist, year, artwork or
totals from the songs.
The tagger also falls back to `Song.data` for fields the constructor did not get, such
as the composer or a full release date. It reads the top level of that dict and a
nested `metadata` sub-dict, with the nested keys winning, so either shape works. The keys
+3 -1
View File
@@ -692,7 +692,9 @@ and `-w` takes it. The tags and the file name keep the album track number.
```
!!! tip "Read the track list first"
`--list-titles` prints the release with the numbers that `-w` takes.
`--list-titles` prints the release with the numbers that `-w` takes. The lines above the track
list describe the release. For songs of different releases, such as a playlist or an artist
listing, they show only what the service gives for the collection.
### Daily and date-based content
+16
View File
@@ -79,6 +79,7 @@ def test_first_text(values: tuple[Any, ...], default: str, expected: str) -> Non
(("abc", 7), 7.0),
((None, ""), None),
((), None),
((10**400, "Infinity", float("nan"), 7), 7.0),
],
)
def test_first_number(values: tuple[Any, ...], expected: float | None) -> None:
@@ -126,6 +127,7 @@ def test_duration_seconds(value: Any, expected: float | None) -> None:
(-5, "0:00"),
(None, ""),
("bad", ""),
(float("inf"), ""),
],
)
def test_format_duration(value: Any, expected: str) -> None:
@@ -189,6 +191,7 @@ def test_build_music_from_songs() -> None:
year=2019,
album="Greatest",
artist="Band",
album_artist="The Band",
total_tracks=2,
total_discs=1,
data={"duration": 100},
@@ -224,6 +227,19 @@ def test_build_music_from_songs_overrides() -> None:
assert music.description == "best of"
def test_build_music_from_songs_of_different_releases_takes_no_fact_from_a_song() -> None:
songs = [
make_song(album="A", album_artist="Band A", total_tracks=30, artwork_url="http://art/a.jpg"),
make_song(track=12, disc=4, album="B", album_artist="Band B", total_discs=4, data={"duration": 60}),
]
music = build_music_from_songs(songs, kind="playlist")
assert (music.title, music.artist, music.year, music.artwork_url) == (None, None, None, None)
assert (music.total_tracks, music.total_discs, music.total_duration) == (2, None, 60)
named = build_music_from_songs(songs, kind="playlist", title="My Mix", artist="Various")
assert str(named) == "Various - My Mix"
def test_build_music_from_songs_empty_raises() -> None:
with pytest.raises(ValueError, match="nothing here"):
build_music_from_songs([], kind="album", empty_error="nothing here")
+205
View File
@@ -1,6 +1,211 @@
from typing import Any
import jsonpickle
import pytest
from tests.lang_selection.test_kind_only_selection import FakeService, run
from unshackle.core.console import console
from unshackle.core.music.renderer import MusicRenderer
from unshackle.core.titles.music import Album, Music, Song
class DummyService:
pass
def song(number: int, album: str, album_artist: str | None, **fields: Any) -> Song:
values: dict[str, Any] = {
"artist": f"Song Artist {number}",
"year": 2000 + number,
"genre": f"Genre {number}",
"label": f"Label {number}",
"data": {"release_date": f"200{number}-10-14", "quality": "FLAC 24-bit/96kHz", "duration": 60},
**fields,
}
return Song(
f"song-{number}", DummyService, f"Name {number}", album=album, album_artist=album_artist, track=number, **values
)
def mixed(**facts: Any) -> Album:
"""Songs of two releases that share no fact with each other."""
return Album([song(1, "Album 1", "Album Artist 1", explicit=True), song(2, "Album 2", "Album Artist 2")], **facts)
def header(music: Music) -> list[tuple[str, str]]:
grid = MusicRenderer().render_header(music)
assert grid is not None
labels, values = (list(column.cells) for column in grid.columns)
return [(str(label), str(value)) for label, value in zip(labels, values, strict=True)]
OWN_FACTS = {"kind": "playlist", "title": "Own Title", "artist": "Own Artist", "year": 1990, "total_tracks": 9}
OWN_ROWS = [
("Title", "Own Title"),
("Artist", "Own Artist"),
("Type", "Playlist Explicit"),
("Year", "1990"),
("Tracks", "9"),
("Length", "2m 00s"),
]
def test_a_collection_of_different_releases_shows_only_its_own_facts() -> None:
assert header(mixed(**OWN_FACTS)) == OWN_ROWS
assert str(mixed(**OWN_FACTS)) == "Own Artist - Own Title (1990)"
def test_a_collection_of_different_releases_shows_the_date_and_quality_set_on_it() -> None:
music = mixed(**OWN_FACTS)
vars(music).update(release_date="1990-02-03", quality="MP3")
rows = dict(header(music))
assert (rows["Released"], rows["Quality"]) == ("February 3, 1990", "MP3")
@pytest.mark.parametrize(
("facts", "line"),
[
({}, "2 songs"),
({"total_tracks": 9}, "2 songs"),
({"title": "Own Title"}, "Own Title"),
({"artist": "Own Artist"}, "Own Artist"),
({"year": 1990}, "(1990)"),
({"title": "Own Title", "year": 1990}, "Own Title (1990)"),
({"title": "Own Title", "artist": "Own Artist"}, "Own Artist - Own Title"),
],
)
def test_a_fact_that_a_collection_of_different_releases_lacks_has_no_row_and_no_placeholder(
facts: dict[str, Any], line: str
) -> None:
assert str(mixed(**facts)) == line
shown = [label for label, _ in header(mixed(**facts)) if label not in ("Type", "Tracks", "Length")]
assert shown == [label for label in ("Title", "Artist", "Year") if label.lower() in facts]
@pytest.mark.parametrize(
"other", [("Album 1", "Album Artist 2"), ("Album 2", "Album Artist 1"), ("Album 1", None)], ids=str
)
def test_the_album_and_its_artist_together_make_one_release(other: tuple[str, str | None]) -> None:
music = Album([song(1, "Album 1", "Album Artist 1"), song(2, *other)], title="Own Title")
assert [label for label, _ in header(music)] == ["Title", "Type", "Tracks", "Length"]
assert str(music) == "Own Title"
@pytest.mark.parametrize(("album_artist", "artist"), [("Album Artist", "Album Artist"), (None, "Song Artist 1")])
def test_a_collection_of_one_release_shows_the_facts_of_its_first_song(album_artist: str | None, artist: str) -> None:
music = Album([song(n, "Album 1", album_artist) for n in (1, 2)], kind="playlist")
assert header(music) == [
("Title", "Album 1"),
("Artist", artist),
("Type", "Playlist"),
("Released", "October 14, 2001"),
("Year", "2001"),
("Tracks", "2"),
("Length", "2m 00s"),
("Quality", "Hi-Res Lossless"),
("Genre", "Genre 1"),
("Label", "Label 1"),
]
assert str(music) == f"{artist} - Album 1 (2001)"
assert str(Album([song(1, "Album 1", album_artist, year=None)])) == f"{artist} - Album 1 (?)"
def test_a_collection_of_one_release_shows_its_own_facts_before_those_of_a_song() -> None:
facts = {**OWN_FACTS, "total_discs": 3, "total_duration": 4000}
music = Album([song(n, "Album 1", "Album Artist", explicit=True) for n in (1, 2)], **facts)
vars(music).update(released="1990-02-03", quality="MP3")
assert dict(header(music)) == {
"Title": "Own Title",
"Artist": "Own Artist",
"Type": "Playlist Explicit",
"Released": "February 3, 1990",
"Year": "1990",
"Tracks": "9",
"Discs": "3",
"Length": "1h 06m 40s",
"Quality": "MP3",
"Genre": "Genre 1",
"Label": "Label 1",
}
assert str(music) == "Own Artist - Own Title (1990)"
@pytest.mark.parametrize("nested", [False, True])
def test_the_first_song_of_one_release_gives_the_quality_flags(nested: bool) -> None:
data = {"lossless": True, "hires": True, "release_date": "2001-10-14"}
music = Album([song(1, "Album 1", None, data={"metadata": data} if nested else data)])
assert (dict(header(music))["Quality"], dict(header(music))["Released"]) == ("Hi-Res Lossless", "October 14, 2001")
def test_a_blank_album_of_one_release_keeps_its_row() -> None:
music = Album([song(1, " ", "Album Artist")])
assert str(music) == "Album Artist - (2001)"
assert header(music)[0] == ("Title", "")
@pytest.mark.parametrize("duration", [10**400, float("inf"), "Infinity"], ids=["huge", "infinite", "text"])
def test_a_song_duration_too_large_to_convert_does_not_count(duration: Any) -> None:
music = Album([song(1, "Album 1", None), song(2, "Album 1", None, data={"duration": duration})])
assert dict(header(music))["Length"] == "1m 00s"
with console.capture() as out:
console.print(music.tree())
assert "Name 2" in out.get()
@pytest.mark.parametrize("field", ["title", "artist", "kind"])
def test_a_fact_is_text_and_not_markup(field: str) -> None:
with console.capture() as out:
console.print(MusicRenderer().render_header(mixed(**{field: "[red]x[/y] :cd:"})))
assert "[red]x[/y] :cd:" in out.get().lower()
def test_a_collection_from_the_title_cache_shows_only_its_own_facts() -> None:
restored = jsonpickle.loads(jsonpickle.dumps(mixed(**OWN_FACTS)))
assert header(restored) == OWN_ROWS
assert str(restored) == "Own Artist - Own Title (1990)"
@pytest.mark.parametrize("field", ["year", "total_tracks", "total_discs", "total_duration"])
def test_a_collection_number_is_never_a_bool(field: str) -> None:
with pytest.raises(TypeError, match=f"Expected {field} to be an int, not True"):
Album([], **{field: True})
def test_a_total_duration_too_large_to_convert_is_shown_as_given() -> None:
assert MusicRenderer.format_total_duration(10**400) == str(10**400)
NOT_MARKUP = pytest.mark.parametrize("name", ["Live [red]set[/red]", "Live [/x]", "Live :cd:", "Live \\"])
@NOT_MARKUP
def test_the_title_line_shows_the_collection_as_given(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
) -> None:
service = FakeService({})
service.get_titles = lambda: mixed(artist="Own Artist", title=name) # type: ignore[assignment]
with console.capture() as out:
run(monkeypatch, caplog, {}, service=service, list_titles=True)
assert f" Album: Own Artist - {name} " in out.get()
@NOT_MARKUP
def test_the_track_line_shows_the_song_as_given(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
) -> None:
music = mixed()
music[0].name = name
service = FakeService({1: {}})
tracks = service.get_tracks(service.get_titles()[0])
service.get_titles = lambda: music # type: ignore[assignment]
service.get_tracks = lambda title: tracks # type: ignore[method-assign]
with console.capture() as out:
run(monkeypatch, caplog, {}, service=service)
assert f" Track 01: {name} " in out.get()
@pytest.mark.parametrize(
@@ -0,0 +1,194 @@
"""The facts of a music collection reach a --remote client through the titles route, with its songs."""
from __future__ import annotations
import asyncio
import json
from datetime import date
from types import SimpleNamespace
from typing import Any
import pytest
import responses
from tests.core.test_music_renderer import OWN_FACTS, OWN_ROWS, header, mixed
from tests.remote.sessions import session_entry
from tests.remote.unit.test_session_reopen import SERVER, make_service
from unshackle.core.api import handlers
from unshackle.core.remote_service import RemoteError, RemoteService
from unshackle.core.titles import Movie, Movies
from unshackle.core.titles.music import MUSIC_FIELDS, Album, Music, Song
pytestmark = pytest.mark.unit
FACTS: dict[str, Any] = {
**OWN_FACTS,
"total_discs": 7,
"artwork_url": "https://img.example/own.jpg",
"total_duration": 120,
"owner": "Own Owner",
"description": "Own Description",
}
def facts_of(music: Any) -> dict[str, Any]:
return {field: getattr(music, field) for field in FACTS}
def titles_reply(monkeypatch: pytest.MonkeyPatch, service: Any) -> dict[str, Any]:
"""The answer of the titles route of a server whose remote session runs ``service``."""
session = session_entry(service_instance=service)
async def validated(*_: Any) -> Any:
return session
monkeypatch.setattr(handlers, "get_validated_session", validated)
response = asyncio.run(handlers.session_titles_handler("sid"))
assert response.status == 200
return json.loads(response.body)
def client_of(answer: dict[str, Any]) -> RemoteService:
"""A client that gets ``answer`` from the titles route."""
service = make_service()
service.session_call = lambda call: answer # type: ignore[method-assign]
service.drain_server_logs = lambda: None # type: ignore[method-assign]
return service
def served(titles: Any) -> Any:
return SimpleNamespace(get_titles=lambda: titles)
def over_remote(monkeypatch: pytest.MonkeyPatch, titles: Any) -> Any:
return client_of(titles_reply(monkeypatch, served(titles))).get_titles()
@pytest.mark.parametrize("collection", [Album, Music])
def test_a_client_gets_the_facts_of_the_collection(monkeypatch: pytest.MonkeyPatch, collection: type[Music]) -> None:
titles = over_remote(monkeypatch, collection(mixed(), **FACTS))
assert type(titles) is Album
assert facts_of(titles) == FACTS
assert [song.name for song in titles] == ["Name 1", "Name 2"]
def test_the_remote_listing_is_the_local_one(monkeypatch: pytest.MonkeyPatch) -> None:
local = mixed(**{**FACTS, "total_discs": None})
titles = over_remote(monkeypatch, local)
assert header(titles) == header(local) == OWN_ROWS
assert str(titles) == str(local) == "Own Artist - Own Title (1990)"
def test_each_fact_the_constructor_takes_crosses_the_wire() -> None:
assert set(MUSIC_FIELDS) == set(FACTS) == set(vars(Album([]))) & set(Music.__init__.__annotations__)
def test_the_reply_names_only_the_facts_the_collection_has(monkeypatch: pytest.MonkeyPatch) -> None:
reply = titles_reply(monkeypatch, served(mixed(kind="artist", title="Own Title")))
assert reply["collection"] == {"kind": "artist", "title": "Own Title"}
@pytest.mark.parametrize(
"value", ["1990", 0, True, 12.5, float("nan"), b"1990", date(1990, 1, 2), " ", {1}, ""], ids=repr
)
@pytest.mark.parametrize("field", ["year", "total_tracks", "total_discs", "kind", "artwork_url"])
def test_a_fact_the_client_would_refuse_never_stops_the_listing(
monkeypatch: pytest.MonkeyPatch, field: str, value: Any
) -> None:
music = mixed(**FACTS)
setattr(music, field, value)
titles = over_remote(monkeypatch, music)
assert len(titles) == 2
assert {**facts_of(titles), field: None} == {**FACTS, field: None}
def test_a_listing_that_is_not_a_collection_sends_no_facts(monkeypatch: pytest.MonkeyPatch) -> None:
movies = Movies([Movie("movie-1", Song, "Name", 2024)])
for titles in (movies, list(mixed(**FACTS))):
assert list(titles_reply(monkeypatch, served(titles))) == ["session_id", "titles"]
@pytest.mark.parametrize("kept", [{}, {"collection": None}], ids=["missing", "null"])
def test_a_reply_with_no_facts_gives_a_plain_album(monkeypatch: pytest.MonkeyPatch, kept: dict[str, Any]) -> None:
reply = titles_reply(monkeypatch, served(mixed(**FACTS)))
del reply["collection"]
titles = client_of({**reply, **kept}).get_titles()
assert type(titles) is Album
assert facts_of(titles) == facts_of(Album([]))
assert len(titles) == 2
def test_a_relaying_server_forwards_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
upstream = titles_reply(monkeypatch, served(mixed(**FACTS)))
relayed = titles_reply(monkeypatch, client_of(upstream))
assert facts_of(client_of(relayed).get_titles()) == FACTS
def test_the_title_map_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS))))
monkeypatch.setattr("unshackle.core.remote_service.config.services", {"TEST": {"title_map": {"Name 1": "New"}}})
titles = client.get_titles_cached()
assert facts_of(titles) == FACTS
assert [song.name for song in titles] == ["New", "Name 2"]
@responses.activate
def test_a_reopened_session_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS))))
client.get_titles()
monkeypatch.setattr(client, "authenticate", lambda credential=None: setattr(client, "_session_id", "s2"))
responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False})
responses.add(
responses.GET,
f"{SERVER}/api/session/s2/titles",
json=titles_reply(monkeypatch, served(mixed(title="Replaced"))),
)
assert client.reopen()
assert facts_of(client.get_titles()) == FACTS
def test_an_unknown_key_of_the_facts_is_dropped(monkeypatch: pytest.MonkeyPatch) -> None:
reply = titles_reply(monkeypatch, served(mixed(**FACTS)))
reply["collection"] |= {"iterable": [], "quality": "MP3", "x": [1]}
titles = client_of(reply).get_titles()
assert facts_of(titles) == FACTS
assert len(titles) == 2
assert not {"iterable", "quality", "x"} & set(vars(titles))
@pytest.mark.parametrize(
"collection",
[
pytest.param([], id="list"),
pytest.param("kind", id="text"),
pytest.param(5, id="number"),
pytest.param(False, id="bool"),
pytest.param({"kind": None}, id="no-kind"),
pytest.param({"kind": " "}, id="blank-kind"),
pytest.param({"title": ["x"]}, id="title-list"),
pytest.param({"artist": 5}, id="artist-number"),
pytest.param({"year": "1990"}, id="year-text"),
pytest.param({"year": True}, id="year-bool"),
pytest.param({"year": 0}, id="year-zero"),
pytest.param({"total_tracks": -1}, id="negative-tracks"),
pytest.param({"total_discs": True}, id="discs-bool"),
pytest.param({"total_duration": 1.5}, id="duration-float"),
pytest.param({"artwork_url": {}}, id="artwork-object"),
pytest.param({"description": 1}, id="description-number"),
],
)
def test_malformed_facts_are_one_remote_error(monkeypatch: pytest.MonkeyPatch, collection: Any) -> None:
reply = titles_reply(monkeypatch, served(mixed()))
with pytest.raises(RemoteError, match="^The remote server sent malformed titles: [^\n]+$"):
client_of({**reply, "collection": collection}).get_titles()
+4 -4
View File
@@ -37,7 +37,7 @@ from unshackle.core.config import (
resolve_cdm_name,
resolve_decryption,
)
from unshackle.core.console import SyncLive, console, listing_panel, print_listing
from unshackle.core.console import SyncLive, console, listing_panel, print_listing, title_rule
from unshackle.core.constants import (
DEFAULT_SAMPLE,
DOWNLOAD_ALL_DRM,
@@ -1745,7 +1745,7 @@ class dl:
titles, enrich=self.enrich, tvdb_order=self.tvdb_order, continuous=self.continuous_episodes
)
console.print(Padding(Rule(f"[rule.text]{titles.__class__.__name__}: {titles}"), (1, 2)))
console.print(Padding(title_rule(f"{titles.__class__.__name__}: {titles}"), (1, 2)))
print_listing(titles.tree(verbose=list_titles))
if list_titles:
@@ -1953,8 +1953,8 @@ class dl:
else:
progress_sink({"title": getattr(title, "name", None) or str(title)})
title_rule = f"Track {title.listing_number[1]:02}: {title.name}" if isinstance(title, Song) else str(title)
console.print(Padding(Rule(f"[rule.text]{title_rule}"), (1, 2)))
heading = f"Track {title.listing_number[1]:02}: {title.name}" if isinstance(title, Song) else str(title)
console.print(Padding(title_rule(heading), (1, 2)))
metadata.search(title, listing=list_ or list_titles)
+5 -1
View File
@@ -98,6 +98,7 @@ from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_optio
from unshackle.core.wire import (
cookie_values,
serialize_drm,
serialize_music,
serialize_title,
serialize_track_data,
serialize_tracks,
@@ -2926,7 +2927,10 @@ async def session_titles_handler(session_id: str, request: web.Request | None =
serialized_titles.append(serialize_title(t, service_instance))
SessionStore.publish_update(session)
return web.json_response(TitlesReply(session_id=session_id, titles=serialized_titles))
reply = TitlesReply(session_id=session_id, titles=serialized_titles)
if collection := serialize_music(titles):
reply["collection"] = collection
return web.json_response(reply)
except (Exception, SystemExit) as e:
log.exception("Error getting titles")
+2 -1
View File
@@ -2208,7 +2208,8 @@ async def session_titles(request: web.Request) -> web.Response:
responses:
'200':
description: >-
List of titles.
List of titles. For a music collection, `collection` holds the facts of the collection itself (kind,
title, artist, year, totals, artwork, owner and description), without those it does not have.
After 30 s the route sends 200 and a newline every 30 s. A failure after that time
arrives as the error body with status 200.
'404':
+9
View File
@@ -25,6 +25,7 @@ from rich.measure import Measurement
from rich.padding import Padding, PaddingDimensions
from rich.panel import Panel
from rich.progress import BarColumn, Task
from rich.rule import Rule
from rich.status import Status
from rich.style import Style, StyleType
from rich.table import Table
@@ -481,6 +482,13 @@ def listing_panel(renderable: RenderableType, title: str) -> Panel:
return Panel(renderable, title=title, box=box.SQUARE, border_style="bright_black")
def title_rule(title: str) -> Rule:
"""A rule whose title is shown as given: brackets and emoji codes in it are text, not markup."""
text = console.render_str(title, markup=False, emoji=False)
text.stylize("rule.text")
return Rule(text)
def listing_table(title: str | None = None, **kwargs: Any) -> Table:
"""Assemble a table in the style of the rich-click help tables, so listings and help screens match."""
kwargs.setdefault("box", box.HORIZONTALS)
@@ -608,4 +616,5 @@ __all__ = (
"set_notice_handler",
"set_prompt_handler",
"show_notice",
"title_rule",
)
+25 -12
View File
@@ -9,10 +9,11 @@ reuse them.
from __future__ import annotations
import math
import re
from typing import Any
from unshackle.core.titles.music import Music, Song
from unshackle.core.titles.music import Music, Song, release_song
def first_text(*values: Any, default: str = "") -> str:
@@ -43,14 +44,16 @@ def first_text(*values: Any, default: str = "") -> str:
def first_number(*values: Any) -> float | None:
"""Return the first value parseable as a float, else ``None``."""
"""Return the first value parseable as a finite float, else ``None``."""
for value in values:
if value in (None, ""):
continue
try:
return float(value)
except (TypeError, ValueError):
number = float(value)
except (TypeError, ValueError, OverflowError):
continue
if math.isfinite(number):
return number
return None
@@ -147,12 +150,22 @@ def build_music_from_songs(
"""Assemble a :class:`Music` release from a list of :class:`Song` objects.
Aggregates artwork and total duration from each song's ``data`` payload and
derives track/disc totals. Raises ``ValueError(empty_error)`` on an empty list.
derives track/disc totals. The title, artist, year, artwork and totals come from the
songs only when all are of one release; a mixed list counts its songs. Raises
``ValueError(empty_error)`` on an empty list.
"""
if not songs:
raise ValueError(empty_error)
first_song = songs[0]
release = release_song(songs)
year = None
total_tracks, total_discs = len(songs), None
if release:
title = title or release.album
artist = artist or release.album_artist or release.artist
year = release.year
total_tracks = max(song.total_tracks or song.track for song in songs)
total_discs = max(song.total_discs or song.disc for song in songs)
artwork_url = ""
total_duration = 0
for song in songs:
@@ -163,12 +176,12 @@ def build_music_from_songs(
return Music(
songs,
kind=kind,
title=title or first_song.album,
artist=artist or first_song.album_artist or first_song.artist,
year=first_song.year,
total_tracks=max((song.total_tracks or song.track for song in songs), default=len(songs)),
total_discs=max((song.total_discs or song.disc for song in songs), default=1),
artwork_url=artwork_url or None,
title=title,
artist=artist,
year=year,
total_tracks=total_tracks,
total_discs=total_discs,
artwork_url=artwork_url or None if release else None,
total_duration=total_duration or None,
owner=owner,
description=description,
+19 -20
View File
@@ -10,8 +10,8 @@ from rich.text import Text
from rich.tree import Tree
from unshackle.core.console import listing_panel
from unshackle.core.music.extract import first_text, format_duration
from unshackle.core.titles.music import Music, Song
from unshackle.core.music.extract import first_number, first_text, format_duration
from unshackle.core.titles.music import Music, Song, release_song
class MusicRenderer:
@@ -33,12 +33,12 @@ class MusicRenderer:
if not music:
return None
first_song = music[0]
data = first_song.data if isinstance(first_song.data, dict) else {}
release = release_song(music)
data = release.data if release and isinstance(release.data, dict) else {}
metadata = m if isinstance(m := data.get("metadata"), dict) else {}
title = music.title or first_song.album
artist = music.artist or first_song.album_artist or first_song.artist
year = getattr(music, "year", None) or first_song.year
title = music.title or (release.album if release else None)
artist = music.artist or (release.album_artist or release.artist if release else None)
year = getattr(music, "year", None) or (release.year if release else None)
kind = self.display_kind(music.kind)
explicit = any(bool(getattr(song, "explicit", None)) for song in music)
total_tracks = getattr(music, "total_tracks", None) or len(music)
@@ -70,8 +70,10 @@ class MusicRenderer:
grid.add_column()
# values are service data, so they stay Text and never get parsed as markup
grid.add_row("Title", Text(str(title)))
grid.add_row("Artist", Text(str(artist)))
if release or title:
grid.add_row("Title", Text(str(title)))
if release or artist:
grid.add_row("Artist", Text(str(artist)))
grid.add_row("Type", self.kind_text(kind, explicit=explicit))
if released:
grid.add_row("Released", Text(released))
@@ -84,10 +86,10 @@ class MusicRenderer:
grid.add_row("Length", Text(length))
if quality:
grid.add_row("Quality", Text(quality))
if first_song.genre:
grid.add_row("Genre", Text(first_song.genre))
if first_song.label:
grid.add_row("Label", Text(first_song.label))
if release and release.genre:
grid.add_row("Genre", Text(release.genre))
if release and release.label:
grid.add_row("Label", Text(release.label))
return grid
@@ -216,10 +218,10 @@ class MusicRenderer:
def format_total_duration(value: Any) -> str:
if value in (None, ""):
return ""
try:
total_seconds = int(float(value))
except (TypeError, ValueError):
number = first_number(value)
if number is None:
return str(value).strip()
total_seconds = int(number)
if total_seconds <= 0:
return ""
minutes, seconds = divmod(total_seconds, 60)
@@ -308,10 +310,7 @@ class MusicRenderer:
data = song.data if isinstance(song.data, dict) else {}
metadata = m if isinstance(m := data.get("metadata"), dict) else {}
value = MusicRenderer.first_value(data.get("duration"), metadata.get("duration"))
try:
total += int(float(value or 0))
except (TypeError, ValueError):
continue
total += int(first_number(value) or 0)
return total
+2 -1
View File
@@ -365,10 +365,11 @@ class LogsReply(TypedDict):
class TitlesReply(TypedDict):
"""The titles of a remote session, each in the form of ``core.wire``."""
"""The titles of a remote session, each in the form of ``core.wire``; ``collection`` only for a music collection."""
session_id: str
titles: list[dict[str, Any]]
collection: NotRequired[dict[str, Any]]
class SessionClosed(TypedDict, total=False):
+4 -3
View File
@@ -94,7 +94,7 @@ from unshackle.core.title_source import KeyArrival, TitleSource
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.titles.music import Song
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
@@ -102,7 +102,7 @@ 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_tracks_reply, build_chapters, build_title
from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music, build_title
if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel
@@ -1365,7 +1365,8 @@ class RemoteService(TitleSource):
if isinstance(first, Episode):
self._titles = Series(titles_list)
elif isinstance(first, Song):
self._titles = Album(titles_list)
with malformed_answer("titles"):
self._titles = build_music(titles_list, result.get("collection"))
else:
self._titles = Movies(titles_list)
return self._titles
+38 -15
View File
@@ -1,6 +1,6 @@
import re
from abc import ABC
from collections.abc import Collection, Iterable
from collections.abc import Collection, Iterable, Sequence
from typing import Any
from langcodes import Language
@@ -67,6 +67,20 @@ MUSIC_DATA_KEYS = (
)
"""The `Song.data` keys the music tagger and renderer read, which a remote session sends as `music_data`."""
MUSIC_FIELDS = (
"kind",
"title",
"artist",
"year",
"total_tracks",
"total_discs",
"artwork_url",
"total_duration",
"owner",
"description",
)
"""The `Music` attributes a remote session sends as `collection`; each is also a constructor argument."""
def song_metadata(song: Any) -> dict[str, Any]:
"""``Song.data`` with its nested ``metadata`` dict merged over it, as the renderer also reads both."""
@@ -285,6 +299,12 @@ class Song(Title):
return formatter.format(context)
def release_song(songs: Sequence[Song]) -> Song | None:
"""The first song when all have the same album and album artist, so its release facts are those of all songs."""
releases = {(song.album, getattr(song, "album_artist", None)) for song in songs}
return songs[0] if len(releases) == 1 else None
class Music(SortedKeyList, ABC):
"""A grouped music release, such as an album, EP, single, compilation, or playlist."""
@@ -311,16 +331,16 @@ class Music(SortedKeyList, ABC):
raise TypeError(f"Expected title to be a str, not {title!r}")
if artist is not None and not isinstance(artist, str):
raise TypeError(f"Expected artist to be a str, not {artist!r}")
if year is not None and not isinstance(year, int):
raise TypeError(f"Expected year to be an int, not {year!r}")
if total_tracks is not None and not isinstance(total_tracks, int):
raise TypeError(f"Expected total_tracks to be an int, not {total_tracks!r}")
if total_discs is not None and not isinstance(total_discs, int):
raise TypeError(f"Expected total_discs to be an int, not {total_discs!r}")
for name, number in (
("year", year),
("total_tracks", total_tracks),
("total_discs", total_discs),
("total_duration", total_duration),
):
if number is not None and (isinstance(number, bool) or not isinstance(number, int)):
raise TypeError(f"Expected {name} to be an int, not {number!r}")
if artwork_url is not None and not isinstance(artwork_url, str):
raise TypeError(f"Expected artwork_url to be a str, not {artwork_url!r}")
if total_duration is not None and not isinstance(total_duration, int):
raise TypeError(f"Expected total_duration to be an int, not {total_duration!r}")
if owner is not None and not isinstance(owner, str):
raise TypeError(f"Expected owner to be a str, not {owner!r}")
if description is not None and not isinstance(description, str):
@@ -354,11 +374,14 @@ class Music(SortedKeyList, ABC):
def __str__(self) -> str:
if not self:
return super().__str__()
first_song = self[0]
artist = self.artist or getattr(first_song, "album_artist", None) or first_song.artist
title = self.title or first_song.album
year = self.year or first_song.year or "?"
return f"{artist} - {title} ({year})"
if song := release_song(self):
artist = self.artist or getattr(song, "album_artist", None) or song.artist
title = self.title or song.album
year = self.year or song.year or "?"
return f"{artist} - {title} ({year})"
name = " - ".join(str(fact) for fact in (self.artist, self.title) if fact)
line = f"{name} ({self.year})".strip() if self.year else name
return line or f"{len(self)} songs"
def tree(self, verbose: bool = False) -> RenderableType:
# verbose is the Titles_T contract; a release always renders its full tracklist
@@ -371,4 +394,4 @@ class Album(Music):
"""Backward-compatible collection name for album-style music releases."""
__all__ = ("Song", "Music", "Album")
__all__ = ("Song", "Music", "Album", "release_song")
+30 -2
View File
@@ -16,6 +16,7 @@ import json
import logging
import re
from collections.abc import Callable, Iterable
from contextlib import suppress
from datetime import date as date_
from enum import Enum
from pathlib import Path
@@ -31,9 +32,9 @@ 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 import Album, Episode, Movie, Music, 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.music import MUSIC_DATA_KEYS, MUSIC_FIELDS, SONG_FIELDS, song_metadata
from unshackle.core.titles.title import rename
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
@@ -142,6 +143,24 @@ def serialize_title(title: Title_T, service: Any) -> dict[str, Any]:
return stamp_service_flags(result, service)
def serialize_music(titles: Any) -> dict[str, Any]:
"""The REST form of the own facts of a music collection, without its songs; empty for any other listing.
A fact that the constructor refuses, set after it ran, stays off the wire: a peer would refuse the whole listing.
"""
facts: dict[str, Any] = {}
if not isinstance(titles, Music):
return facts
for field in MUSIC_FIELDS:
value: Any = getattr(titles, field, None)
if value is None:
continue
with suppress(TypeError, ValueError):
Music(**{field: value})
facts[field] = value
return facts
def title_to_meta(title: Title_T) -> dict[str, Any]:
"""The export form of a title: the fields an import needs to rebuild it for output naming.
@@ -318,6 +337,15 @@ def build_title(info: dict[str, Any], service_tag: str, fallback_id: str) -> Tit
return title
def build_music(songs: list[Title_T], info: Any) -> Album:
"""Rebuild a music collection from its songs and serialize_music; a server without the facts sends none."""
if info is None:
return Album(songs)
if not isinstance(info, dict):
raise TypeError(f"Expected collection to be an object, not {type(info).__name__}")
return Album(songs, **{field: info[field] for field in MUSIC_FIELDS if field in info})
def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
"""Serialise DRM objects to JSON-serializable list."""
if not drm_list:
+3 -5
View File
@@ -242,11 +242,9 @@ class MUSIC_EXAMPLE(Service):
kind="discography",
title=f"{artist['name']} Discography",
artist=artist["name"],
# These are the header rows the helper would fill from the FIRST song,
# which is one album's answer and wrong for a discography. A None does not
# blank a row: the renderer falls back to the first song for the title,
# the artist and the year, so only the counts and the duration below are
# really the collection's to state.
# A discography has no year. The header reads a fact off the first song only
# when all songs share one album and album artist, so the None here means no
# Year row.
year=None,
total_tracks=len(discography),
total_discs=1,