From ef26f7ff12fd87b670060bfebbcdcafa3bec3aac Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 15:44:39 -0600 Subject: [PATCH] Covers and artist photos with fallbacks, tag IDs first Covers come from the release in the player's own tags (Cover Art Archive), then ListenBrainz's match, the release group, Deezer and iTunes. Deezer and iTunes results count only when the artist and title match. Artist photos come from Deezer, then MusicBrainz/Wikimedia. Missing album names are looked up on Deezer. Play counts and Who Knows match by MusicBrainz ID before names. Co-Authored-By: Claude Opus 5.5 --- docs/DECISIONS.md | 1 + docs/PROGRESS.md | 5 + src/commands/lastfm/api.rs | 32 +++-- src/commands/lastfm/covers.rs | 263 ++++++++++++++++++++++++++++++++++ src/commands/lastfm/extras.rs | 99 ++++++------- src/commands/lastfm/mod.rs | 1 + src/commands/lastfm/views.rs | 28 +++- web/site/privacy.html | 2 +- 8 files changed, 356 insertions(+), 75 deletions(-) create mode 100644 src/commands/lastfm/covers.rs diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 0761907..e6dbc52 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -12,3 +12,4 @@ - D-008 — 2026-11-12 — Adds to D-007 (owner reference `assets/reference/speechbubble-bsm.gif`, BSM-bot style): the bubble is a wide white ellipse with a black outline hanging off the edge, its tail pointing into the picture, the picture's edge clipped to the bubble's curve. Options on `/speechbubble`: `position` top|bottom (bubble hangs off that edge, tail points inward), `flip` (mirrors the tail to the other side), `solid` (white fill; without it the bubble is cut out transparent where the format allows). Inputs and outputs cover many media types: PNG, JPG, WebP (still and animated), GIF and video (MP4/WebM/MOV); animated input stays animated (every frame gets the bubble), video comes back as GIF or video in the same format. `/caption` takes the same input types. Both are also `D!speechbubble` / `D!caption`. — Owner reference, 2026-11-12. — 02 Image commands. - D-009 — 2026-11-12 — The Assyst-style output described in D-007 (transparent cutout, no outline, tail toward the right) is saved as `assets/reference/speechbubble-assyst.gif`, next to the BSM-style `speechbubble-bsm.gif` (D-008). Compare the drawn bubbles against both. — Owner request. — 02 Image commands. - D-010 — 2026-12-01 — The fm commands read ListenBrainz (free, no key) instead of the Last.fm API, which needs Pro for everything but scrobbling from 2026-12-01. Same commands and cards; links are stored separately in `data/listenbrainz.json` (`data/lastfm.json` is kept, untouched); song links still go to the Last.fm website (free, and the Listen button reads them). Lyrics song search uses Deezer (popularity-ranked, no key). The Last.fm version is the git tag `lastfm-api-backup`. — Owner request. — all fm commands. +- D-011 — 2026-12-01 — Covers come from a chain (`src/commands/lastfm/covers.rs`): the release ID in the player's own tags (Cover Art Archive) → ListenBrainz's match → the release group → Deezer → iTunes; Deezer/iTunes results count only when artist and title match. Artist photos: Deezer → MusicBrainz/Wikimedia. Play counts match by MusicBrainz ID before names. — MusicBrainz art alone left many covers blank; owner asked for the most reliable sources with fallbacks. — fm commands. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index ed68c9b..992092b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -9,5 +9,10 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: not tested in Discord 🧑; not deployed. Everyone must link again (`/fm mode:link`), ListenBrainz names can differ from Last.fm ones. - Differences: periods are ListenBrainz's (last week/month/quarter/half-year, this year), not rolling; stats update about once a day; Who Knows and "plays of this track" only see each person's all-time top 1000. +## 2026-12-01 — covers and artist photos with fallbacks (owner request) +- Done: `covers.rs` (cover chain, artist photos, missing album names via Deezer); listens keep the player's tag IDs (`mbids`), tags win over ListenBrainz's guess; play counts and Who Knows match by ID first. Every card, chart and Pixel Jumble uses it. +- Verified: `cargo test` (same 8 worktree-only asset failures); `cargo test covers_live -- --ignored` and `listenbrainz_live` pass. +- Not done: not deployed at commit time; not checked in Discord 🧑. + ## Later - (none yet) diff --git a/src/commands/lastfm/api.rs b/src/commands/lastfm/api.rs index 851effd..8225f13 100644 --- a/src/commands/lastfm/api.rs +++ b/src/commands/lastfm/api.rs @@ -158,11 +158,15 @@ impl Lb { } /// How often `username` played an artist/album/track (all time), with that entry. `None` when it isn't in their - /// top `LOOKUP_DEPTH`. - pub async fn plays(&self, username: &str, kind: &str, name: &str, artist: Option<&str>) -> Result, Error> { + /// top `LOOKUP_DEPTH`. `mbid` (a recording/release group/artist ID, e.g. from the player's tags) is matched first: + /// names differ between players ("feat.", "Remastered"), IDs don't. + pub async fn plays(&self, username: &str, kind: &str, name: &str, artist: Option<&str>, mbid: Option<&str>) -> Result, Error> { let items = self.top(username, &format!("{kind}s"), "overall", LOOKUP_DEPTH).await?; + let id_key = match kind { "artist" => "artist", "album" => "release_group", _ => "recording" }; + let by_id = mbid.filter(|m| !m.is_empty()).and_then(|m| items.iter().position(|i| i["mbids"][id_key].as_str() == Some(m))); let same = |a: &str, b: &str| a.trim().to_lowercase() == b.trim().to_lowercase(); - Ok(items.into_iter().find(|i| same(i["name"].as_str().unwrap_or(""), name) && (kind == "artist" || artist.is_none_or(|a| same(i["artist"]["name"].as_str().unwrap_or(""), a)))).map(|i| (i["playcount"].as_u64().unwrap_or(0), i))) + let by_name = || items.iter().position(|i| same(i["name"].as_str().unwrap_or(""), name) && (kind == "artist" || artist.is_none_or(|a| same(i["artist"]["name"].as_str().unwrap_or(""), a)))); + Ok(by_id.or_else(by_name).map(|n| (items[n]["playcount"].as_u64().unwrap_or(0), items[n].clone()))) } /// (artist, title) of the most popular song with that title. Deezer's search (free, no key) ranks by popularity @@ -213,16 +217,18 @@ fn listen(l: &Value, playing: bool) -> Value { let m = &l["track_metadata"]; let map = &m["mbid_mapping"]; let (artist, title) = (m["artist_name"].as_str().unwrap_or(""), m["track_name"].as_str().unwrap_or("")); + let tags = &m["additional_info"]; + // the player's own tags first (exact), then ListenBrainz's match (a guess from the names) + let id = |key: &str| tags[key].as_str().or(map[key].as_str()).unwrap_or(""); + let artist_id = tags["artist_mbids"].get(0).or(map["artist_mbids"].get(0)).and_then(Value::as_str).unwrap_or(""); let mut t = json!({ + "type": "track", "name": title, "artist": {"#text": artist}, "album": {"#text": m["release_name"].as_str().unwrap_or("")}, - "image": image_list(cover(map["caa_release_mbid"].as_str(), map["caa_id"].as_u64(), 500).or_else(|| { - // not matched yet (often the case for what's playing now), but the player sent the release - let release = m["additional_info"]["release_mbid"].as_str().filter(|r| r.len() == 36 && r.chars().all(|c| c.is_ascii_hexdigit() || c == '-'))?; - Some(format!("https://coverartarchive.org/release/{release}/front-500")) - })), + "image": image_list(cover(map["caa_release_mbid"].as_str(), map["caa_id"].as_u64(), 500)), "url": fm_url(&[artist, "_", title]), + "mbids": {"release": id("release_mbid"), "release_group": id("release_group_mbid"), "recording": id("recording_mbid"), "artist": artist_id}, }); if playing { t["@attr"] = json!({"nowplaying": "true"}); @@ -245,12 +251,16 @@ fn top_item(kind: &str, i: &Value) -> Value { "albums" => fm_url(&[artist, name]), _ => fm_url(&[artist, "_", name]), }; + let artist_id = i["artist_mbid"].as_str().or(i["artist_mbids"].get(0).and_then(Value::as_str)).unwrap_or(""); json!({ + "type": &kind[..kind.len() - 1], "name": name, "artist": {"name": artist}, + "album": {"#text": i["release_name"].as_str().unwrap_or(if kind == "albums" { name } else { "" })}, "playcount": i["listen_count"].as_u64().unwrap_or(0), "image": image_list(cover(i["caa_release_mbid"].as_str(), i["caa_id"].as_u64(), 500)), "url": url, + "mbids": {"release": i["release_mbid"].as_str().or(i["caa_release_mbid"].as_str()).unwrap_or(""), "release_group": i["release_group_mbid"].as_str().unwrap_or(""), "recording": i["recording_mbid"].as_str().unwrap_or(""), "artist": artist_id}, }) } @@ -352,6 +362,8 @@ mod tests { assert_eq!(t["date"]["uts"].as_str(), Some("1771414109")); assert!(best_image(&t["image"]).unwrap().ends_with("mbid-f1418001-7f1e-46af-bfdb-95faeded8841-32916450708_thumb500.jpg")); assert_eq!(track_from_url(t["url"].as_str().unwrap()), Some(("Röyksopp".into(), "Some Resolve".into()))); + let tagged = listen(&json!({"track_metadata": {"artist_name": "A", "track_name": "B", "additional_info": {"release_mbid": "tag-release", "artist_mbids": ["tag-artist"]}, "mbid_mapping": {"release_mbid": "guessed", "recording_mbid": "rec"}}}), false); + assert_eq!((tagged["mbids"]["release"].as_str(), tagged["mbids"]["recording"].as_str(), tagged["mbids"]["artist"].as_str()), (Some("tag-release"), Some("rec"), Some("tag-artist")), "tags win, the match fills gaps"); let now = listen(&json!({"track_metadata": {"artist_name": "A", "track_name": "B"}}), true); assert_eq!((now["@attr"]["nowplaying"].as_str(), best_image(&now["image"])), (Some("true"), None)); let album = top_item("albums", &json!({"artist_name": "Pretty Lights", "release_group_name": "Filling Up the City Skies", "listen_count": 1699})); @@ -375,7 +387,9 @@ mod tests { let recent = api.recent("rob", 3).await.expect("recent"); assert!(!recent.is_empty()); let first = &top[0]; - let found = api.plays("rob", "album", first["name"].as_str().unwrap(), first["artist"]["name"].as_str()).await.expect("plays"); + let found = api.plays("rob", "album", first["name"].as_str().unwrap(), first["artist"]["name"].as_str(), None).await.expect("plays"); + let by_id = api.plays("rob", "album", "a name that does not match", None, first["mbids"]["release_group"].as_str()).await.expect("plays by id"); + assert_eq!(by_id.map(|f| f.0), first["playcount"].as_u64(), "the ID wins over the name"); assert_eq!(found.map(|f| f.0), first["playcount"].as_u64()); assert!(matches!(api.user_info("this-user-does-not-exist-9z8y7x").await, Err(Error::NotFound(_)))); let (artist, title) = api.search_track("Get Lucky").await.expect("deezer search"); diff --git a/src/commands/lastfm/covers.rs b/src/commands/lastfm/covers.rs new file mode 100644 index 0000000..2a681bb --- /dev/null +++ b/src/commands/lastfm/covers.rs @@ -0,0 +1,263 @@ +//! Album covers, artist photos and missing album names, from the most exact source down to the broadest. +//! +//! Cover: the release in the player's own tags (Cover Art Archive) → ListenBrainz's match → any edition of the album +//! (CAA release group) → Deezer → iTunes. MusicBrainz's art is exact but has holes (unmatched listens, releases nobody +//! uploaded art for); Deezer and iTunes have label-supplied art for nearly every commercial release, found by name, +//! so their results are only used when the artist and title match. +//! Artist photo: Deezer → MusicBrainz → Wikimedia Commons. +use super::api::{best_image, MB_AGENT}; +use super::normalise_title; +use crate::state::State; +use serde_json::Value; +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::sync::Semaphore; + +/// A found picture is remembered for a day: covers don't change, and every lookup costs time on the slow line. +const FOUND_TTL: u64 = 86400; +/// A miss is retried after an hour: ListenBrainz may match the listen or someone may upload art meanwhile. +const MISSING_TTL: u64 = 3600; +const TIMEOUT: Duration = Duration::from_secs(8); + +fn memo() -> &'static Mutex)>> { + static M: OnceLock)>>> = OnceLock::new(); + M.get_or_init(Default::default) +} + +async fn remembered(key: String, find: impl std::future::Future>) -> Option { + if let Some((until, v)) = memo().lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + if *until > Instant::now() { + return v.clone(); + } + } + let found = find.await; + let mut m = memo().lock().unwrap_or_else(|e| e.into_inner()); + if m.len() > 5000 { + let now = Instant::now(); + m.retain(|_, v| v.0 > now); + } + m.insert(key, (Instant::now() + Duration::from_secs(if found.is_some() { FOUND_TTL } else { MISSING_TTL }), found.clone())); + found +} + +fn is_mbid(s: &str) -> bool { + s.len() == 36 && s.chars().all(|c| c.is_ascii_hexdigit() || c == '-') +} + +/// Names compared the forgiving way: case, brackets ("(Remastered)") and punctuation don't count. +fn same_title(a: &str, b: &str) -> bool { + let (x, y) = (normalise_title(a), normalise_title(b)); + !x.is_empty() && x == y +} + +/// Artist credits differ between services ("Daron Malakian and Scars On Broadway" vs "Scars on Broadway"): one +/// containing the other counts. +fn same_artist(a: &str, b: &str) -> bool { + let (x, y) = (normalise_title(a), normalise_title(b)); + !x.is_empty() && !y.is_empty() && (x.contains(&y) || y.contains(&x)) +} + +async fn json(state: &State, url: &str, query: &[(&str, &str)]) -> Option { + let r = state.web.get(url).query(query).header(reqwest::header::USER_AGENT, MB_AGENT).timeout(TIMEOUT).send().await.ok()?; + r.status().is_success().then_some(())?; + r.json().await.ok() +} + +/// The front cover of a CAA release or release group, if it has one. One HEAD request: CAA answers 404 or redirects +/// to the image, and that redirect target is the URL (saves the hop on every later download). +async fn caa(kind: &str, mbid: &str) -> Option { + if !is_mbid(mbid) { + return None; + } + static CLIENT: OnceLock = OnceLock::new(); + let client = CLIENT.get_or_init(|| reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).user_agent(MB_AGENT).timeout(TIMEOUT).build().expect("http client")); + let url = format!("https://coverartarchive.org/{kind}/{mbid}/front-500"); + let r = client.head(&url).send().await.ok()?; + if r.status().is_success() { + return Some(url); + } + r.status().is_redirection().then_some(())?; + r.headers().get(reqwest::header::LOCATION)?.to_str().ok().filter(|l| l.starts_with("https://")).map(str::to_string) +} + +/// (album title, cover) from Deezer: the album when it's known, otherwise the track's album. +async fn deezer(state: &State, artist: &str, album: Option<&str>, track: Option<&str>) -> Option<(String, String)> { + let clean = |s: &str| s.replace('"', " "); + let (path, q) = match (album, track) { + (Some(al), _) => ("album", format!("artist:\"{}\" album:\"{}\"", clean(artist), clean(al))), + (None, Some(t)) => ("track", format!("artist:\"{}\" track:\"{}\"", clean(artist), clean(t))), + _ => return None, + }; + let d = json(state, &format!("https://api.deezer.com/search/{path}"), &[("q", &q), ("limit", "5")]).await?; + d["data"].as_array()?.iter().find_map(|hit| { + let (title, album_of) = if path == "album" { (album?, hit) } else { (track?, &hit["album"]) }; + let found = hit["title"].as_str()?; + (same_artist(hit["artist"]["name"].as_str()?, artist) && same_title(found, title)).then_some(())?; + Some((album_of["title"].as_str()?.to_string(), album_of["cover_big"].as_str().filter(|c| !c.is_empty())?.to_string())) + }) +} + +/// A cover from the iTunes Search API (free, no key; fewer requests allowed than Deezer, so it's the last resort). +async fn itunes(state: &State, artist: &str, album: Option<&str>, track: Option<&str>) -> Option { + let (entity, title) = match (album, track) { + (Some(al), _) => ("album", al), + (None, Some(t)) => ("song", t), + _ => return None, + }; + let term = format!("{artist} {title}"); + let d = json(state, "https://itunes.apple.com/search", &[("term", &term), ("entity", entity), ("media", "music"), ("limit", "5")]).await?; + d["results"].as_array()?.iter().find_map(|hit| { + let found = if entity == "album" { hit["collectionName"].as_str()? } else { hit["trackName"].as_str()? }; + (same_artist(hit["artistName"].as_str()?, artist) && same_title(found, title)).then_some(())?; + Some(hit["artworkUrl100"].as_str()?.replace("100x100bb", "600x600bb")) + }) +} + +/// The best cover for a track or album item from `api` (it carries the names, ListenBrainz's picture and the +/// MusicBrainz IDs from the player's tags). +pub async fn cover(state: &State, item: &Value) -> Option { + let artist = item["artist"]["name"].as_str().or(item["artist"]["#text"].as_str()).unwrap_or("").to_string(); + let is_album = item["type"].as_str() == Some("album"); + let album = if is_album { item["name"].as_str() } else { item["album"]["#text"].as_str() }.filter(|a| !a.is_empty()).map(str::to_string); + let track = (!is_album).then(|| item["name"].as_str().unwrap_or("").to_string()).filter(|t| !t.is_empty()); + let ids = &item["mbids"]; + let (release, group) = (ids["release"].as_str().unwrap_or("").to_string(), ids["release_group"].as_str().unwrap_or("").to_string()); + let known = best_image(&item["image"]); + let key = format!("cover|{}|{}|{}|{release}", artist.to_lowercase(), album.as_deref().unwrap_or("").to_lowercase(), track.as_deref().unwrap_or("").to_lowercase()); + remembered(key, async move { + if !release.is_empty() { + if known.as_deref().is_some_and(|k| k.contains(&release)) { + return known; + } + if let Some(u) = caa("release", &release).await { + return Some(u); + } + } + if known.is_some() { + return known; + } + if let Some(u) = caa("release-group", &group).await { + return Some(u); + } + if artist.is_empty() { + return None; + } + if let Some((_, u)) = deezer(state, &artist, album.as_deref(), track.as_deref()).await { + return Some(u); + } + // a track's album name may be missing or spelled differently: try the track itself on Deezer too + if let (Some(_), Some(t)) = (&album, &track) { + if let Some((_, u)) = deezer(state, &artist, None, Some(t)).await { + return Some(u); + } + } + itunes(state, &artist, album.as_deref(), track.as_deref()).await + }) + .await +} + +/// The album a track is on, when the listen didn't say (some players send no album). +pub async fn album_name(state: &State, artist: &str, track: &str) -> Option { + remembered(format!("album|{}|{}", artist.to_lowercase(), track.to_lowercase()), async { Some(deezer(state, artist, None, Some(track)).await?.0) }).await +} + +/// A photo of the artist. `mbid` (from the player's tags or ListenBrainz) skips the MusicBrainz name search. +pub async fn artist_photo(state: &State, artist: &str, mbid: Option<&str>) -> Option { + let mbid = mbid.filter(|m| is_mbid(m)).map(str::to_string); + remembered(format!("artist|{}", artist.to_lowercase()), async move { + if let Some(d) = json(state, "https://api.deezer.com/search/artist", &[("q", artist), ("limit", "5")]).await { + // an artist without a photo has an empty picture hash: ".../images/artist//500x500-..." + let photo = d["data"].as_array().into_iter().flatten().find_map(|a| { + same_title(a["name"].as_str()?, artist).then_some(())?; + a["picture_big"].as_str().filter(|p| !p.is_empty() && !p.contains("/artist//")).map(str::to_string) + }); + if photo.is_some() { + return photo; + } + } + commons_photo(state, artist, mbid.as_deref()).await + }) + .await +} + +/// MusicBrainz's "image" link for the artist → its Wikimedia Commons thumbnail. +async fn commons_photo(state: &State, artist: &str, mbid: Option<&str>) -> Option { + static SLOT: Semaphore = Semaphore::const_new(1); // MusicBrainz allows 1 request/second + let _s = SLOT.acquire().await.ok()?; + let id = match mbid { + Some(m) => m.to_string(), + None => { + let found = json(state, "https://musicbrainz.org/ws/2/artist/", &[("query", &format!("artist:\"{}\"", artist.replace('"', " "))), ("fmt", "json"), ("limit", "1")]).await?; + let first = found["artists"].get(0)?; + (first["score"].as_i64().unwrap_or(0) >= 90).then_some(())?; + tokio::time::sleep(Duration::from_secs(1)).await; + first["id"].as_str()?.to_string() + } + }; + let rel = json(state, &format!("https://musicbrainz.org/ws/2/artist/{id}"), &[("inc", "url-rels"), ("fmt", "json")]).await?; + let commons = rel["relations"].as_array()?.iter().find_map(|r| { + let res = r["url"]["resource"].as_str()?; + (r["type"].as_str() == Some("image") && res.contains("commons.wikimedia.org/wiki/File:")).then(|| res.to_string()) + })?; + let title = commons.rsplit('/').next()?.to_string(); + let pages = json(state, "https://commons.wikimedia.org/w/api.php", &[("action", "query"), ("titles", &title), ("prop", "imageinfo"), ("iiprop", "url"), ("iiurlwidth", "300"), ("format", "json")]).await?; + pages["query"]["pages"].as_object()?.values().find_map(|p| { + let i = p["imageinfo"].get(0)?; + i["thumburl"].as_str().or_else(|| i["url"].as_str()).map(str::to_string) + }) +} + +/// The same picture at about 250 px, for the small tiles of a big chart (fewer bytes on the slow line). +pub fn small(url: &str) -> String { + url.replace("_thumb500.jpg", "_thumb250.jpg").replace("/front-500", "/front-250").replace("/500x500-", "/250x250-").replace("600x600bb", "300x300bb") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_match_across_services() { + assert!(same_title("Get Lucky (Radio Edit - feat. Pharrell Williams)", "Get Lucky")); + assert!(!same_title("Dictator", "Scars on Broadway")); + assert!(same_artist("Daron Malakian and Scars On Broadway", "Scars on Broadway")); + assert!(!same_artist("", "Anyone")); + assert!(is_mbid("dda07cd4-efaa-400a-8151-08c29729604a") && !is_mbid("../../etc")); + } + + #[test] + fn small_pictures() { + assert_eq!(small("https://archive.org/download/mbid-x/mbid-x-1_thumb500.jpg"), "https://archive.org/download/mbid-x/mbid-x-1_thumb250.jpg"); + assert_eq!(small("https://cdn-images.dzcdn.net/images/cover/abc/500x500-000000-80-0-0.jpg"), "https://cdn-images.dzcdn.net/images/cover/abc/250x250-000000-80-0-0.jpg"); + assert_eq!(small("https://is1-ssl.mzstatic.com/a/600x600bb.jpg"), "https://is1-ssl.mzstatic.com/a/300x300bb.jpg"); + } + + fn state() -> State { + let _ = rustls::crypto::ring::default_provider().install_default(); + State::new(std::sync::Arc::new(twilight_http::Client::new("x".into())), crate::cmd::Registry::new(vec![]), "x".into()) + } + + /// `cargo test covers_live -- --ignored --nocapture` + #[tokio::test] + #[ignore = "needs the internet"] + async fn covers_live_fall_back_in_order() { + let s = state(); + // tagged release with art → Cover Art Archive + let tagged = serde_json::json!({"type": "track", "name": "x", "artist": {"#text": "Pretty Lights"}, "album": {"#text": ""}, "image": [], "mbids": {"release": "dda07cd4-efaa-400a-8151-08c29729604a"}}); + let u = cover(&s, &tagged).await.expect("CAA by tag"); + println!("tag: {u}"); + assert!(u.contains("archive.org")); + // no IDs, no art → Deezer by name + let named = serde_json::json!({"type": "track", "name": "Till the End", "artist": {"#text": "Daron Malakian and Scars On Broadway"}, "album": {"#text": "Dictator"}, "image": []}); + let u = cover(&s, &named).await.expect("Deezer by name"); + println!("name: {u}"); + assert!(u.contains("dzcdn")); + assert_eq!(album_name(&s, "Daft Punk", "Get Lucky").await.is_some(), true); + let photo = artist_photo(&s, "Wax Tailor", None).await.expect("artist photo"); + println!("photo: {photo}"); + assert!(itunes(&s, "Daft Punk", Some("Random Access Memories"), None).await.is_some_and(|u| u.contains("600x600"))); + // iTunes doesn't sell "Dictator" and answers with their other album: that must not be taken + assert_eq!(itunes(&s, "Daron Malakian and Scars On Broadway", Some("Dictator"), None).await, None); + } +} diff --git a/src/commands/lastfm/extras.rs b/src/commands/lastfm/extras.rs index 9e65c20..b594d2d 100644 --- a/src/commands/lastfm/extras.rs +++ b/src/commands/lastfm/extras.rs @@ -1,6 +1,7 @@ //! Who Knows, album charts, Pixel Jumble, lyrics, the Listen button and the pictures they need. use super::super::games::{btn, Game, Rendered, Reply, LOSE}; -use super::api::{all_links, best_image, fm_url, linked, track_from_url, Lb, MB_AGENT}; +use super::api::{all_links, fm_url, linked, track_from_url, Lb}; +use super::covers; use super::{link, normalise_title, period_label, period_of}; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::pix; @@ -43,66 +44,28 @@ pub async fn fetch_image(state: &State, url: &str) -> Option> { Some(data) } -/// Artist photos come from MusicBrainz → Wikimedia Commons (ListenBrainz and Last.fm have none). -pub async fn artist_image(state: &State, artist: &str) -> Option { - static CACHE: OnceLock)>>> = OnceLock::new(); - static SLOT: Semaphore = Semaphore::const_new(1); // MusicBrainz allows 1 request/second - let cache = CACHE.get_or_init(Default::default); - let key = artist.to_lowercase(); - if let Some((until, v)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { - if *until > Instant::now() { - return v.clone(); - } - } - let image = async { - let _s = SLOT.acquire().await.ok()?; - let get = |url: String, q: Vec<(&'static str, String)>| { - let web = state.web.clone(); - async move { web.get(url).query(&q).header(reqwest::header::USER_AGENT, MB_AGENT).timeout(Duration::from_secs(8)).send().await.ok()?.json::().await.ok() } - }; - let found = get("https://musicbrainz.org/ws/2/artist/".into(), vec![("query", format!("artist:\"{artist}\"")), ("fmt", "json".into()), ("limit", "1".into())]).await?; - let first = found["artists"].get(0)?; - if first["score"].as_i64().unwrap_or(0) < 90 { - return None; - } - tokio::time::sleep(Duration::from_secs(1)).await; - let rel = get(format!("https://musicbrainz.org/ws/2/artist/{}", first["id"].as_str()?), vec![("inc", "url-rels".into()), ("fmt", "json".into())]).await?; - let commons = rel["relations"].as_array()?.iter().find_map(|r| { - let res = r["url"]["resource"].as_str()?; - (r["type"].as_str() == Some("image") && res.contains("commons.wikimedia.org/wiki/File:")).then(|| res.to_string()) - })?; - let pages = get("https://commons.wikimedia.org/w/api.php".into(), vec![("action", "query".into()), ("titles", commons.rsplit('/').next()?.to_string()), ("prop", "imageinfo".into()), ("iiprop", "url".into()), ("iiurlwidth", "300".into()), ("format", "json".into())]).await?; - pages["query"]["pages"].as_object()?.values().find_map(|p| { - let i = p["imageinfo"].get(0)?; - i["thumburl"].as_str().or_else(|| i["url"].as_str()).map(str::to_string) - }) - } - .await; - cache.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (Instant::now() + Duration::from_secs(86400), image.clone())); - image -} - -/// Picture for a top-list's #1: the album cover, or the artist's photo. +/// Picture for a top-list's #1: the cover of an album or track, the photo of an artist (or of a track's artist when +/// no cover turns up). pub async fn cover_for(state: &State, kind: &str, item: &Value) -> Option { - if kind == "albums" { - if let Some(i) = best_image(&item["image"]) { - return Some(i); + if kind != "artists" { + if let Some(c) = covers::cover(state, item).await { + return Some(c); } } let artist = if kind == "artists" { item["name"].as_str() } else { item["artist"]["name"].as_str() }?; - artist_image(state, artist).await + covers::artist_photo(state, artist, item["mbids"]["artist"].as_str()).await } // ---- who knows ---------------------------------------------------------------------------------------------------------------- -async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist: Option<&str>) -> (Component, Option>) { +async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist: Option<&str>, mbid: Option<&str>) -> (Component, Option>) { let guild = ctx.guild_id.unwrap(); let members: Vec<(u64, String)> = all_links().into_iter().filter(|(u, _)| twilight_model::id::Id::new_checked(*u).is_some_and(|id| ctx.state.cache.member(guild, id).is_some())).collect(); if members.is_empty() { return (Card::new(Some(RED)).text("### ❌ No linked accounts\nNo one in this server has linked ListenBrainz yet.").build(), None); } let results = futures::future::join_all(members.iter().map(|(u, un)| async move { - match api.plays(un, kind, name, artist).await { + match api.plays(un, kind, name, artist, mbid).await { Ok(Some((n, item))) => (*u, n, Some(item)), _ => (*u, 0, None), } @@ -111,15 +74,15 @@ async fn whoknows_card(ctx: &Ctx, api: &Arc, kind: &str, name: &str, artist: // the name as the listeners' stats spell it; nobody here played it → the name as asked let entity = results.iter().find_map(|r| r.2.clone()).unwrap_or_else(|| { let url = match (kind, artist) { ("artist", _) | (_, None) => fm_url(&[name]), ("album", Some(a)) => fm_url(&[a, name]), (_, Some(a)) => fm_url(&[a, "_", name]) }; - serde_json::json!({"name": name, "artist": {"name": artist}, "url": url}) + serde_json::json!({"type": kind, "name": name, "artist": {"name": artist}, "url": url}) }); let mut listeners: Vec<(u64, u64)> = results.iter().filter(|r| r.1 > 0).map(|r| (r.0, r.1)).collect(); listeners.sort_by_key(|l| std::cmp::Reverse(l.1)); let display = entity["name"].as_str().unwrap_or(name).to_string(); let entity_artist = if kind != "artist" { entity["artist"]["name"].as_str().or(artist).map(str::to_string) } else { None }; let image = match kind { - "artist" => artist_image(&ctx.state, &display).await, - _ => best_image(&entity["image"]), + "artist" => covers::artist_photo(&ctx.state, &display, entity["mbids"]["artist"].as_str().or(mbid)).await, + _ => covers::cover(&ctx.state, &entity).await, }; let guild_name = ctx.state.cache.guild(guild).map(|g| g.name().to_string()).unwrap_or_default(); let accent = colors::accent(&ctx.state, image.as_deref(), GREEN).await; @@ -155,7 +118,7 @@ async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result let api = super::lfm(&ctx.state); ctx.defer().await?; let username = linked(ctx.user_id.get()); - let (mut name, mut artist): (Option, Option) = (None, None); + let (mut name, mut artist, mut mbid): (Option, Option, Option) = (None, None, None); match query.map(str::trim).filter(|q| !q.is_empty()) { Some(q) if kind == "artist" => name = Some(q.to_string()), Some(q) if q.contains(" - ") => { @@ -166,6 +129,9 @@ async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result if let Some(u) = &username { if let Some(track) = api.recent(u, 1).await.ok().and_then(|t| t.into_iter().next()) { artist = track["artist"]["#text"].as_str().map(str::to_string); + // what they're playing, by its ID from their tags (only when no name was typed) + let id = match kind { "artist" => "artist", "album" => "release_group", _ => "recording" }; + mbid = q.is_none().then(|| track["mbids"][id].as_str().filter(|m| !m.is_empty()).map(str::to_string)).flatten(); name = match kind { "artist" => artist.clone(), "track" => q.map(str::to_string).or_else(|| track["name"].as_str().map(str::to_string)), @@ -182,7 +148,7 @@ async fn run_whoknows(ctx: &Arc, kind: &str, query: Option<&str>) -> Result let example = match kind { "artist" => "Artist", "track" => "Artist - Track", _ => "Artist - Album" }; return super::error(ctx, &format!("Tell me what to look up (`{example}`) or play something first.")).await; }; - match whoknows_card(ctx, &api, kind, &n, artist.as_deref()).await { + match whoknows_card(ctx, &api, kind, &n, artist.as_deref(), mbid.as_deref()).await { (card, Some(picture)) => ctx.reply_file(card, super::art::FILE, picture).await, (card, None) => ctx.reply(card).await, } @@ -276,17 +242,21 @@ async fn chart(ctx: Arc) -> Result<()> { let slots = Arc::new(Semaphore::new(8)); let covers: Vec>> = futures::future::join_all(albums.iter().map(|a| { let (state, slots) = (ctx.state.clone(), slots.clone()); - let url = best_image(&a["image"]).map(|u| if cell <= 250 { u.replace("_thumb500.jpg", "_thumb250.jpg") } else { u }); + let album = a.clone(); async move { let _p = slots.acquire().await.ok()?; - fetch_image(&state, &url?).await + let url = covers::cover(&state, &album).await?; + fetch_image(&state, &if cell <= 250 { covers::small(&url) } else { url }).await } })) .await; let (albums2, covers2) = (albums.clone(), covers.clone()); let (bytes, name) = tokio::task::spawn_blocking(move || compose_chart(&covers2, &albums2, rows, cols)).await?; let plays: u64 = albums.iter().map(|a| a["playcount"].as_u64().unwrap_or(0)).sum(); - let first = covers.iter().position(Option::is_some).and_then(|i| best_image(&albums[i]["image"])); + let first = match covers.iter().position(Option::is_some) { + Some(i) => covers::cover(&ctx.state, &albums[i]).await, // remembered from the chart, no new lookup + None => None, + }; let accent = colors::accent(&ctx.state, first.as_deref(), GREEN).await; let card = Card::new(Some(accent)).text(&format!("### 📊 {} album chart · {}\n-# {rows}x{cols} · {} albums · {} plays", period_label(period), escape(&username), albums.len(), crate::converters::thousands(plays))).gallery(&[&format!("attachment://{name}")]).build(); ctx.reply_file(card, name, bytes).await @@ -346,6 +316,8 @@ pub struct Pixel { } const MAX_LEVEL: u32 = 5; +/// Albums tried for a cover before Pixel Jumble gives up (each miss can cost a few lookups). +const PIXEL_TRIES: usize = 8; impl Pixel { fn answer_text(&self) -> String { @@ -453,15 +425,24 @@ async fn pixel(ctx: Arc) -> Result<()> { let mut albums = Vec::new(); for period in ["7day", "1month", "overall"] { // fall back when they were quiet this week albums = match api.top(&username, "albums", period, 100).await { - Ok(a) => a.into_iter().filter(|a| best_image(&a["image"]).is_some()).collect(), + Ok(a) => a, Err(e) => return super::error(&ctx, &e.to_string()).await, }; if albums.len() >= 3 { break; } } - let Some(album) = albums.choose(&mut rand::rng()).cloned() else { return super::error(&ctx, "Couldn't find any albums with cover art in your history.").await }; - let Some(cover) = async { pix::decode(&fetch_image(&ctx.state, &best_image(&album["image"])?).await?) }.await else { return super::error(&ctx, "Couldn't download the album cover — try again.").await }; + // random albums until one has a cover that downloads + let mut picked = None; + let tries: Vec = albums.sample(&mut rand::rng(), PIXEL_TRIES).cloned().collect(); + for album in &tries { + let Some(url) = covers::cover(&ctx.state, album).await else { continue }; + if let Some(img) = fetch_image(&ctx.state, &url).await.as_deref().and_then(pix::decode) { + picked = Some((album.clone(), img)); + break; + } + } + let Some((album, cover)) = picked else { return super::error(&ctx, "Couldn't find any albums with cover art in your history.").await }; let game = Pixel { owner: ctx.user_id.get(), album: album["name"].as_str().unwrap_or("?").into(), artist: album["artist"]["name"].as_str().unwrap_or("?").into(), url: album["url"].as_str().map(str::to_string), cover, level: 1, started: Instant::now(), result: None }; super::super::games::launch(&ctx, Box::new(game), None).await } @@ -551,7 +532,7 @@ async fn lyrics(ctx: Arc) -> Result<()> { let Some(track) = track else { return super::error(&ctx, "You haven't listened to anything yet — give me a song (`Artist - Title`).").await }; artist = track["artist"]["#text"].as_str().map(str::to_string); title = track["name"].as_str().unwrap_or("").to_string(); - cover = best_image(&track["image"]); + cover = covers::cover(&ctx.state, &track).await; } } let Some((text, artist, title)) = fetch_lyrics(&ctx.state, artist.as_deref(), &title).await else { diff --git a/src/commands/lastfm/mod.rs b/src/commands/lastfm/mod.rs index 4b74705..97112b7 100644 --- a/src/commands/lastfm/mod.rs +++ b/src/commands/lastfm/mod.rs @@ -11,6 +11,7 @@ mod api; mod extras; mod art; +mod covers; mod views; use self::api::{as_list, best_image, fm_url, Lb}; diff --git a/src/commands/lastfm/views.rs b/src/commands/lastfm/views.rs index 1de1b2f..176b867 100644 --- a/src/commands/lastfm/views.rs +++ b/src/commands/lastfm/views.rs @@ -54,10 +54,22 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option>), Error let title = track["name"].as_str().unwrap_or("Unknown track"); let album = track["album"]["#text"].as_str().filter(|a| !a.is_empty()); let playing = track["@attr"]["nowplaying"].as_str() == Some("true"); - let found = b.api.plays(&b.username, "track", title, Some(artist)).await.ok().flatten(); + let found = b.api.plays(&b.username, "track", title, Some(artist), track["mbids"]["recording"].as_str()).await.ok().flatten(); let plays = found.as_ref().map(|p| p.0).filter(|p| *p > 0); - // what's playing now often isn't matched to MusicBrainz yet; their stats for the same track have the cover - let cover = best_image(&track["image"]).or_else(|| best_image(&found?.1["image"])); + // some players send no album; Deezer knows which one the track is on + let looked_up = match album { + None => super::covers::album_name(&b.state, artist, title).await, + Some(_) => None, + }; + let album = album.or(looked_up.as_deref()); + let cover = match super::covers::cover(&b.state, track).await { + Some(c) => Some(c), + // their stats for the same track may carry a cover the listen doesn't + None => match &found { + Some((_, item)) => super::covers::cover(&b.state, item).await, + None => None, + }, + }; let accent = colors::accent(&b.state, cover.as_deref(), GREEN).await; let art_image = match &cover { Some(url) => match crate::commands::media::fetch_limited(&b.state, url, 4 * 1024 * 1024).await { @@ -226,6 +238,7 @@ impl Game for Top { pub struct Recent { b: Base, tracks: Vec, + cover: Option, scrobbles: u64, accent: u32, page: usize, @@ -236,9 +249,12 @@ impl Recent { pub async fn load(b: Base) -> Result { let (tracks, info) = tokio::join!(b.api.recent(&b.username, 50), b.api.user_info(&b.username)); let tracks: Vec = tracks?.into_iter().take(50).collect(); - let cover = tracks.first().and_then(|t| best_image(&t["image"])); + let cover = match tracks.first() { + Some(t) => super::covers::cover(&b.state, t).await, + None => None, + }; let accent = colors::accent(&b.state, cover.as_deref().or(Some(&b.avatar)), GREEN).await; - Ok(Self { scrobbles: num(&info?, "playcount"), b, tracks, accent, page: 0, over: false }) + Ok(Self { scrobbles: num(&info?, "playcount"), b, tracks, cover, accent, page: 0, over: false }) } fn pages(&self) -> usize { @@ -272,7 +288,7 @@ impl Game for Recent { } } }).collect(); - let cover = self.tracks.first().and_then(|t| best_image(&t["image"])); + let cover = &self.cover; let mut buttons = nav(t, self.page, self.pages()); buttons.push(go(t, "top", "Top", "🏆")); buttons.push(go(t, "profile", "Profile", "👤")); diff --git a/web/site/privacy.html b/web/site/privacy.html index 9a85a8f..85bd250 100644 --- a/web/site/privacy.html +++ b/web/site/privacy.html @@ -31,7 +31,7 @@

