feat(music): list and select playlist songs by their position

This commit is contained in:
imSp4rky
2026-11-30 12:39:51 -07:00
parent 40114fff19
commit 70ace41201
16 changed files with 222 additions and 38 deletions
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
+2 -2
View File
@@ -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://<resolver>@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)
+3 -7
View File
@@ -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",)
+7 -3
View File
@@ -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):
+20 -3
View File
@@ -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:
+4 -3
View File
@@ -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(