Typed music searches use YouTube Music for real album details

A search now finds the song on YouTube Music and keeps its artists, album,
year and square album art, which also feeds the card's colours. Plain
YouTube is the fallback, and links keep their own details.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-06 20:43:27 -06:00
commit 6bb6be168b
3 changed files with 66 additions and 3 deletions

View file

@ -105,6 +105,6 @@ Plan (backward compatible with the existing file):
- Dashboard controls live in `web/dashboard/static/controls.js` (faders, switches, segments, searchable pickers, colour picker). Every control fires a bubbling `input`; sections go through one save bar.
- The server page has only been looked at with faked API answers (`--web-dev` has no Discord cache). Not checked on the live bot yet.
- Fixed: role menus published from the dashboard no longer claim roles they didn't make (taking one out used to delete a server's own role); zero ids no longer panic `D!ban`; announcement channels show in the pickers; static files revalidate after an update.
- Music panel: an animated GIF drawn by `commands/music/card.rs`, laid out like the website's player: cover and title, moving bars, clock and progress. Each GIF is 30 s and is replaced about every 20 s while people listen; paused gives a still JPEG. Bar heights follow the song's real loudness (`source::peaks`), their shape is drawn, not a real spectrum. Bar colours come from the album cover (greys for a cover with no colour). Without Attach Files the panel falls back to the text card.
- Music panel: an animated GIF drawn by `commands/music/card.rs`, laid out like the website's player: cover and title, moving bars, clock and progress. Each GIF is 30 s and is replaced about every 20 s while people listen; paused gives a still JPEG. Bar heights follow the song's real loudness (`source::peaks`), their shape is drawn, not a real spectrum. Bar colours come from the album cover (greys for a cover with no colour). Typed searches go to YouTube Music for the real artist, album, year and square art, falling back to plain YouTube; links keep their own details. Without Attach Files the panel falls back to the text card.
- Voice: a failed join now forgets the call, and a song whose position stands still for 45 s tells the channel and leaves. Why the joins failed on 2026-11-06 isn't known; songbird logs nothing at info level for it.
- Known gap, unchanged: on a stage channel the bot can't unsuppress itself (twilight's `suppress()` only sets true).

View file

@ -710,6 +710,7 @@ async fn panel_picture(p: &Player) -> Option<Attachment> {
let art = track.art.lock().unwrap_or_else(|e| e.into_inner());
let status = if cur.paused { "Paused" } else if track.duration.is_none() { "Live" } else { "Now playing" };
let mut who: Vec<String> = track.uploader.iter().cloned().collect();
who.extend(track.album.iter().map(|a| track.year.map_or(a.clone(), |y| format!("{a} ({y})"))));
who.push(track.duration.map_or("Live".to_string(), |d| fmt_time(d as f64)));
(cur.paused, card::View { status: status.to_string(), title: track.title.clone(), artist: who.join(" · "), position: cur.pos.seconds(), duration: track.duration.map(|d| d as f64), levels: art.peaks.clone(), cover: art.cover.clone() })
};

View file

