From 70ace4120186e66901e570888c15781f64f4175e Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Mon, 30 Nov 2026 12:39:51 -0700 Subject: [PATCH] feat(music): list and select playlist songs by their position --- docs/dev/rest-api/endpoints.md | 15 ++--- docs/dev/service-architecture.md | 6 ++ docs/guide/cli-reference.md | 2 +- docs/guide/downloading.md | 9 +-- tests/core/test_music_folder_template.py | 11 ++++ tests/core/test_music_wanted.py | 66 +++++++++++++++++++++- tests/core/test_wire.py | 19 +++++++ tests/remote/unit/test_api_title_fields.py | 14 +++++ tests/remote/unit/test_session_reopen.py | 58 +++++++++++++++++++ unshackle/commands/dl.py | 4 +- unshackle/core/api/handlers.py | 2 +- unshackle/core/api/routes.py | 4 +- unshackle/core/music/renderer.py | 10 +--- unshackle/core/remote_service.py | 10 +++- unshackle/core/titles/music.py | 23 +++++++- unshackle/core/wire.py | 7 ++- 16 files changed, 222 insertions(+), 38 deletions(-) diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 8da1424b1..cf4096428 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -271,14 +271,11 @@ server, uses the server's own cache and returns no `cache` field. } ``` -Each serialized title carries `type` (`"episode"`, `"movie"`, or `"other"`), `name`, `id`, `language`, `description`, `date`, and `cover_url`. Episodes and movies add `year`. Episodes also add `series_title`, `season`, and `number`. +Each serialized title carries `type` (`"episode"`, `"movie"`, `"song"`, or `"other"`), `name`, `id`, `language`, `description`, `date`, and `cover_url`. Episodes and movies add `year`. Episodes also add `series_title`, `season`, and `number`. -!!! warning "A song serializes as `"other"`" - A song has no `type` of its own. The server sends it as `"other"`, and the response - carries none of its music fields: no artist, no album, no track or disc number, and no - `year`. `name` holds the song name. To read the disc and track numbers of a release, - operate the CLI with `--list-titles`. You can still select songs over the API, - through the `wanted` parameter. +!!! info "The number that `wanted` takes for a song" + A song adds `year` and its music fields, such as `artist`, `album`, `disc`, `track` and + `position`. `wanted` takes `position` when it is not `null`, else `disc` and `track` as in `"2x3"`. These keys are sent only when the title carries them, so a title without them serializes exactly as before: @@ -322,7 +319,7 @@ Show the video, audio, and subtitle tracks for a title. For series, you can scop | --- | --- | --- | --- | | `service` | string | yes | Service tag. | | `title_id` | string | yes | Title identifier. | -| `wanted` | string / string[] | no | Episode/season range (e.g. `"S01E01-S01E03"`), or a song selector (e.g. `"1-5"`, `"1,3,7"`, or `"2x3"` for disc 2 track 3). A list of selectors is accepted too. | +| `wanted` | string / string[] | no | Episode/season range (e.g. `"S01E01-S01E03"`), or a song by its number in the track list (e.g. `"1-5"`, `"1,3,7"`, or `"2x3"` for disc 2 track 3). A list of selectors is accepted too. | | `season` | int/string | no | Season number (combined with `episode`). | | `episode` | int/string | no | Episode number (combined with `season`). | | `part` | int/string | no | Part index of a split episode (combined with `season` and `episode`). | @@ -451,7 +448,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is | `range` | string[] | `["SDR"]` | Dynamic range(s). | | `channels` | number | `null` | Audio channel layout. | | `no_atmos` | boolean | `false` | Exclude Atmos tracks. | -| `wanted` | string / string[] | `[]` | Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, `"S01E01.2"`, and the air-date form, `"2026-08-11"` or `"2026-08-01:2026-08-31"`. For a music release, a selector is a track number, `"1-5"` or `"1,3,7"`, or `"{disc}x{track}"` such as `"2x3"`. | +| `wanted` | string / string[] | `[]` | Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, `"S01E01.2"`, and the air-date form, `"2026-08-11"` or `"2026-08-01:2026-08-31"`. For a music release, a selector is a number of the track list, `"1-5"` or `"1,3,7"`, or `"{disc}x{track}"` such as `"2x3"`. | | `latest_episode` | boolean | `false` | Only the newest episode. | | `latest_episodes` | integer | `null` | Only the N newest episodes. A positive integer. When set, it overrides `latest_episode`. | | `lang` / `v_lang` / `a_lang` / `s_lang` | string[] | `["orig"]` / `[]` / `[]` / `["all"]` | Language filters. A missing `s_lang` language gives a warning and the job continues. | diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 3d0e662a3..0d2d2eece 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -204,6 +204,12 @@ Each subclass adds its own required fields on top of `id_` and `service`: final audio file under that suffix. You can set these fields in `get_tracks()` too, and a remote client gets them back. + For a playlist whose songs keep the tags of their own album, give `position` (a positive integer, + from 1) to every song. The track list, the download order and `-w` then use that number. The + tags, the file name and the folder keep `track`, `disc` and `album`. Set it in `get_titles()`, + 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. + 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 diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index be3c2cbcf..bbe54a8c5 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -122,7 +122,7 @@ unshackle honours the special language tokens `orig`, `all`, and `best` everywhe | Flag | Description | |---|---| -| `-w`, `--wanted` | Wanted episodes, e.g. `S01-S05,S07`, `S01E01-S02E03`. Supports exclusions with a leading `-` (e.g. `-S03`). For a [split episode](downloading.md#split-episodes), `.N` picks one part (`S01E01.2`), a range must stay inside the episode (`S01E01.1-S01E01.3`), and `S01E01` on its own takes every part. For a [dated episode](downloading.md#daily-and-date-based-content), a token can also be an ISO air date (`2026-08-11`) or a date range with a colon (`2026-08-01:2026-08-31`). For a [music release](downloading.md#music-tracks), a token is a track number (`1-5`, `1,3,7`), or `{disc}x{track}` (`2x3`) when the release has more than one disc. | +| `-w`, `--wanted` | Wanted episodes, e.g. `S01-S05,S07`, `S01E01-S02E03`. Supports exclusions with a leading `-` (e.g. `-S03`). For a [split episode](downloading.md#split-episodes), `.N` picks one part (`S01E01.2`), a range must stay inside the episode (`S01E01.1-S01E01.3`), and `S01E01` on its own takes every part. For a [dated episode](downloading.md#daily-and-date-based-content), a token can also be an ISO air date (`2026-08-11`) or a date range with a colon (`2026-08-01:2026-08-31`). For a [music release](downloading.md#music-tracks), a token is a number of the track list (`1-5`, `1,3,7`), or `{disc}x{track}` (`2x3`) when the release has more than one disc. | | `--select-titles` | Interactively select what to download: episodes of a series, or films when a title has more than one. **Cannot combine with `-w`.** | | `--latest-episode` | Download only the single most recent episode. | | `--latest-episodes N` | Download only the N most recent episodes. | diff --git a/docs/guide/downloading.md b/docs/guide/downloading.md index fe880ca85..d486a87a3 100644 --- a/docs/guide/downloading.md +++ b/docs/guide/downloading.md @@ -654,7 +654,9 @@ with `-` to exclude it. For a music release, the same option takes track numbers `-w` selects the tracks of an album, EP, single, or playlist. Give a track by its number. A release with more than one disc uses the `{disc}x{track}` form. A number on its own is a -track on disc 1, which is the number the track list shows for a single-disc release. +track on disc 1, which is the number the track list shows for a single-disc release. The +songs of a playlist can have a position in the playlist. The track list then shows that position, +and `-w` takes it. The tags and the file name keep the album track number. === "Tracks" @@ -690,8 +692,7 @@ track on disc 1, which is the number the track list shows for a single-disc rele ``` !!! tip "Read the track list first" - `--list-titles` prints the release with its disc and track numbers, so you can see - which numbers to give `-w`. + `--list-titles` prints the release with the numbers that `-w` takes. ### Daily and date-based content @@ -1254,7 +1255,7 @@ authoritative list. | `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. `-` excludes. | | `--sub-format` | | Output subtitle format. | | `--sub-font` | | Font for subtitles converted to ASS; implies `--sub-format ASS`. | -| `--wanted` | `-w` | Episode/season range, an air date, or a track number for a music release (`1-5`, `2x3`). | +| `--wanted` | `-w` | Episode/season range, an air date, or a number of the track list for a music release (`1-5`, `2x3`). | | `--daily` | | Fill missing air dates from TVDB during `--enrich`. | | `--select-titles` | | Interactively pick episodes or films. | | `--latest-episode` | | Only the newest episode. | diff --git a/tests/core/test_music_folder_template.py b/tests/core/test_music_folder_template.py index fb002dee1..52ef84b78 100644 --- a/tests/core/test_music_folder_template.py +++ b/tests/core/test_music_folder_template.py @@ -125,3 +125,14 @@ def test_songs_separator_survives_a_config_without_a_songs_template(reset_folder """A user config with output_template but no `songs` key used to raise a KeyError.""" reset_folder_config.output_template = {"movies": "{title}.{year}"} assert reset_folder_config.get_template_separator("songs") == "." + + +def test_a_playlist_position_changes_no_output_name(reset_folder_config): + """The file name, the folder and the text form of a song come from its own album.""" + reset_folder_config.output_template = {"songs": "{disc?}-{track_number}. {title}"} + reset_folder_config.folder_templates = {"albums": "{album} {disc?} {track_number}"} + song = make_song(track=6, disc=2, position=9) + + assert song.get_filename(StubMediaInfo()) == "02-06.Example.Track" + assert song.get_filename(StubMediaInfo(), folder=True) == "Example Album 02 06" + assert str(song) == "Example Artist - Example Album (2025) / 06. Example Track" diff --git a/tests/core/test_music_wanted.py b/tests/core/test_music_wanted.py index 7eb8b2eaf..9c317a8df 100644 --- a/tests/core/test_music_wanted.py +++ b/tests/core/test_music_wanted.py @@ -7,12 +7,19 @@ click type makes of them, and the titles the download loop keeps. from __future__ import annotations +import re + import click +import jsonpickle import pytest +from tests.lang_selection.test_kind_only_selection import FakeService, run from unshackle.commands.dl import title_wanted +from unshackle.core.console import console +from unshackle.core.music.renderer import MusicRenderer +from unshackle.core.music.tagger import build_tag_values from unshackle.core.titles.movie import Movie -from unshackle.core.titles.music import Song +from unshackle.core.titles.music import Album, Song from unshackle.core.utils.click_types import SeasonRange @@ -20,15 +27,16 @@ class DummyService: pass -def make_song(track: int = 1, disc: int = 1) -> Song: +def make_song(track: int = 1, disc: int = 1, position: int | None = None, album: str = "Example Album") -> Song: return Song( id_=f"track-{disc:02}{track:04}", service=DummyService, name=f"Example Track {track}", artist="Example Artist", - album="Example Album", + album=album, track=track, disc=disc, + position=position, year=2025, album_artist="Example Artist", ) @@ -124,3 +132,55 @@ def test_song_matches_only_its_own_key(): song = make_song(track=3, disc=2) assert song.matches_wanted(["2x3"]) is True assert song.matches_wanted(["1x3", "2x4"]) is False + + +def test_a_playlist_lists_and_selects_by_position_but_tags_by_album_track(): + songs = [make_song(1, position=1, album="Z"), make_song(6, 2, 2, "B"), make_song(1, position=3, album="A")] + playlist = Album(reversed(songs), kind="playlist") + + assert list(playlist) == songs + assert select("2", playlist) == [6] + assert not songs[1].matches_wanted(["2x6"]) + assert [MusicRenderer().song_line(s, playlist).plain[:2] for s in playlist] == ["01", "02", "03"] + tags = build_tag_values(songs[1]) + assert (tags["TRACKNUMBER"], tags["DISCNUMBER"]) == ("6", "2") + + +def test_a_playlist_shows_no_disc_count(): + playlist = Album([make_song(6, 2, position=1), make_song(1, 3, position=2)], kind="playlist") + assert "Discs" not in list(MusicRenderer().render_header(playlist).columns[0].cells) + assert "Discs" in list(MusicRenderer().render_header(Album([make_song(6, 2)])).columns[0].cells) + + +@pytest.mark.parametrize(("position", "key", "rule"), [(9, "1x9", "Track 09"), (None, "2x6", "Track 06")]) +def test_the_download_loop_names_the_number_that_selected_the_song(monkeypatch, caplog, position, key, rule): + service = FakeService({1: {}}) + tracks = service.get_tracks(service.get_titles()[0]) + service.get_titles = lambda: Album([make_song(6, 2, position, "B"), make_song(1)]) + service.get_tracks = lambda title: tracks + + with console.capture() as out: + run(monkeypatch, caplog, {}, service=service, wanted=[key]) + + assert re.findall(r"Track \d+: Example Track \d+", out.get()) == [f"{rule}: Example Track 6"] + + +def test_a_release_without_positions_keeps_its_order_and_numbers(): + songs = [make_song(1, album="A"), make_song(6, 2, album="B"), make_song(1, album="Z")] + release = Album(reversed(songs)) + + assert list(release) == songs + assert [MusicRenderer().song_line(s, release).plain[:4].strip() for s in release] == ["01", "2.06", "01"] + + +def test_a_release_from_an_older_title_cache_reads_as_having_no_positions(): + """jsonpickle restores a Song without its __init__, so an older entry has no 'position' key.""" + songs = [make_song(6, 2, album="B"), make_song(1, album="Z")] + for song in songs: + del song.__dict__["position"] + + restored = jsonpickle.loads(jsonpickle.dumps(songs)) + + assert ["position" in vars(song) for song in restored] == [False, False] + assert [song.listing_number for song in restored] == [(2, 6), (1, 1)] + assert [song.album for song in Album(reversed(restored))] == ["B", "Z"] diff --git a/tests/core/test_wire.py b/tests/core/test_wire.py index 5a8c3f276..b9d2f4d94 100644 --- a/tests/core/test_wire.py +++ b/tests/core/test_wire.py @@ -146,6 +146,7 @@ def song() -> Song: artwork_url="https://img.example/song.jpg", synced_lyrics="[00:01.00]la", lyrics_suffix=".lrc", + position=7, ) @@ -398,6 +399,7 @@ REST_SONG = { "synced_lyrics": "[00:01.00]la", "lyrics_suffix": ".lrc", "artwork_url": "https://img.example/song.jpg", + "position": 7, "music_data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"}, } @@ -783,6 +785,23 @@ def test_build_title_from_rest_song() -> None: } +def test_a_song_of_an_older_server_has_no_position() -> None: + rebuilt = build_title({k: v for k, v in REST_SONG.items() if k != "position"}, "EXAMPLE", "fallback-id") + assert (rebuilt.position, rebuilt.listing_number) == (None, (1, 3)) + + +@pytest.mark.parametrize("position", [0, -1, "7", 7.5, True, [7]]) +def test_build_title_refuses_a_bad_song_position(position: Any) -> None: + with pytest.raises((TypeError, ValueError), match="position"): + build_title({**REST_SONG, "position": position}, "EXAMPLE", "fallback-id") + + +def test_apply_title_fields_keeps_the_song_position() -> None: + title = song() + apply_title_fields(title, {"position": 9, "genre": "Jazz"}) + assert (title.position, title.genre) == (7, "Jazz") + + def test_build_title_from_export_meta() -> None: title = build_title(json_copy(META_EPISODE), "EXAMPLE", "fallback-id") assert title_fields(title) == {**EPISODE_FIELDS, "data": None, "description": None} diff --git a/tests/remote/unit/test_api_title_fields.py b/tests/remote/unit/test_api_title_fields.py index 80ad1817f..23f2a6d7a 100644 --- a/tests/remote/unit/test_api_title_fields.py +++ b/tests/remote/unit/test_api_title_fields.py @@ -177,6 +177,20 @@ def test_list_tracks_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch, w assert all((t["anime"], t["daily"]) == (True, True) for t in titles) +def test_list_tracks_selects_a_playlist_song_by_position(monkeypatch: pytest.MonkeyPatch) -> None: + songs = [ + Song(f"song-{album}", _FakeSvc, "Track", "Artist", album, track, disc, position=position) + for album, track, disc, position in (("Z", 1, 1, 1), ("B", 6, 2, 2), ("A", 2, 1, 3)) + ] + monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE") + monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService(songs), None, None)) + + response = asyncio.run(handlers.list_tracks_handler({"service": "FAKE", "title_id": "t1", "wanted": "2"})) + + title = json.loads(response.body)["title"] + assert (title["id"], title["position"], title["track"]) == ("song-B", 2, 6) + + 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, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService([ep()]), None, None)) diff --git a/tests/remote/unit/test_session_reopen.py b/tests/remote/unit/test_session_reopen.py index 9e88d55b7..c97833c7f 100644 --- a/tests/remote/unit/test_session_reopen.py +++ b/tests/remote/unit/test_session_reopen.py @@ -5,6 +5,7 @@ from __future__ import annotations import json import logging from threading import Lock +from typing import Any import click import pytest @@ -87,6 +88,63 @@ def test_a_lost_session_reopens_and_replays_the_call_under_the_new_ids(monkeypat assert service._title_alias == {"ep3-aaaa": "ep3-bbbb"} +def rest_song(id_: str, album: str, position: Any = None, track: int = 1) -> dict: + return {"type": "song", "id": id_, "name": "N", "artist": "A", "album": album, "track": track, "position": position} + + +@pytest.mark.parametrize( + ("before", "after", "alias"), + [ + pytest.param( + [rest_song("song-z", "Z", 1), rest_song("song-b", "B", 2)], + [rest_song("song-b", "B", 1), rest_song("song-z", "Z", 2)], + {}, + id="reordered-playlist", + ), + pytest.param( + [rest_song("song-clean", "Z", 1), rest_song("song-explicit", "Z", 2)], + [rest_song("song-explicit", "Z", 1)], + {}, + id="two-versions-of-one-single", + ), + pytest.param( + [rest_song("song-z", "Z"), rest_song("song-b", "B")], + [rest_song("song-z", "Z", 1), rest_song("song-b", "B", 2)], + {}, + id="server-updated", + ), + pytest.param( + [rest_song("song-x-old", "X"), rest_song("song-y-old", "X", track=2)], + [rest_song("song-x-new", "X"), rest_song("song-y-new", "X", track=2)], + {"song-x-old": "song-x-new", "song-y-old": "song-y-new"}, + id="album-without-positions", + ), + ], +) +@responses.activate +def test_a_reopened_session_never_takes_another_song_for_a_playlist_song(monkeypatch, before, after, alias): + service = make_service() + service._titles = [build_title(info, "TEST", "x") for info in before] + monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_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": after}) + + assert service.reopen() + assert service._title_alias == alias + + +@responses.activate +def test_a_malformed_song_position_on_reopen_is_one_error_line(monkeypatch): + service = make_service() + monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_session_id", "s2")) + responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False}) + listing = {"titles": [rest_song("song-z", "Z", "x")]} + responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json=listing) + + with pytest.raises(RemoteError, match="The remote server sent malformed titles: Expected position"): + service.reopen() + + @pytest.mark.parametrize( "broken", [ diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 6bdb5d2e3..0c9ab924e 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -723,7 +723,7 @@ class dl: "--wanted", type=SEASON_RANGE, default=None, - help="Wanted episodes, e.g. `S01-S05,S07`, `S01E01-S02E03`, `S02-S02E03`, etc. Music uses track numbers, e.g. `1-5`, `1,3,7`, or `2x3` for disc 2 track 3. Defaults to all.", + help="Wanted episodes, e.g. `S01-S05,S07`, `S01E01-S02E03`, `S02-S02E03`, etc. Music uses the numbers of the track list, e.g. `1-5`, `1,3,7`, or `2x3` for disc 2 track 3. Defaults to all.", ) @click.option( "-l", @@ -1953,7 +1953,7 @@ class dl: else: progress_sink({"title": getattr(title, "name", None) or str(title)}) - title_rule = f"Track {title.track:02}: {title.name}" if isinstance(title, Song) else 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))) metadata.search(title, listing=list_ or list_titles) diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 4e1b1e665..48854f10e 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -1508,7 +1508,7 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None else: log.debug(f"Episode {episode_key} not in wanted list") elif isinstance(title, Song): - song_key = f"{title.disc}x{title.track}" + song_key = "{}x{}".format(*title.listing_number) if title.matches_wanted(wanted): log.debug(f"Song {song_key} matches wanted list") matching_titles.append(title) diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 45dabc286..e2183f6c5 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -891,7 +891,7 @@ async def list_tracks(request: web.Request) -> web.Response: description: Title identifier wanted: type: string - description: Specific episode/season, or song ("1-5", "2x3" for disc 2 track 3) (optional) + description: Specific episode/season, or song by its number in the track list ("1-5", "2x3" for disc 2 track 3) (optional) proxy: type: string description: Full proxy URI on a public host, a Control D resolver as controld://@dns.controld.com, or a country code when the API key has server_proxy (default - None) @@ -1031,7 +1031,7 @@ async def download(request: web.Request) -> web.Response: type: array items: type: string - description: Wanted episodes (e.g., ["S01E01", "S01E02"]) or music tracks (e.g., ["1-5"], ["2x3"] for disc 2 track 3) (default - all) + description: Wanted episodes (e.g., ["S01E01", "S01E02"]) or music tracks by their number in the track list (e.g., ["1-5"], ["2x3"] for disc 2 track 3) (default - all) latest_episode: type: boolean description: Download only the single most recent episode (default - false) diff --git a/unshackle/core/music/renderer.py b/unshackle/core/music/renderer.py index 1284c71fa..b8b82a773 100644 --- a/unshackle/core/music/renderer.py +++ b/unshackle/core/music/renderer.py @@ -42,7 +42,7 @@ class MusicRenderer: 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) - total_discs = getattr(music, "total_discs", None) or self.max_value(music, "disc") + total_discs = getattr(music, "total_discs", None) or max(song.listing_number[0] for song in music) released = self.format_release_date( self.first_value( getattr(music, "released", None), @@ -126,7 +126,8 @@ class MusicRenderer: return text.replace("_", " ").replace("-", " ").title() def song_line(self, song: Song, music: Music) -> Text: - number = f"{song.disc}.{song.track:02}" if song.disc > 1 else f"{song.track:02}" + disc, track = song.listing_number + number = f"{disc}.{track:02}" if disc > 1 else f"{track:02}" line = Text() line.append(number, style="repr.number") line.append(" ") @@ -313,10 +314,5 @@ class MusicRenderer: continue return total - @staticmethod - def max_value(music: Music, attr: str) -> int: - values = [getattr(song, attr, 0) or 0 for song in music] - return max(values, default=0) - __all__ = ("MusicRenderer",) diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 0163ee2b0..a02fff813 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -446,11 +446,14 @@ def segment_uri_filter(uris: Iterable[Any]) -> Callable[[Any], bool]: def title_key(title: Title_T) -> tuple: - """What tells a title apart from the others in one listing, other than its id: a service may vary the id per listing.""" + """What tells a title apart from the others in one listing, other than its id: a service may vary the id per listing. + + A song with a position has only its id: an edited playlist gives that number to another song. + """ if isinstance(title, Episode): return (title.season, title.number, title.part) if isinstance(title, Song): - return (title.disc, title.track) + return (title.id,) if title.position else (title.disc, title.track) return (getattr(title, "year", None),) @@ -1290,7 +1293,8 @@ class RemoteService(TitleSource): listing = cast(TitlesReply, self.client.get(TITLES_ROUTE.format(session_id=self._session_id))).get( "titles", [] ) - fresh_titles = [build_title(t, self.service_tag, self.title_id) for t in listing] + with malformed_answer("titles"): + fresh_titles = [build_title(t, self.service_tag, self.title_id) for t in listing] for old in self._titles or []: same = [t for t in fresh_titles if title_key(t) == title_key(old)] if len(same) == 1 and str(same[0].id) != str(old.id): diff --git a/unshackle/core/titles/music.py b/unshackle/core/titles/music.py index e99e9194a..69a960667 100644 --- a/unshackle/core/titles/music.py +++ b/unshackle/core/titles/music.py @@ -32,6 +32,7 @@ SONG_FIELDS = ( "synced_lyrics", "lyrics_suffix", "artwork_url", + "position", ) """The `Song` attributes a remote session sends, beyond the fields every title has.""" @@ -77,6 +78,8 @@ def song_metadata(song: Any) -> dict[str, Any]: class Song(Title): + position: int | None = None + def __init__( self, id_: Any, @@ -103,9 +106,12 @@ class Song(Title): artwork_url: str | None = None, synced_lyrics: str | None = None, lyrics_suffix: str | None = None, + position: int | None = None, ) -> None: """`lyrics` is the plain text the tagger embeds. + `position` is the number in a playlist: it replaces `track` in the listing and in `-w`, not in tags or names. + `synced_lyrics` (timed LRC or TTML) is saved beside the audio file with `lyrics_suffix` (".lrc", ".ttml"). """ super().__init__(id_, service, language, data) @@ -164,6 +170,9 @@ class Song(Title): if lyrics_suffix is not None and not (isinstance(lyrics_suffix, str) and lyrics_suffix.startswith(".")): raise TypeError(f"Expected lyrics_suffix to be a str starting with '.', not {lyrics_suffix!r}") + if position is not None and (isinstance(position, bool) or not isinstance(position, int)): + raise TypeError(f"Expected position to be an int, not {position!r}") + name = name.strip() artist = artist.strip() album = album.strip() @@ -189,6 +198,8 @@ class Song(Title): raise ValueError(f"Song total_tracks cannot be {total_tracks}") if total_discs is not None and total_discs <= 0: raise ValueError(f"Song total_discs cannot be {total_discs}") + if position is not None and position <= 0: + raise ValueError(f"Song position cannot be {position}") self.name = name self.artist = artist @@ -210,6 +221,12 @@ class Song(Title): self.artwork_url = artwork_url self.synced_lyrics = synced_lyrics.strip() if synced_lyrics else None self.lyrics_suffix = lyrics_suffix + self.position = position + + @property + def listing_number(self) -> tuple[int, int]: + """The disc and track that the listing shows and ``-w`` selects; a position is always on disc 1.""" + return (1, self.position) if self.position else (self.disc, self.track) def __str__(self) -> str: return "{artist} - {album} ({year}) / {track:02}. {name}".format( @@ -221,9 +238,9 @@ class Song(Title): A song shares the episode key space, its disc reading as the season and its track as the episode, so ``-w 1-5`` takes tracks 1 to 5 and ``-w 2x3`` takes disc 2 - track 3. A song has no parts and no air date, so it answers to its disc-and-track key only. + track 3. A song with a position answers to that number instead of its disc and track. """ - return f"{self.disc}x{self.track}" in wanted + return "{}x{}".format(*self.listing_number) in wanted def build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict: """Build template context dictionary from MediaInfo.""" @@ -309,7 +326,7 @@ class Music(SortedKeyList, ABC): if description is not None and not isinstance(description, str): raise TypeError(f"Expected description to be a str, not {description!r}") - super().__init__(iterable, key=lambda x: (x.album, x.disc, x.track, x.year or 0)) + super().__init__(iterable, key=lambda x: (x.position or 0, x.album, x.disc, x.track, x.year or 0)) kind = kind.strip().lower() if not kind: diff --git a/unshackle/core/wire.py b/unshackle/core/wire.py index 787a18fda..8c9e3105c 100644 --- a/unshackle/core/wire.py +++ b/unshackle/core/wire.py @@ -221,8 +221,8 @@ def apply_title_fields(title: Title_T, info: dict[str, Any]) -> None: A service can change its title inside ``get_tracks`` (a corrected original language, a real episode name, an air date), so the client re-applies the server's view of the - title after every call that returns one. Season, number and part are set only by - ``build_title``, as dl can renumber them after the listing. + title after every call that returns one. Season, number, part and position are set only by + ``build_title``: dl can renumber the first three after the listing, and the position orders it. """ if info.get("language"): title.language = Language.get(info["language"]) @@ -244,7 +244,7 @@ def apply_title_fields(title: Title_T, info: dict[str, Any]) -> None: title.name = info["name"] for key in ("anime", "daily", "sport", "metadata_provider", *(SONG_FIELDS if isinstance(title, Song) else ())): - if info.get(key) is not None: + if info.get(key) is not None and key != "position": setattr(title, key, info[key]) extra = {k: info[k] for k in ("date", "cover_url") if info.get(k) is not None} @@ -308,6 +308,7 @@ def build_title(info: dict[str, Any], service_tag: str, fallback_id: str) -> Tit artwork_url=info.get("artwork_url"), synced_lyrics=info.get("synced_lyrics"), lyrics_suffix=info.get("lyrics_suffix"), + position=info.get("position"), ) else: raise click.ClickException(