2. Services Dezio talks to

-

To do what you ask, Dezio sends the needed parts of your request to: Discord; OpenRouter (AI replies — the last few messages of a conversation are kept in memory for about 20 minutes); ListenBrainz, MusicBrainz, the Cover Art Archive, Wikimedia Commons and Deezer (song search for lyrics); the sites you play or download from; VirusTotal (links and files you ask it to scan); Google Translate and MyMemory (text you translate); Open-Meteo (weather); DuckDuckGo, Bing, Openverse, Zenserp, Wikipedia, dictionary and Urban Dictionary APIs (searches); TBIB and Xbooru (age-restricted image searches); and GIF and animal picture APIs.

+

To do what you ask, Dezio sends the needed parts of your request to: Discord; OpenRouter (AI replies — the last few messages of a conversation are kept in memory for about 20 minutes); ListenBrainz, MusicBrainz, the Cover Art Archive, Wikimedia Commons, Deezer and iTunes (album covers, artist photos and song search); the sites you play or download from; VirusTotal (links and files you ask it to scan); Google Translate and MyMemory (text you translate); Open-Meteo (weather); DuckDuckGo, Bing, Openverse, Zenserp, Wikipedia, dictionary and Urban Dictionary APIs (searches); TBIB and Xbooru (age-restricted image searches); and GIF and animal picture APIs.

3. What Dezio doesn't do

Dezio doesn't sell your data or use it for advertising, and doesn't read messages beyond what its features need (commands, mentions, logging, snipe and automatic channel features that servers turn on).