@ -31,6 +31,9 @@ pub struct Track {
pub duration: Option<u64>,
pub thumbnail: Option<String>,
pub uploader: Option<String>,
/// The album and its year, for songs found on YouTube Music.
pub album: Option<String>,
pub year: Option<u64>,
pub requester: Option<u64>,
pub stream: Arc<AsyncMutex<Option<Stream>>>,
pub accent: Arc<Mutex<Option<u32>>>,
@ -59,7 +62,7 @@ fn title_from_url(url: &str) -> String {
impl Track {
fn blank(url: String, title: String, requester: Option<u64>) -> Self {
Self { url, title, duration: None, thumbnail: None, uploader: None, requester, stream: Default::default(), accent: Default::default(), art: Default::default() }
Self { url, title, duration: None, thumbnail: None, uploader: None, album: None, year: None, requester, stream: Default::default(), accent: Default::default(), art: Default::default() }
}
/// From a full extraction (has the stream URL).
@ -70,6 +73,19 @@ impl Track {
t
}
/// From a full extraction of a YouTube Music song: the real title, artists, album and square album art.
pub fn from_music(info: &Value, requester: Option<u64>) -> Self {
let mut t = Self::from_info(info, requester);
t.title = s(info, "track").unwrap_or(t.title);
let artists: Vec<&str> = info["artists"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
t.uploader = if artists.is_empty() { s(info, "artist").or(t.uploader) } else { Some(artists.join(", ")) };
t.album = s(info, "album");
t.year = info["release_year"].as_u64();
let square = info["thumbnails"].as_array().into_iter().flatten().filter(|x| x["width"].as_u64().is_some() && x["width"] == x["height"]).max_by_key(|x| x["width"].as_u64());
t.thumbnail = square.and_then(|x| s(x, "url")).or(t.thumbnail);
t
}
/// A flat playlist entry (metadata only, no stream yet).
pub fn from_entry(e: &Value, requester: Option<u64>) -> Self {
let youtube = e["ie_key"].as_str() == Some("Youtube") || e["extractor"].as_str().is_some_and(|x| x.to_lowercase().contains("youtube"));
@ -155,7 +171,7 @@ pub async fn extract(query: &str, mode: Mode) -> Result<Value, String> {
cmd.args(["-J", "--no-warnings", "--source-address", "0.0.0.0", "--socket-timeout", "10", "--retries", "3", "--no-cache-dir"]);
let limit = match &mode {
Mode::Search => {
cmd.args(["--flat-playlist", "--no-playlist", "--extractor-args", "youtubetab:skip=webpage"]);
cmd.args(["--flat-playlist", "--no-playlist", "--playlist-end", "1", "--extractor-args", "youtubetab:skip=webpage"]);
SEARCH_TIMEOUT
}
Mode::Link { first } => {
@ -190,6 +206,18 @@ pub struct Found {
pub more: Option<String>,
}
/// The best song for a typed search on YouTube Music. `None` sends the search to plain YouTube instead.
async fn music_search(query: &str, requester: u64) -> Option<Track> {
let page = reqwest::Url::parse_with_params("https://music.youtube.com/search", &[("q", query)]).ok()?;
let found = extract(&format!("{page}#songs"), Mode::Search).await.ok()?;
let link = found["entries"].as_array()?.iter().find_map(|e| s(e, "url"))?;
let info = extract(&link, Mode::Resolve).await.ok()?;
let stream = Track::stream_of(&info)?;
let track = Track::from_music(&info, Some(requester));
*track.stream.try_lock().ok()? = Some(stream);
Some(track)
}
pub async fn search(query: &str, requester: u64) -> Result<Found, String> {
let query = query.trim().trim_matches(|c| c == '<' || c == '>');
if query.starts_with("http://") || query.starts_with("https://") {
@ -209,6 +237,9 @@ pub async fn search(query: &str, requester: u64) -> Result<Found, String> {
*track.stream.try_lock().unwrap() = Some(stream);
return Ok(Found { tracks: vec![track], playlist: None, more: None });
}
if let Some(track) = music_search(query, requester).await {
return Ok(Found { tracks: vec![track], playlist: None, more: None });
}
let info = extract(&format!("ytsearch1:{query}"), Mode::Search).await?;
let tracks: Vec<Track> = info["entries"].as_array().into_iter().flatten().filter(|e| !e.is_null()).map(|e| Track::from_entry(e, Some(requester))).filter(|t| !t.url.is_empty()).collect();
if tracks.is_empty() {
@ -292,4 +323,35 @@ mod tests {
assert!(real > 50, "only {real} frames of audio");
assert!(pos.seconds() > 1.0);
}
#[test]
fn youtube_music_songs_keep_their_album_details() {
let info = serde_json::json!({
"webpage_url": "https://www.youtube.com/watch?v=abc", "title": "Heartless (Official Video)", "track": "Heartless", "channel": "Kanye West - Topic",
"artists": ["Kanye West", "Someone Else"], "album": "808s & Heartbreak", "release_year": 2008, "duration": 211, "thumbnail": "https://i.ytimg.com/wide.jpg",
"thumbnails": [{"url": "https://a/226", "width": 226, "height": 226}, {"url": "https://a/544", "width": 544, "height": 544}, {"url": "https://a/wide", "width": 1920, "height": 1080}],
});
let t = Track::from_music(&info, Some(1));
assert_eq!(t.title, "Heartless");
assert_eq!(t.uploader.as_deref(), Some("Kanye West, Someone Else"));
assert_eq!((t.album.as_deref(), t.year), (Some("808s & Heartbreak"), Some(2008)));
assert_eq!(t.thumbnail.as_deref(), Some("https://a/544"));
assert_eq!(t.duration, Some(211));
}
#[test]
fn links_keep_their_own_details() {
let info = serde_json::json!({"webpage_url": "https://www.youtube.com/watch?v=abc", "title": "My video", "track": "Other", "channel": "A channel", "album": "An album", "thumbnail": "https://i/v.jpg"});
let t = Track::from_info(&info, None);
assert_eq!((t.title.as_str(), t.uploader.as_deref(), t.album.as_deref()), ("My video", Some("A channel"), None));
}
#[tokio::test]
#[ignore = "needs the internet and yt-dlp"]
async fn live_youtube_music_search_finds_the_album() {
let t = music_search("kanye west heartless", 1).await.expect("found");
println!("{} | {:?} | {:?} | {:?} | {:?} | {:?}", t.title, t.uploader, t.album, t.year, t.duration, t.thumbnail);
assert_eq!(t.title, "Heartless");
assert!(t.album.is_some() && t.duration.is_some());
}
}