forked from kenzuya/unshackle
refactor(music)!: make Song an ordinary Title on the generic path
Delete the dead grouped-download block, the planner, and the music service hooks; Song now flows through the one download loop, gets tagged via tag_file, and answers -w with {disc}x{track} keys.
BREAKING CHANGE: GROUP_AUDIO_DOWNLOADS, get_music_track_options and get_music_collection_label are gone. A music service returns one Audio track per quality and lets the framework choose.
This commit is contained in:
@@ -3,33 +3,28 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
from rich import box
|
||||
from rich.console import Group, RenderableType
|
||||
from rich.markup import escape
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from rich.tree import Tree
|
||||
|
||||
from unshackle.core.music.models import MusicDownloadPlan, MusicTrackOption
|
||||
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
|
||||
|
||||
|
||||
class MusicRenderer:
|
||||
"""Render native Music title containers for the CLI."""
|
||||
"""Render a Music release for the CLI title listing.
|
||||
|
||||
COMPACT_TRACK_LIMIT = 8
|
||||
The album header and per-track lines are specific to music. The box around
|
||||
the tracklist comes from ``listing_panel``, so it restyles along with the
|
||||
track listing that core prints for every other title type.
|
||||
"""
|
||||
|
||||
def render(self, music: Music, *, verbose: bool = False) -> RenderableType:
|
||||
def render(self, music: Music) -> RenderableType:
|
||||
header = self.render_header(music)
|
||||
tracks = self.render_tracks(music, verbose=verbose)
|
||||
if header:
|
||||
return Group(header, Text(""), tracks)
|
||||
return tracks
|
||||
|
||||
def render_plan(self, plan: MusicDownloadPlan, *, verbose: bool = True) -> RenderableType:
|
||||
header = self.render_plan_header(plan)
|
||||
tracks = self.render_plan_tracks(plan, verbose=verbose)
|
||||
tracks = self.render_tracks(music)
|
||||
if header:
|
||||
return Group(header, Text(""), tracks)
|
||||
return tracks
|
||||
@@ -60,7 +55,7 @@ class MusicRenderer:
|
||||
)
|
||||
length = self.format_total_duration(getattr(music, "total_duration", None) or self.sum_duration(music))
|
||||
quality = self.quality_summary(
|
||||
self.first_text(
|
||||
first_text(
|
||||
getattr(music, "quality", None),
|
||||
data.get("quality"),
|
||||
metadata.get("quality"),
|
||||
@@ -70,119 +65,44 @@ class MusicRenderer:
|
||||
hires=self.as_bool(self.first_value(data.get("hires"), metadata.get("hires"))),
|
||||
)
|
||||
|
||||
grid = self.metadata_grid()
|
||||
grid = Table.grid(padding=(0, 2))
|
||||
grid.add_column(style="bright_black", no_wrap=True)
|
||||
grid.add_column()
|
||||
|
||||
grid.add_row(Text("Title", style="bright_black"), Text(str(title)))
|
||||
grid.add_row(Text("Artist", style="bright_black"), Text(str(artist)))
|
||||
grid.add_row(Text("Type", style="bright_black"), self.kind_text(kind, explicit=explicit))
|
||||
# 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)))
|
||||
grid.add_row("Type", self.kind_text(kind, explicit=explicit))
|
||||
if released:
|
||||
grid.add_row(Text("Released", style="bright_black"), Text(released))
|
||||
grid.add_row("Released", Text(released))
|
||||
if year:
|
||||
grid.add_row(Text("Year", style="bright_black"), Text(str(year)))
|
||||
grid.add_row(Text("Tracks", style="bright_black"), Text(str(total_tracks)))
|
||||
grid.add_row("Year", Text(str(year)))
|
||||
grid.add_row("Tracks", Text(str(total_tracks)))
|
||||
if total_discs and total_discs > 1:
|
||||
grid.add_row(Text("Discs", style="bright_black"), Text(str(total_discs)))
|
||||
grid.add_row("Discs", Text(str(total_discs)))
|
||||
if length:
|
||||
grid.add_row(Text("Length", style="bright_black"), Text(length))
|
||||
grid.add_row("Length", Text(length))
|
||||
if quality:
|
||||
grid.add_row(Text("Quality", style="bright_black"), Text(quality))
|
||||
grid.add_row("Quality", Text(quality))
|
||||
if first_song.genre:
|
||||
grid.add_row(Text("Genre", style="bright_black"), Text(first_song.genre))
|
||||
grid.add_row("Genre", Text(first_song.genre))
|
||||
if first_song.label:
|
||||
grid.add_row(Text("Label", style="bright_black"), Text(first_song.label))
|
||||
grid.add_row("Label", Text(first_song.label))
|
||||
|
||||
return grid
|
||||
|
||||
def render_tracks(self, music: Music, *, verbose: bool = False) -> Panel:
|
||||
def render_tracks(self, music: Music) -> Panel:
|
||||
total = len(music)
|
||||
track_label = "Track" if total == 1 else "Tracks"
|
||||
tree = Tree(f"[repr.number]{total}[/] {track_label}", guide_style="bright_black")
|
||||
|
||||
visible_songs = list(music)
|
||||
if not verbose and len(visible_songs) > self.COMPACT_TRACK_LIMIT:
|
||||
visible_songs = visible_songs[: self.COMPACT_TRACK_LIMIT]
|
||||
|
||||
for song in visible_songs:
|
||||
node = tree.add(self.song_line(song, music), guide_style="bright_black")
|
||||
for song in music:
|
||||
node = tree.add(self.song_line(song, music))
|
||||
option = self.option_from_song(song)
|
||||
if option:
|
||||
node.add(option, guide_style="bright_black")
|
||||
node.add(option)
|
||||
|
||||
hidden = total - len(visible_songs)
|
||||
if hidden > 0:
|
||||
suffix = "s" if hidden != 1 else ""
|
||||
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
|
||||
|
||||
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
|
||||
|
||||
def render_plan_header(self, plan: MusicDownloadPlan) -> Optional[Table]:
|
||||
title = plan.title
|
||||
artist = plan.artist or plan.album_artist
|
||||
kind = self.display_kind(plan.kind)
|
||||
explicit = any(
|
||||
bool(getattr(song_plan.song, "explicit", None) or (song_plan.selected and song_plan.selected.explicit))
|
||||
for disc in plan.discs
|
||||
for song_plan in disc.songs
|
||||
)
|
||||
released = self.format_release_date(getattr(plan, "released", None) or getattr(plan, "release_date", None))
|
||||
length = self.format_total_duration(plan.total_duration)
|
||||
quality = self.quality_summary(plan.quality_requested)
|
||||
|
||||
grid = self.metadata_grid()
|
||||
if title:
|
||||
grid.add_row(Text("Title", style="bright_black"), Text(str(title)))
|
||||
if artist:
|
||||
grid.add_row(Text("Artist", style="bright_black"), Text(str(artist)))
|
||||
grid.add_row(Text("Type", style="bright_black"), self.kind_text(kind, explicit=explicit))
|
||||
if released:
|
||||
grid.add_row(Text("Released", style="bright_black"), Text(released))
|
||||
if plan.year:
|
||||
grid.add_row(Text("Year", style="bright_black"), Text(str(plan.year)))
|
||||
if plan.total_tracks:
|
||||
grid.add_row(Text("Tracks", style="bright_black"), Text(str(plan.total_tracks)))
|
||||
if plan.total_discs and plan.total_discs > 1:
|
||||
grid.add_row(Text("Discs", style="bright_black"), Text(str(plan.total_discs)))
|
||||
if length:
|
||||
grid.add_row(Text("Length", style="bright_black"), Text(length))
|
||||
if quality:
|
||||
grid.add_row(Text("Quality", style="bright_black"), Text(quality))
|
||||
if plan.genre:
|
||||
grid.add_row(Text("Genre", style="bright_black"), Text(str(plan.genre)))
|
||||
if plan.label:
|
||||
grid.add_row(Text("Label", style="bright_black"), Text(str(plan.label)))
|
||||
return grid
|
||||
|
||||
def render_plan_tracks(self, plan: MusicDownloadPlan, *, verbose: bool = True) -> Panel:
|
||||
songs = [song_plan for disc in plan.discs for song_plan in disc.songs]
|
||||
total = len(songs)
|
||||
track_label = "Track" if total == 1 else "Tracks"
|
||||
tree = Tree(f"[repr.number]{total}[/] {track_label}", guide_style="bright_black")
|
||||
|
||||
visible_songs = songs
|
||||
if not verbose and len(visible_songs) > self.COMPACT_TRACK_LIMIT:
|
||||
visible_songs = visible_songs[: self.COMPACT_TRACK_LIMIT]
|
||||
|
||||
for song_plan in visible_songs:
|
||||
node = tree.add(self.song_line(song_plan.song, plan), guide_style="bright_black")
|
||||
if song_plan.skip_reason:
|
||||
node.add(f"[yellow]Skipped:[/] {escape(song_plan.skip_reason)}", guide_style="bright_black")
|
||||
continue
|
||||
for option in song_plan.options:
|
||||
node.add(self.option_line(option), guide_style="bright_black")
|
||||
|
||||
hidden = total - len(visible_songs)
|
||||
if hidden > 0:
|
||||
suffix = "s" if hidden != 1 else ""
|
||||
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
|
||||
|
||||
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
|
||||
|
||||
@staticmethod
|
||||
def metadata_grid() -> Table:
|
||||
grid = Table.grid(padding=(0, 2))
|
||||
grid.add_column(style="orchid1", no_wrap=True)
|
||||
grid.add_column()
|
||||
return grid
|
||||
return listing_panel(tree, "Tracklist")
|
||||
|
||||
@staticmethod
|
||||
def display_kind(kind: Any) -> str:
|
||||
@@ -205,7 +125,7 @@ class MusicRenderer:
|
||||
return labels[key]
|
||||
return text.replace("_", " ").replace("-", " ").title()
|
||||
|
||||
def song_line(self, song: Song, music: Music | MusicDownloadPlan) -> Text:
|
||||
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}"
|
||||
line = Text()
|
||||
line.append(number, style="repr.number")
|
||||
@@ -217,20 +137,22 @@ class MusicRenderer:
|
||||
line.append(f" - {song.artist}", style="bright_black")
|
||||
return line
|
||||
|
||||
def option_from_song(self, song: Song) -> Text | str:
|
||||
def option_from_song(self, song: Song) -> Text:
|
||||
data = song.data if isinstance(song.data, dict) else {}
|
||||
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
||||
|
||||
quality = self.first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
|
||||
duration = self.format_duration(self.first_value(data.get("duration"), metadata.get("duration")))
|
||||
reason = self.first_text(
|
||||
quality = first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
|
||||
raw_duration = self.first_value(data.get("duration"), metadata.get("duration"))
|
||||
# an already-formatted duration ("3:45") does not parse as seconds, so show it as given
|
||||
duration = format_duration(raw_duration) or first_text(raw_duration)
|
||||
reason = first_text(
|
||||
data.get("unavailable_reason"),
|
||||
data.get("skip_reason"),
|
||||
metadata.get("unavailable_reason"),
|
||||
metadata.get("skip_reason"),
|
||||
)
|
||||
if reason:
|
||||
return f"[yellow]Skipped:[/] {escape(reason)}"
|
||||
return Text.assemble(("Skipped:", "yellow"), f" {reason}")
|
||||
|
||||
badges = []
|
||||
if song.explicit:
|
||||
@@ -246,35 +168,9 @@ class MusicRenderer:
|
||||
if duration:
|
||||
details.append(duration)
|
||||
if not details and not badges:
|
||||
return ""
|
||||
return Text()
|
||||
return self.format_option_text(details, badges)
|
||||
|
||||
def option_line(self, option: MusicTrackOption) -> Text:
|
||||
parts = []
|
||||
codec = str(option.codec or "").strip()
|
||||
if codec:
|
||||
parts.append(f"[{codec}]")
|
||||
if option.quality_label:
|
||||
parts.extend(self.split_quality_label(option.quality_label, codec))
|
||||
elif option.bit_depth and option.sample_rate:
|
||||
parts.append(f"{option.bit_depth}-bit/{self.format_sample_rate(option.sample_rate)}")
|
||||
elif option.bitrate:
|
||||
parts.append(f"{int(option.bitrate / 1000)} kb/s")
|
||||
if option.channels:
|
||||
parts.append(self.format_channels(option.channels))
|
||||
if option.duration:
|
||||
parts.append(self.format_duration(option.duration))
|
||||
badges = []
|
||||
if option.explicit:
|
||||
badges.append(("E", "bold bright_red"))
|
||||
if option.atmos:
|
||||
badges.append(("Atmos", "magenta"))
|
||||
if self.is_cd_option(option):
|
||||
badges.append(("CD", "yellow1"))
|
||||
if option.hires:
|
||||
badges.append(("Hi-Res", "gold1"))
|
||||
return self.format_option_text(parts, badges)
|
||||
|
||||
@staticmethod
|
||||
def kind_text(kind: str, *, explicit: bool = False) -> Text:
|
||||
text = Text(str(kind))
|
||||
@@ -300,76 +196,6 @@ class MusicRenderer:
|
||||
first = False
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def format_option_parts(parts: list[str]) -> str:
|
||||
if not parts:
|
||||
return ""
|
||||
return " | ".join(escape(part) for part in parts if part)
|
||||
|
||||
@staticmethod
|
||||
def split_quality_label(value: str, codec: str = "") -> list[str]:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
if codec and text.lower().startswith(codec.lower()):
|
||||
text = text[len(codec) :].strip()
|
||||
return [text] if text else []
|
||||
|
||||
@staticmethod
|
||||
def is_cd_option(option: MusicTrackOption) -> bool:
|
||||
codec = str(option.codec or "").upper()
|
||||
if codec not in {"FLAC", "ALAC", "WAV", "AIFF"}:
|
||||
return False
|
||||
if option.bit_depth == 16 and option.sample_rate in {44100, 44100.0}:
|
||||
return True
|
||||
return "16-bit/44.1" in str(option.quality_label or "").lower()
|
||||
|
||||
@staticmethod
|
||||
def format_sample_rate(value: Any) -> str:
|
||||
try:
|
||||
sample_rate = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value).strip()
|
||||
if sample_rate >= 1000:
|
||||
sample_rate /= 1000
|
||||
if sample_rate.is_integer():
|
||||
return f"{int(sample_rate)} kHz"
|
||||
return f"{sample_rate:g} kHz"
|
||||
|
||||
@staticmethod
|
||||
def format_channels(value: Any) -> str:
|
||||
try:
|
||||
channels = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value).strip()
|
||||
if channels == 1:
|
||||
return "Mono"
|
||||
if channels == 2:
|
||||
return "Stereo"
|
||||
if channels.is_integer():
|
||||
return f"{int(channels)}.0"
|
||||
return f"{channels:g}"
|
||||
|
||||
@staticmethod
|
||||
def first_text(*values: Any) -> str:
|
||||
for value in values:
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, dict):
|
||||
for key in ("label", "name", "title", "display_name", "value"):
|
||||
nested = value.get(key)
|
||||
if nested:
|
||||
return str(nested).strip()
|
||||
elif isinstance(value, (list, tuple)):
|
||||
text = MusicRenderer.first_text(*value)
|
||||
if text:
|
||||
return text
|
||||
else:
|
||||
text = str(value).strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def first_value(*values: Any) -> Any:
|
||||
for value in values:
|
||||
@@ -385,20 +211,6 @@ class MusicRenderer:
|
||||
return value.strip().lower() in {"1", "true", "yes", "y"}
|
||||
return bool(value)
|
||||
|
||||
@staticmethod
|
||||
def format_duration(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
try:
|
||||
seconds = int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return str(value).strip()
|
||||
minutes, seconds = divmod(seconds, 60)
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
if hours:
|
||||
return f"{hours}:{minutes:02}:{seconds:02}"
|
||||
return f"{minutes}:{seconds:02}"
|
||||
|
||||
@staticmethod
|
||||
def format_total_duration(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
|
||||
Reference in New Issue
Block a user