From 6430c1ffc11f0d533c421c95e3e69b7c55f2f3b7 Mon Sep 17 00:00:00 2001 From: Christian Date: Fri, 20 Nov 2026 17:25:42 -0500 Subject: [PATCH] Album covers, logos and descriptions from the web - Search online from an album's Edit dialog: covers from TheAudioDB, Deezer, Apple Music and the Cover Art Archive, logos from Wikidata, Wikimedia Commons and the artist's TheAudioDB logo, and a Wikipedia page for the description - Album pages show the logo and an About section, looked up automatically when "Find artist and album info" is on - Your own logo file and About text, kept in albums.json - Clean no longer deletes artist or album logos; backups include them - Artist pages credit the real bio source - Home shelves show exactly one row instead of peeking into a second - Window buttons use the native Windows icon font so they stay sharp at any display scale - Web requests identify Atmosphere with its repo link --- src/albuminfo.rs | 388 ++++++++++++++++++++++++++++++++++++++++++++++ src/artistinfo.rs | 22 ++- src/backup.rs | 35 +++-- src/libcmd.rs | 78 ++++++++++ src/library.rs | 94 +++++++++++ src/main.rs | 10 +- src/storage.rs | 8 +- ui/app.js | 4 +- ui/index.html | 8 +- ui/library.js | 148 ++++++++++++++++-- ui/styles.css | 33 +++- 11 files changed, 792 insertions(+), 36 deletions(-) create mode 100644 src/albuminfo.rs diff --git a/src/albuminfo.rs b/src/albuminfo.rs new file mode 100644 index 0000000..3bd55ca --- /dev/null +++ b/src/albuminfo.rs @@ -0,0 +1,388 @@ +// atmosphere · albuminfo.rs · Finds album covers, descriptions and logos from keyless public sources: Deezer, Apple, TheAudioDB, the Cover Art Archive, Wikipedia, Wikidata and Wikimedia Commons +use crate::artistinfo::{audiodb_logo, commons_file, enc, get_bytes, get_json, norm, path_enc, wikidata_file, wikidata_file_name, PageChoice}; +use anyhow::{anyhow, bail, Result}; +use base64::Engine as _; +use regex::Regex; +use serde_json::Value; +use std::sync::LazyLock; + +const AUDIODB: &str = "https://www.theaudiodb.com/api/v1/json/123"; +pub const COVER_EDGE: u32 = 1500; + +#[derive(Default)] +pub struct Found { + pub bio: Option, + pub bio_source: Option, + pub logo: Option>, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CoverChoice { + pub source: String, + pub title: String, + pub artist: String, + pub thumb: String, + pub full: String, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LogoChoice { + pub source: String, + pub name: String, + pub thumb: String, + pub full: String, +} + +static ALBUM: LazyLock = LazyLock::new(|| Regex::new(r"(?i)\b(album|ep|extended play|mixtape|soundtrack|compilation|live recording)\b").unwrap()); + +fn base(s: &str) -> String { + norm(s.split(" (").next().unwrap_or(s).split(" [").next().unwrap_or(s)) +} + +pub fn is_album_description(d: &str, artist: &str) -> bool { + let a = norm(artist); + ALBUM.is_match(d) && (a.is_empty() || a == "variousartists" || norm(d).contains(&a)) +} + +async fn summary(http: &reqwest::Client, key: &str) -> Option<(String, String, Option)> { + let s = get_json(http, &format!("https://en.wikipedia.org/api/rest_v1/page/summary/{}", path_enc(key))).await?; + if s["type"].as_str() != Some("standard") { + return None; + } + let extract = s["extract"].as_str()?.trim().to_string(); + if extract.len() < 40 { + return None; + } + let url = s["content_urls"]["desktop"]["page"].as_str().unwrap_or_default().to_string(); + Some((extract, url, s["wikibase_item"].as_str().map(String::from))) +} + +async fn wikipedia(http: &reqwest::Client, artist: &str, title: &str) -> Option<(String, String, Option)> { + let v = get_json(http, &format!("https://en.wikipedia.org/w/rest.php/v1/search/page?q={}&limit=10", enc(&format!("{title} {artist} album")))).await?; + let want = base(title); + let key = v["pages"] + .as_array()? + .iter() + .filter(|p| p["key"].as_str().is_some_and(|k| base(&k.replace('_', " ")) == want)) + .find(|p| p["description"].as_str().is_some_and(|d| is_album_description(d, artist)))?["key"] + .as_str()? + .to_string(); + summary(http, &key).await +} + +async fn audiodb_album(http: &reqwest::Client, artist: &str, title: &str) -> Option { + let v = get_json(http, &format!("{AUDIODB}/searchalbum.php?s={}&a={}", enc(artist), enc(title))).await?; + let want = base(title); + v["album"].as_array()?.iter().find(|a| a["strAlbum"].as_str().is_some_and(|n| base(n) == want)).cloned() +} + +fn audiodb_bio(a: &Value) -> Option<(String, String)> { + let text = a["strDescriptionEN"].as_str().or(a["strDescription"].as_str())?.trim(); + (text.len() >= 40).then(|| (text.to_string(), format!("https://www.theaudiodb.com/album/{}", a["idAlbum"].as_str().unwrap_or_default()))) +} + +pub async fn find(http: &reqwest::Client, artist: &str, title: &str, want_bio: bool, want_logo: bool) -> Found { + let mut found = Found::default(); + if !want_bio && !want_logo { + return found; + } + let (wiki, adb) = tokio::join!(wikipedia(http, artist, title), async { if want_bio { audiodb_album(http, artist, title).await } else { None } }); + if let Some((bio, url, qid)) = wiki { + if want_bio { + found.bio = Some(bio); + found.bio_source = Some(url); + } + if let (true, Some(q)) = (want_logo, qid) { + found.logo = wikidata_file(http, &q, "P154").await; + } + } + if want_bio && found.bio.is_none() { + if let Some((bio, url)) = adb.as_ref().and_then(audiodb_bio) { + found.bio = Some(bio); + found.bio_source = Some(url); + } + } + found +} + +pub async fn chosen(http: &reqwest::Client, key: &str) -> Found { + let mut found = Found::default(); + if key.is_empty() || key.len() >= 300 || key.contains('/') { + return found; + } + if let Some((bio, url, qid)) = summary(http, key).await { + found.bio = Some(bio); + found.bio_source = Some(url); + if let Some(q) = qid { + found.logo = wikidata_file(http, &q, "P154").await; + } + } + found +} + +pub fn allowed_cover(url: &str) -> bool { + url::Url::parse(url).is_ok_and(|u| { + u.scheme() == "https" + && u.host_str().is_some_and(|h| h.ends_with(".dzcdn.net") || h.ends_with(".mzstatic.com") || h == "theaudiodb.com" || h.ends_with(".theaudiodb.com") || h == "coverartarchive.org") + }) +} + +pub async fn choices(http: &reqwest::Client, query: &str, artist: &str, title: &str) -> (Vec, Vec) { + let q = enc(query); + let deezer = async { + let Some(v) = get_json(http, &format!("https://api.deezer.com/search/album?q={q}&limit=10")).await else { return Vec::new() }; + v["data"] + .as_array() + .map(|list| { + list.iter() + .filter_map(|a| { + let full = a["cover_xl"].as_str().filter(|u| !u.contains("/cover//"))?; + Some(CoverChoice { source: "Deezer".into(), title: a["title"].as_str()?.into(), artist: a["artist"]["name"].as_str().unwrap_or_default().into(), thumb: a["cover_medium"].as_str().unwrap_or(full).into(), full: full.into() }) + }) + .collect() + }) + .unwrap_or_default() + }; + let apple = async { + let Some(v) = get_json(http, &format!("https://itunes.apple.com/search?term={q}&entity=album&limit=10")).await else { return Vec::new() }; + v["results"] + .as_array() + .map(|list| { + list.iter() + .filter_map(|a| { + let art = a["artworkUrl100"].as_str().filter(|u| u.contains("100x100bb"))?; + Some(CoverChoice { source: "Apple Music".into(), title: a["collectionName"].as_str()?.into(), artist: a["artistName"].as_str().unwrap_or_default().into(), thumb: art.replace("100x100bb", "300x300bb"), full: art.replace("100x100bb", &format!("{COVER_EDGE}x{COVER_EDGE}bb")) }) + }) + .collect() + }) + .unwrap_or_default() + }; + let audiodb = async { + let Some(a) = audiodb_album(http, artist, title).await else { return Vec::new() }; + let name = a["strAlbum"].as_str().unwrap_or(title).to_string(); + let by = a["strArtist"].as_str().unwrap_or(artist).to_string(); + let mut out = Vec::new(); + if let Some(u) = a["strAlbumThumb"].as_str().filter(|u| allowed_cover(u)) { + out.push(CoverChoice { source: "TheAudioDB".into(), title: name.clone(), artist: by.clone(), thumb: format!("{u}/preview"), full: u.into() }); + } + if let Some(mb) = a["strMusicBrainzID"].as_str().filter(|m| m.len() == 36 && m.chars().all(|c| c.is_ascii_hexdigit() || c == '-')) { + let root = format!("https://coverartarchive.org/release-group/{mb}"); + out.push(CoverChoice { source: "Cover Art Archive".into(), title: name, artist: by, thumb: format!("{root}/front-250"), full: format!("{root}/front-1200") }); + } + out + }; + let pages = async { + let Some(v) = get_json(http, &format!("https://en.wikipedia.org/w/rest.php/v1/search/page?q={}&limit=8", enc(&format!("{query} album")))).await else { return Vec::new() }; + v["pages"] + .as_array() + .map(|list| { + list.iter() + .filter_map(|p| { + let description = p["description"].as_str().unwrap_or_default().to_string(); + Some(PageChoice { key: p["key"].as_str()?.into(), title: p["title"].as_str()?.into(), music: is_album_description(&description, artist), description }) + }) + .collect::>() + }) + .unwrap_or_default() + }; + let (dz, ap, adb, pages) = tokio::join!(deezer, apple, audiodb, pages); + let mut covers: Vec = adb.into_iter().chain(dz).chain(ap).collect(); + let thumbs = futures_util::future::join_all(covers.iter().map(|c| get_bytes(http, &c.thumb))).await; + for (c, bytes) in covers.iter_mut().zip(thumbs) { + c.thumb = bytes.map(|b| format!("data:{};base64,{}", sniff(&b).unwrap_or("image/jpeg"), base64::engine::general_purpose::STANDARD.encode(b))).unwrap_or_default(); + } + covers.retain(|c| !c.thumb.is_empty()); + (covers, pages) +} + +pub fn allowed_logo(url: &str) -> bool { + crate::artistinfo::allowed_logo(url) || url::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str() == Some("commons.wikimedia.org") && u.path().starts_with("/wiki/Special:FilePath/")) +} + +fn looks_like_logo(stem: &str) -> bool { + let s = stem.to_lowercase(); + s.contains("logo") || s.contains("wordmark") || s.contains("title") +} + +fn names_album(stem: &str, want: &str, artist: &str) -> bool { + let n = norm(stem); + if !n.contains(want) { + return false; + } + if !artist.is_empty() && n.contains(artist) { + return true; + } + let rest: Vec<&str> = stem.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty() && !w.chars().all(|c| c.is_ascii_digit()) && !matches!(w.to_lowercase().as_str(), "logo" | "wordmark" | "title" | "album" | "text" | "cover")).collect(); + norm(&rest.join(" ")) == want +} + +async fn commons_logos(http: &reqwest::Client, search: &str, want: &str, artist: &str) -> Vec { + let url = format!("https://commons.wikimedia.org/w/api.php?action=query&format=json&generator=search&gsrnamespace=6&gsrlimit=20&gsrsearch={}&prop=imageinfo&iiprop=mime", enc(search)); + let Some(v) = get_json(http, &url).await else { return Vec::new() }; + let Some(pages) = v["query"]["pages"].as_object() else { return Vec::new() }; + let mut hits: Vec<(bool, i64, String)> = pages + .values() + .filter_map(|p| { + let mime = p["imageinfo"][0]["mime"].as_str()?; + if mime != "image/png" && mime != "image/svg+xml" { + return None; + } + let file = p["title"].as_str()?.strip_prefix("File:")?.to_string(); + let stem = file.rsplit_once('.').map_or(file.as_str(), |(s, _)| s); + let (hit, rank) = (names_album(stem, want, artist), !looks_like_logo(stem)); + hit.then(|| (rank, p["index"].as_i64().unwrap_or(99), file)) + }) + .collect(); + hits.sort(); + hits.into_iter().map(|(_, _, f)| f).collect() +} + +pub async fn logo_choices(http: &reqwest::Client, query: &str, artist: &str, title: &str) -> Vec { + let (want, by) = (base(title), norm(artist)); + if want.is_empty() { + return Vec::new(); + } + let wikidata = async { + let (_, _, qid) = wikipedia(http, artist, title).await?; + wikidata_file_name(http, &qid?, "P154").await + }; + let (by_query, by_title) = (format!("{query} logo"), format!("{title} logo")); + let (wd, by_query, by_title, artist_logo) = tokio::join!(wikidata, commons_logos(http, &by_query, &want, &by), commons_logos(http, &by_title, &want, &by), audiodb_logo(http, artist)); + let mut seen = std::collections::HashSet::new(); + let mut out: Vec = wd + .map(|f| ("Wikidata", f)) + .into_iter() + .chain(by_query.into_iter().chain(by_title).map(|f| ("Wikimedia Commons", f))) + .filter(|(_, f)| seen.insert(f.clone())) + .take(12) + .map(|(source, f)| LogoChoice { source: source.into(), name: f.rsplit_once('.').map_or(f.as_str(), |(s, _)| s).replace('_', " "), thumb: commons_file(&f, 320), full: commons_file(&f, 800) }) + .collect(); + if let Some(u) = artist_logo { + out.push(LogoChoice { source: "TheAudioDB".into(), name: format!("{artist} (artist logo)"), thumb: format!("{u}/preview"), full: u }); + } + let thumbs = futures_util::future::join_all(out.iter().map(|l| async { match get_bytes(http, &l.thumb).await { Some(b) if sniff(&b).is_some() => Some(b), _ => get_bytes(http, &l.full).await } })).await; + for (l, bytes) in out.iter_mut().zip(thumbs) { + l.thumb = bytes.filter(|b| sniff(b).is_some()).map(|b| format!("data:{};base64,{}", sniff(&b).unwrap_or("image/png"), base64::engine::general_purpose::STANDARD.encode(b))).unwrap_or_default(); + } + out.retain(|l| !l.thumb.is_empty()); + out +} + +pub async fn logo(http: &reqwest::Client, url: &str) -> Result> { + if !allowed_logo(url) { + bail!("That image isn't from a source Atmosphere trusts."); + } + get_bytes(http, url).await.ok_or_else(|| anyhow!("Couldn't download that logo. Try another one.")) +} + +fn sniff(b: &[u8]) -> Option<&'static str> { + if b.starts_with(&[0xFF, 0xD8]) { + Some("image/jpeg") + } else if b.starts_with(&[0x89, b'P', b'N', b'G']) { + Some("image/png") + } else { + None + } +} + +pub async fn cover(http: &reqwest::Client, url: &str) -> Result> { + if !allowed_cover(url) { + bail!("That image isn't from a source Atmosphere trusts."); + } + let bytes = get_bytes(http, url).await.ok_or_else(|| anyhow!("Couldn't download that cover. Try another one."))?; + fit_cover(&bytes) +} + +pub fn fit_cover(bytes: &[u8]) -> Result> { + let img = image::load_from_memory(bytes).map_err(|_| anyhow!("That cover isn't an image Atmosphere can read."))?; + if sniff(bytes) == Some("image/jpeg") && img.width() <= COVER_EDGE && img.height() <= COVER_EDGE { + return Ok(bytes.to_vec()); + } + let img = if img.width() > COVER_EDGE || img.height() > COVER_EDGE { img.resize(COVER_EDGE, COVER_EDGE, image::imageops::FilterType::Lanczos3) } else { img }; + let mut out = std::io::Cursor::new(Vec::new()); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90).encode_image(&img.to_rgb8())?; + Ok(out.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spots_album_pages_by_this_artist() { + assert!(is_album_description("2001 studio album by Daft Punk", "Daft Punk")); + assert!(is_album_description("2019 EP by Billie Eilish", "Billie Eilish")); + assert!(!is_album_description("2003 single by Daft Punk", "Daft Punk")); + assert!(!is_album_description("2001 studio album by Gorillaz", "Daft Punk")); + assert!(is_album_description("1999 compilation album", "Various Artists")); + assert_eq!(base("Discovery (Daft Punk album)"), base("Discovery")); + assert_eq!(base("Homework (25th Anniversary Edition)"), "homework"); + } + + #[test] + fn trusts_only_known_cover_hosts() { + assert!(allowed_cover("https://cdn-images.dzcdn.net/images/cover/abc/1000x1000-000000-80-0-0.jpg")); + assert!(allowed_cover("https://is1-ssl.mzstatic.com/image/thumb/Music/x/1500x1500bb.jpg")); + assert!(allowed_cover("https://coverartarchive.org/release-group/48117b90-a16e-34ca-a514-19c702df1158/front-1200")); + assert!(allowed_cover("https://r2.theaudiodb.com/images/media/album/thumb/x.jpg")); + assert!(!allowed_cover("http://cdn-images.dzcdn.net/x.jpg")); + assert!(!allowed_cover("https://evil.example/dzcdn.net.jpg")); + assert!(!allowed_cover("https://dzcdn.net.evil.example/x.jpg")); + } + + #[test] + fn trusts_only_known_logo_hosts() { + assert!(allowed_logo("https://commons.wikimedia.org/wiki/Special:FilePath/Starboy_album_logo.png?width=800")); + assert!(allowed_logo("https://r2.theaudiodb.com/images/media/artist/logo/x.png")); + assert!(!allowed_logo("https://commons.wikimedia.org/w/index.php?title=x")); + assert!(!allowed_logo("http://commons.wikimedia.org/wiki/Special:FilePath/x.png")); + assert!(!allowed_logo("https://commons.wikimedia.org.evil.example/wiki/Special:FilePath/x.png")); + assert!(names_album("Starboy album logo", "starboy", "theweeknd") && names_album("Planet Her (Logo)", "planether", "dojacat") && names_album("Positions wordmark 1", "positions", "arianagrande")); + assert!(names_album("Anti Rihanna. logo", "anti", "rihanna") && !names_album("Antifaschistische Aktion logo", "anti", "rihanna") && !names_album("Anti-doping logo black", "anti", "rihanna")); + assert!(looks_like_logo("Planet Her (Logo)") && looks_like_logo("Positions wordmark 1") && !looks_like_logo("Positions album")); + } + + #[test] + fn large_covers_are_shrunk_to_a_jpeg() { + let big = image::DynamicImage::new_rgb8(3000, 3000); + let mut png = std::io::Cursor::new(Vec::new()); + big.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let out = fit_cover(png.get_ref()).unwrap(); + assert_eq!(sniff(&out), Some("image/jpeg")); + let back = image::load_from_memory(&out).unwrap(); + assert_eq!((back.width(), back.height()), (COVER_EDGE, COVER_EDGE)); + } + + #[tokio::test] + #[ignore] + async fn live_finds_discovery() { + let http = reqwest::Client::builder().user_agent("atmosphere/test (+https://github.com/pvrzz/atmosphere)").build().unwrap(); + let f = find(&http, "Daft Punk", "Discovery", true, true).await; + assert!(f.bio.as_deref().is_some_and(|b| b.contains("Daft Punk")), "no bio"); + let (covers, pages) = choices(&http, "Discovery Daft Punk", "Daft Punk", "Discovery").await; + assert!(covers.iter().any(|c| c.source == "Deezer"), "no Deezer covers"); + assert!(covers.iter().any(|c| c.source == "Apple Music"), "no Apple covers"); + assert!(pages.iter().any(|p| p.music), "no album page"); + let bytes = cover(&http, &covers[0].full).await.unwrap(); + assert_eq!(sniff(&bytes), Some("image/jpeg")); + } + + #[tokio::test] + #[ignore] + async fn live_finds_an_album_logo() { + let http = reqwest::Client::builder().user_agent("atmosphere/test (+https://github.com/pvrzz/atmosphere)").build().unwrap(); + let f = find(&http, "Ariana Grande", "Positions", true, true).await; + assert!(f.logo.is_some(), "no logo"); + assert!(f.bio_source.as_deref().is_some_and(|u| u.contains("wikipedia.org")), "no Wikipedia bio"); + for (artist, title) in [("Ariana Grande", "Positions"), ("The Weeknd", "Starboy"), ("Doja Cat", "Planet Her (Deluxe)"), ("Rihanna", "ANTI")] { + let logos = logo_choices(&http, &format!("{title} {artist}"), artist, title).await; + eprintln!("{title}: {:?}", logos.iter().map(|l| format!("{} [{}]", l.name, l.source)).collect::>()); + assert!(logos.iter().any(|l| l.source != "TheAudioDB"), "no album logos for {title}"); + assert!(logos.iter().all(|l| l.thumb.starts_with("data:image/") && allowed_logo(&l.full))); + } + let bytes = logo(&http, &commons_file("Starboy album logo.png", 800)).await.unwrap(); + assert_eq!(sniff(&bytes), Some("image/png")); + } +} diff --git a/src/artistinfo.rs b/src/artistinfo.rs index 41f93b1..03c79ef 100644 --- a/src/artistinfo.rs +++ b/src/artistinfo.rs @@ -43,7 +43,7 @@ pub(crate) async fn get_json(http: &reqwest::Client, url: &str) -> Option r.json().await.ok() } -async fn get_bytes(http: &reqwest::Client, url: &str) -> Option> { +pub(crate) async fn get_bytes(http: &reqwest::Client, url: &str) -> Option> { let r = http.get(url).timeout(Duration::from_secs(20)).send().await.ok()?; if !r.status().is_success() || r.content_length().is_some_and(|n| n as usize > MAX_IMAGE) { return None; @@ -56,7 +56,7 @@ pub(crate) fn enc(s: &str) -> String { url::form_urlencoded::byte_serialize(s.as_bytes()).collect() } -fn path_enc(s: &str) -> String { +pub(crate) fn path_enc(s: &str) -> String { s.replace(' ', "_") .bytes() .map(|b| if b.is_ascii_alphanumeric() || b"-_.~()".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }) @@ -95,13 +95,21 @@ async fn wikipedia(http: &reqwest::Client, name: &str) -> Option<(String, String Some((extract, url, s["wikibase_item"].as_str().map(String::from))) } -async fn wikidata_file(http: &reqwest::Client, qid: &str, prop: &str) -> Option> { +pub(crate) async fn wikidata_file_name(http: &reqwest::Client, qid: &str, prop: &str) -> Option { if !qid.starts_with('Q') || !qid[1..].chars().all(|c| c.is_ascii_digit()) { return None; } let v = get_json(http, &format!("https://www.wikidata.org/wiki/Special:EntityData/{qid}.json")).await?; - let file = v["entities"][qid]["claims"][prop][0]["mainsnak"]["datavalue"]["value"].as_str()?; - get_bytes(http, &format!("https://commons.wikimedia.org/wiki/Special:FilePath/{}?width=800", path_enc(file))).await + v["entities"][qid]["claims"][prop][0]["mainsnak"]["datavalue"]["value"].as_str().map(String::from) +} + +pub(crate) fn commons_file(file: &str, width: u32) -> String { + format!("https://commons.wikimedia.org/wiki/Special:FilePath/{}?width={width}", path_enc(file)) +} + +pub(crate) async fn wikidata_file(http: &reqwest::Client, qid: &str, prop: &str) -> Option> { + let file = wikidata_file_name(http, qid, prop).await?; + get_bytes(http, &commons_file(&file, 800)).await } struct AudioDb { @@ -120,6 +128,10 @@ async fn audiodb_search(http: &reqwest::Client, query: &str) -> Vec { get_json(http, &format!("{AUDIODB}/search.php?s={}", enc(query))).await.and_then(|v| v["artists"].as_array().cloned()).unwrap_or_default() } +pub(crate) async fn audiodb_logo(http: &reqwest::Client, name: &str) -> Option { + audiodb(http, name).await?.logo.filter(|u| allowed_logo(u)) +} + async fn audiodb(http: &reqwest::Client, name: &str) -> Option { let want = norm(name); audiodb_search(http, name).await.iter().find(|a| a["strArtist"].as_str().is_some_and(|n| norm(n) == want)).and_then(audiodb_entry) diff --git a/src/backup.rs b/src/backup.rs index fd7f644..7791104 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -1,19 +1,24 @@ -// atmosphere · backup.rs · Saves and restores settings, library, stats, liked songs and artist photos as one .zip +// atmosphere · backup.rs · Saves and restores settings, library, stats, liked songs, artist photos and logos, and album info as one .zip use crate::engine::data_dir; use anyhow::{anyhow, bail, Context, Result}; use serde_json::Value; use std::io::{Read, Write}; use std::path::Path; -const DATA_FILES: &[&str] = &["library.json", "stats.json", "artists.json", "hidden.json", "history.json", "archive.txt", "linked.json"]; +const DATA_FILES: &[&str] = &["library.json", "stats.json", "artists.json", "albums.json", "hidden.json", "history.json", "archive.txt", "linked.json"]; const MARKER: &str = "atmosphere-backup.json"; -fn artist_photos(data: &Path) -> Vec { - let Ok(bytes) = std::fs::read(data.join("artists.json")) else { return Vec::new() }; - let v: Value = serde_json::from_slice(&bytes).unwrap_or_default(); - v.as_object() - .map(|m| m.values().filter_map(|a| a["image"].as_str().map(|s| format!("{s}.jpg"))).collect()) - .unwrap_or_default() +fn saved_art(data: &Path) -> Vec { + let mut out = Vec::new(); + for file in ["artists.json", "albums.json"] { + let Ok(bytes) = std::fs::read(data.join(file)) else { continue }; + let v: Value = serde_json::from_slice(&bytes).unwrap_or_default(); + for m in v.as_object().into_iter().flat_map(|m| m.values()) { + out.extend(m["image"].as_str().map(|s| format!("{s}.jpg"))); + out.extend(m["logo"].as_str().map(|s| format!("{s}.png"))); + } + } + out } fn safe_name(name: &str) -> bool { @@ -51,7 +56,7 @@ fn create_from(data: &Path, settings: &Path, dest: &Path) -> Result { count += 1; } } - for photo in artist_photos(data) { + for photo in saved_art(data) { if let Ok(bytes) = std::fs::read(data.join("art").join(&photo)) { put(&mut zip, &format!("art/{photo}"), &bytes)?; count += 1; @@ -79,7 +84,7 @@ fn restore_into(data: &Path, settings: &Path, src: &Path) -> Result { settings.to_path_buf() } else if DATA_FILES.contains(&name.as_str()) { data.join(&name) - } else if let Some(photo) = name.strip_prefix("art/").filter(|p: &&str| !p.contains('/') && p.ends_with(".jpg")) { + } else if let Some(photo) = name.strip_prefix("art/").filter(|p: &&str| !p.contains('/') && (p.ends_with(".jpg") || p.ends_with(".png"))) { data.join("art").join(photo) } else { continue; @@ -105,8 +110,11 @@ mod tests { let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join("art")).unwrap(); std::fs::write(root.join("stats.json"), br#"{"liked":["a"]}"#).unwrap(); - std::fs::write(root.join("artists.json"), br#"{"x":{"name":"X","image":"p1"}}"#).unwrap(); + std::fs::write(root.join("artists.json"), br#"{"x":{"name":"X","image":"p1","logo":"l1"}}"#).unwrap(); + std::fs::write(root.join("albums.json"), br#"{"y":{"title":"Y","logo":"l2"}}"#).unwrap(); std::fs::write(root.join("art").join("p1.jpg"), b"jpg").unwrap(); + std::fs::write(root.join("art").join("l1.png"), b"png").unwrap(); + std::fs::write(root.join("art").join("l2.png"), b"png").unwrap(); std::fs::write(root.join("art").join("cover.jpg"), b"thumb").unwrap(); let zip_path = root.join("b.zip"); let set = root.join("cfg").join("settings.json"); @@ -116,10 +124,15 @@ mod tests { std::fs::remove_file(&set).unwrap(); std::fs::remove_file(root.join("stats.json")).unwrap(); std::fs::remove_file(root.join("art").join("p1.jpg")).unwrap(); + std::fs::remove_file(root.join("art").join("l1.png")).unwrap(); + std::fs::remove_file(root.join("art").join("l2.png")).unwrap(); + std::fs::remove_file(root.join("albums.json")).unwrap(); assert!(restore_into(&root, &set, &zip_path).unwrap() >= 4); assert!(set.exists()); assert_eq!(std::fs::read(root.join("stats.json")).unwrap(), br#"{"liked":["a"]}"#); assert!(root.join("art").join("p1.jpg").exists()); + assert!(root.join("art").join("l1.png").exists() && root.join("art").join("l2.png").exists()); + assert!(root.join("albums.json").exists()); std::fs::write(root.join("not.zip"), b"nope").unwrap(); assert!(restore_into(&root, &set, &root.join("not.zip")).is_err()); assert!(!safe_name("../x") && !safe_name("C:x") && safe_name("art/p.jpg")); diff --git a/src/libcmd.rs b/src/libcmd.rs index 4dc0ad3..37ba99d 100644 --- a/src/libcmd.rs +++ b/src/libcmd.rs @@ -858,6 +858,84 @@ pub async fn artist_apply(state: State<'_, AppState>, name: String, photo: Optio Ok(state.library.apply_artist_info(&name, found, true)) } +#[tauri::command] +pub async fn album_fetch(state: State<'_, AppState>, artist: String, title: String, force: bool) -> CmdResult> { + if title.trim().is_empty() || (!state.snapshot().artist_info && !force) { + return Ok(None); + } + let existing = state.library.album(&artist, &title).unwrap_or_default(); + if existing.checked.is_some() && !force { + return Ok(Some(existing)); + } + let found = crate::albuminfo::find(&state.http, &artist, &title, force || existing.bio.trim().is_empty(), force || existing.logo.is_none()).await; + Ok(Some(state.library.apply_album_info(&artist, &title, found, force))) +} + +#[tauri::command] +pub async fn album_choices(state: State<'_, AppState>, query: String, artist: String, title: String) -> CmdResult { + let q = query.trim(); + if q.is_empty() { + return Ok(serde_json::json!({ "covers": [], "pages": [], "logos": [] })); + } + let ((covers, pages), logos) = tokio::join!(crate::albuminfo::choices(&state.http, q, &artist, &title), crate::albuminfo::logo_choices(&state.http, q, &artist, &title)); + Ok(serde_json::json!({ "covers": covers, "pages": pages, "logos": logos })) +} + +#[tauri::command] +pub async fn album_apply(state: State<'_, AppState>, artist: String, title: String, page: String) -> CmdResult { + let found = crate::albuminfo::chosen(&state.http, &page).await; + if found.bio.is_none() && found.logo.is_none() { + return Err("Couldn't get anything from that page. Try another one.".into()); + } + Ok(state.library.apply_album_info(&artist, &title, found, true)) +} + +#[tauri::command] +pub async fn album_cover_get(state: State<'_, AppState>, url: String) -> CmdResult { + use base64::Engine as _; + let bytes = crate::albuminfo::cover(&state.http, &url).await.map_err(err)?; + let dir = crate::engine::temp_root().join("covers"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let path = dir.join(format!("{}.jpg", crate::library::hash(&url))); + std::fs::write(&path, &bytes).map_err(|e| e.to_string())?; + let data_url = format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(&bytes)); + Ok(serde_json::json!({ "path": path.to_string_lossy(), "dataUrl": data_url })) +} + +#[tauri::command] +pub async fn album_media(app: AppHandle, state: State<'_, AppState>, artist: String, title: String, kind: String, pick: bool) -> CmdResult { + let image = if pick { + let a = app.clone(); + let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title("Choose a logo (a transparent PNG looks best)").add_filter("Images", &["png", "jpg", "jpeg", "webp"]).blocking_pick_file()) + .await + .map_err(|e| e.to_string())?; + match picked.and_then(|p| p.into_path().ok()) { + Some(p) => Some(p), + None => return Err("cancelled".into()), + } + } else { + None + }; + let meta = state.library.album_media(&artist, &title, &kind, image.as_deref()).map_err(err)?; + changed(&app); + Ok(meta) +} + +#[tauri::command] +pub async fn album_logo_set(app: AppHandle, state: State<'_, AppState>, artist: String, title: String, url: String) -> CmdResult { + let bytes = crate::albuminfo::logo(&state.http, &url).await.map_err(err)?; + let meta = state.library.set_album_logo(&artist, &title, &bytes).map_err(err)?; + changed(&app); + Ok(meta) +} + +#[tauri::command] +pub fn album_update(app: AppHandle, state: State<'_, AppState>, artist: String, title: String, bio: String) -> CmdResult { + let meta = state.library.set_album_bio(&artist, &title, bio).map_err(err)?; + changed(&app); + Ok(meta) +} + #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct FolderReport { diff --git a/src/library.rs b/src/library.rs index f1befcb..b3d2d04 100644 --- a/src/library.rs +++ b/src/library.rs @@ -81,6 +81,29 @@ pub struct ArtistMeta { pub checked: Option, } +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct AlbumMeta { + pub artist: String, + pub title: String, + pub bio: String, + pub bio_source: Option, + pub logo: Option, + pub logo_dark: bool, + pub checked: Option, +} + +pub fn album_key(artist: &str, title: &str) -> String { + hash(&format!("{}\u{1f}{}", artist.trim().to_lowercase(), title.trim().to_lowercase())) +} + +fn set_logo(key: &str, meta: &mut AlbumMeta, data: &[u8]) -> Result<()> { + let (k, dark) = save_logo(&format!("albumlogouser{key}"), data).ok_or_else(|| anyhow!("That image couldn't be read"))?; + meta.logo = Some(k); + meta.logo_dark = dark; + Ok(()) +} + fn save_logo(key: &str, data: &[u8]) -> Option<(String, bool)> { let dir = art_dir(); std::fs::create_dir_all(&dir).ok()?; @@ -140,6 +163,7 @@ pub struct Snapshot { pub last_played: HashMap, pub liked: Vec, pub artists: HashMap, + pub albums: HashMap, pub scanning: bool, pub hidden: usize, } @@ -148,6 +172,7 @@ pub struct Library { tracks: RwLock>, stats: RwLock, artists: RwLock>, + albums: RwLock>, hidden: RwLock>, linked: RwLock>, opened: RwLock>, @@ -326,6 +351,7 @@ impl Library { tracks: RwLock::new(cached.into_iter().map(|t| (t.id.clone(), t)).collect()), stats: RwLock::new(load("stats.json")), artists: RwLock::new(load("artists.json")), + albums: RwLock::new(load("albums.json")), hidden: RwLock::new(load("hidden.json")), linked: RwLock::new(load("linked.json")), opened: RwLock::new(HashMap::new()), @@ -435,6 +461,7 @@ impl Library { last_played: stats.last_played.clone(), liked: stats.liked.iter().cloned().collect(), artists: self.artists.read().unwrap().clone(), + albums: self.albums.read().unwrap().clone(), scanning: self.scanning.load(Ordering::SeqCst), hidden: self.hidden.read().unwrap().len(), } @@ -944,6 +971,73 @@ impl Library { Ok(out) } + pub fn album(&self, artist: &str, title: &str) -> Option { + self.albums.read().unwrap().get(&album_key(artist, title)).cloned() + } + + fn with_album(&self, artist: &str, title: &str, f: impl FnOnce(&str, &mut AlbumMeta) -> Result) -> Result { + let key = album_key(artist, title); + let mut albums = self.albums.write().unwrap(); + let meta = albums.entry(key.clone()).or_default(); + meta.artist = artist.trim().to_string(); + meta.title = title.trim().to_string(); + f(&key, meta)?; + let out = meta.clone(); + store("albums.json", &*albums); + Ok(out) + } + + pub fn apply_album_info(&self, artist: &str, title: &str, found: crate::albuminfo::Found, force: bool) -> AlbumMeta { + self.with_album(artist, title, |key, meta| { + if let Some(bio) = found.bio.filter(|_| force || meta.bio.trim().is_empty()) { + meta.bio = bio; + meta.bio_source = found.bio_source; + } + if let Some(logo) = found.logo.filter(|_| force || meta.logo.is_none()) { + if let Some((k, dark)) = save_logo(&format!("albumlogo{key}"), &logo) { + meta.logo = Some(k); + meta.logo_dark = dark; + } + } + meta.checked = Some(now()); + Ok(()) + }) + .unwrap_or_default() + } + + pub fn album_media(&self, artist: &str, title: &str, kind: &str, image: Option<&Path>) -> Result { + self.with_album(artist, title, |key, meta| { + meta.checked.get_or_insert(now()); + match (kind, image) { + ("logo", None) => { + meta.logo = None; + meta.logo_dark = false; + } + ("logo", Some(src)) => set_logo(key, meta, &std::fs::read(src).context("Couldn't read that image")?)?, + _ => bail!("Unknown album field"), + } + Ok(()) + }) + } + + pub fn set_album_logo(&self, artist: &str, title: &str, data: &[u8]) -> Result { + self.with_album(artist, title, |key, meta| { + meta.checked.get_or_insert(now()); + set_logo(key, meta, data) + }) + } + + pub fn set_album_bio(&self, artist: &str, title: &str, bio: String) -> Result { + self.with_album(artist, title, |_, meta| { + if bio.trim() != meta.bio.trim() { + meta.bio_source = None; + } + meta.bio = bio; + meta.checked.get_or_insert(now()); + Ok(()) + }) + } + pub fn playlist_cover(&self, dir: &Path, name: &str, image: Option<&Path>) -> Result<()> { let folder = self.folder(dir, name); if !folder.is_dir() { diff --git a/src/main.rs b/src/main.rs index 5305949..8dce27a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ #[cfg(not(windows))] compile_error!("Atmosphere is a Windows app."); +mod albuminfo; mod api; mod artistinfo; mod backup; @@ -466,7 +467,7 @@ fn main() { } let settings = Arc::new(Mutex::new(loaded)); let http = reqwest::Client::builder() - .user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION"))) + .user_agent(concat!("atmosphere/", env!("CARGO_PKG_VERSION"), " (+https://github.com/pvrzz/atmosphere)")) .connect_timeout(Duration::from_secs(15)) .read_timeout(Duration::from_secs(90)) .build() @@ -589,6 +590,13 @@ fn main() { libcmd::artist_media, libcmd::artist_choices, libcmd::artist_apply, + libcmd::album_fetch, + libcmd::album_choices, + libcmd::album_apply, + libcmd::album_cover_get, + libcmd::album_logo_set, + libcmd::album_media, + libcmd::album_update, libcmd::playlist_cover, libcmd::playlist_relocate, libcmd::playlist_unlink diff --git a/src/storage.rs b/src/storage.rs index 228d9a3..7af3860 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -57,7 +57,13 @@ fn stalled(settings: &Settings) -> Vec { } fn orphan_art(lib: &Snapshot) -> Vec { - let used: HashSet = lib.tracks.iter().filter_map(|t| t.art.clone()).chain(lib.artists.values().filter_map(|a| a.image.clone())).collect(); + let used: HashSet = lib + .tracks + .iter() + .filter_map(|t| t.art.clone()) + .chain(lib.artists.values().flat_map(|a| [a.image.clone(), a.logo.clone()]).flatten()) + .chain(lib.albums.values().filter_map(|a| a.logo.clone())) + .collect(); let mut out = Vec::new(); walk(&data_dir().join("art"), 0, &mut out, &|p| p.file_stem().and_then(|s| s.to_str()).is_some_and(|s| !used.contains(s))); out diff --git a/ui/app.js b/ui/app.js index 9ed615b..ff914e7 100644 --- a/ui/app.js +++ b/ui/app.js @@ -206,12 +206,10 @@ function bindWindow() { const api = window.__TAURI__.window; if (!api?.getCurrentWindow) return; const win = api.getCurrentWindow(); - const restoreSvg = ''; - const maxSvg = ''; const syncMax = async () => { const maxed = await win.isMaximized().catch(() => false); const b = $("#winMax"); - b.innerHTML = maxed ? restoreSvg : maxSvg; + b.firstElementChild.textContent = maxed ? "\uE923" : "\uE922"; b.setAttribute("aria-label", maxed ? "Restore" : "Maximize"); b.title = maxed ? "Restore" : "Maximize"; }; diff --git a/ui/index.html b/ui/index.html index f1d093e..62bdec2 100644 --- a/ui/index.html +++ b/ui/index.html @@ -11,9 +11,9 @@
- - - + + +
@@ -281,7 +281,7 @@
Playlist folders live in
- +
diff --git a/ui/library.js b/ui/library.js index 0e325ff..2a3deb4 100644 --- a/ui/library.js +++ b/ui/library.js @@ -72,6 +72,8 @@ function buildIndexes(snap) { a.year ||= t.year; } for (const a of albums.values()) a.tracks.sort((x, y) => (x.discNo || 1) - (y.discNo || 1) || (x.trackNo || 999) - (y.trackNo || 999) || x.title.localeCompare(y.title)); + const albumMeta = new Map(Object.values(snap.albums || {}).map((m) => [`${lnorm(m.artist)}|${lnorm(m.title)}`, m])); + for (const a of albums.values()) a.meta = albumMeta.get(a.key) || null; Lib.albums = albums; const metaByName = new Map(Object.values(snap.artists || {}).map((m) => [lnorm(m.name), m])); const artists = new Map(); @@ -545,13 +547,56 @@ async function editTracks(tracks, opts = {}) { const showPreview = (src) => preview.replaceChildren(src ? h("img", { src, alt: "" }) : h("div", { class: "edit-cover-ph" }, icon("photo"))); showPreview(currentArt ? artUrl(currentArt) : null); const coverNote = h("p", { class: "muted small" }, currentArt ? "Current cover." : tracks.some((t) => t.art) ? "These songs have different covers." : "No cover yet."); + const al = opts.album; + let ameta = al?.meta || {}; + const about = al ? h("textarea", { class: "text area", rows: "5", placeholder: `A few lines about this ${kindWord(al)}…` }, ameta.bio || "") : null; + const logoBox = h("div", { class: "edit-logo" }); + const drawLogo = () => logoBox.replaceChildren(ameta.logo ? h("img", { class: `artist-logo ${ameta.logoDark ? "dark" : ""}`, src: artUrl(ameta.logo), alt: "" }) : h("span", { class: "muted small" }, "No logo. The title is shown as text.")); + const logoAct = (pick) => async () => { + try { + ameta = await invoke("album_media", { artist: al.artist, title: al.title, kind: "logo", pick }); + setAlbumMeta(al, ameta); + drawLogo(); + } catch (e) { + if (errText(e) !== "cancelled") toast(errText(e), "err"); + } + }; + const searchFor = (focus) => async () => { + const r = await searchAlbumOnline(al, focus); + if (!r) return; + if (r.cover) { + artwork = { kind: "file", path: r.cover.path }; + showPreview(r.cover.dataUrl); + coverNote.textContent = `New cover from ${r.cover.source} for all ${plural(tracks.length, "song")}. It's written into the files when you save.`; + } + if (r.meta) { + ameta = r.meta; + about.value = ameta.bio || ""; + drawLogo(); + } + }; + const searchOnline = al ? h("button", { class: "btn small", type: "button", onclick: searchFor("cover") }, icon("search"), "Search online…") : null; const coverBox = h("div", { class: "edit-cover-row" }, preview, h("div", { class: "stack" }, h("strong", {}, "Cover art"), coverNote, - h("div", { class: "row" }, + h("div", { class: "row wrap" }, + searchOnline, h("button", { class: "btn small", type: "button", onclick: async () => { const p = await invoke("pick_image").catch((x) => (toast(errText(x), "err"), null)); if (p) { artwork = { kind: "file", path: p.path }; showPreview(p.dataUrl); coverNote.textContent = `New cover for all ${plural(tracks.length, "song")}.`; } } }, "Choose image…"), h("button", { class: "btn small ghost", type: "button", onclick: () => { artwork = { kind: "none" }; showPreview(null); coverNote.textContent = "The cover will be removed from every song."; } }, "Remove")))); - const ok = await modal(title, h("div", { class: "stack" }, coverBox, grid, h("p", { class: "muted small" }, "Changes are written into each file's tags. Fields you leave untouched aren't changed.")), [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }]); + drawLogo(); + const albumExtras = al ? [ + h("div", { class: "stack" }, h("strong", {}, "Logo"), logoBox, + h("div", { class: "row wrap" }, h("button", { class: "btn small", type: "button", onclick: searchFor("logo") }, icon("search"), "Search online…"), h("button", { class: "btn small", type: "button", onclick: logoAct(true) }, "Choose logo…"), h("button", { class: "btn small ghost", type: "button", onclick: logoAct(false) }, "Remove"))), + h("label", { class: "field" }, h("span", {}, "About"), about), + ] : []; + const ok = await modal(title, h("div", { class: "stack" }, coverBox, grid, ...albumExtras, h("p", { class: "muted small" }, al ? "Cover and fields are written into each file's tags; fields you leave untouched aren't changed. The logo and description stay in Atmosphere." : "Changes are written into each file's tags. Fields you leave untouched aren't changed.")), [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }]); if (!ok) return; + if (al && about.value !== (ameta.bio || "")) { + try { + setAlbumMeta(al, await invoke("album_update", { artist: al.artist, title: al.title, bio: about.value })); + } catch (e) { + toast(errText(e), "err"); + } + } const meta = { artwork }; for (const [k, , v] of fields) { const nv = inputs[k].value.trim(); @@ -712,6 +757,85 @@ async function searchArtistOnline(ar) { } } +const creditFor = (url) => (/wikipedia\.org/.test(url || "") ? "From Wikipedia, under CC BY-SA" : /theaudiodb\.com/.test(url || "") ? "From TheAudioDB" : "Source"); + +const AlbumFetch = { asked: new Set() }; + +function setAlbumMeta(a, meta) { + if (!meta) return; + a.meta = meta; + const al = Lib.albums.get(a.key); + if (al) al.meta = meta; + const r = Lib.route; + if (state.view === "library" && r.name === "album" && r.id === a.key) renderLib(true); +} + +async function fetchAlbumInfo(a) { + if (state.settings?.artistInfo === false || a.meta?.checked || AlbumFetch.asked.has(a.key)) return; + AlbumFetch.asked.add(a.key); + try { + setAlbumMeta(a, await invoke("album_fetch", { artist: a.artist, title: a.title, force: false })); + } catch {} +} + +async function searchAlbumOnline(a, focus) { + let pick = { cover: null, page: null, logo: null }; + const input = h("input", { class: "text wide", type: "search", value: `${a.title} ${a.artist}`, "aria-label": "Search for this album", spellcheck: "false" }); + const covers = h("div", { class: "pick-covers" }); + const pages = h("div", { class: "pick-pages" }); + const logos = h("div", { class: "pick-logos" }); + const logoHead = h("strong", { class: "pick-head" }, "Logos from Wikimedia Commons, Wikidata and TheAudioDB"); + const status = h("p", { class: "muted small" }, "Searching…"); + const run = async () => { + status.textContent = "Searching…"; + pick = { cover: null, page: null, logo: null }; + const r = await invoke("album_choices", { query: input.value, artist: a.artist, title: a.title }).catch((e) => (status.textContent = errText(e), null)); + if (!r) return; + covers.replaceChildren(...r.covers.map((c) => { + const el = h("button", { class: "pick-cover", type: "button", title: `${c.title} · ${c.artist} (${c.source})`, onclick: () => { pick.cover = pick.cover === c ? null : c; $$(".pick-cover", covers).forEach((x) => x.classList.toggle("on", x === el && !!pick.cover)); } }, + h("img", { src: c.thumb, alt: "" }), h("span", {}, c.title), h("small", {}, c.source)); + return el; + })); + pages.replaceChildren(...r.pages.map((p) => { + const el = h("button", { class: `pick-page ${p.music ? "" : "dim"}`, type: "button", onclick: () => { pick.page = pick.page === p.key ? null : p.key; $$(".pick-page", pages).forEach((x) => x.classList.toggle("on", x === el && !!pick.page)); } }, + h("strong", {}, p.title), h("span", {}, p.description || "No description")); + return el; + })); + logos.replaceChildren(...(r.logos.length ? r.logos.map((l) => { + const el = h("button", { class: "pick-logo", type: "button", title: `${l.name} (${l.source})`, onclick: () => { pick.logo = pick.logo === l ? null : l; $$(".pick-logo", logos).forEach((x) => x.classList.toggle("on", x === el && !!pick.logo)); } }, + h("img", { src: l.thumb, alt: "" }), h("span", {}, l.name), h("small", {}, l.source)); + return el; + }) : [h("p", { class: "muted small" }, "No logos found for this one. You can still choose your own file.")])); + if (focus === "logo") logoHead.scrollIntoView({ block: "start" }); + status.textContent = r.covers.length || r.pages.length || r.logos.length ? "Pick a cover, a logo, a Wikipedia page for the description, or any mix." : "Nothing found. Try a different spelling."; + }; + input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); run(); } }); + const body = h("div", { class: "stack" }, + h("div", { class: "row" }, input, h("button", { class: "btn", type: "button", onclick: run }, icon("search"), "Search")), + status, + h("strong", { class: "pick-head" }, "Covers from TheAudioDB, Deezer, Apple Music and the Cover Art Archive"), covers, + logoHead, logos, + h("strong", { class: "pick-head" }, "Wikipedia page (for the description)"), pages); + run(); + const ok = await modal(`Find ${a.title} online`, body, [{ label: "Cancel", value: false }, { label: "Use these", value: true, primary: true }]); + if (!ok || (!pick.cover && !pick.page && !pick.logo)) return null; + const out = {}; + try { + if (pick.cover) out.cover = { ...(await invoke("album_cover_get", { url: pick.cover.full })), source: pick.cover.source }; + if (pick.page) { + out.meta = await invoke("album_apply", { artist: a.artist, title: a.title, page: pick.page }); + setAlbumMeta(a, out.meta); + } + if (pick.logo) { + out.meta = await invoke("album_logo_set", { artist: a.artist, title: a.title, url: pick.logo.full }); + setAlbumMeta(a, out.meta); + } + } catch (e) { + toast(errText(e), "err"); + } + return out.cover || out.meta ? out : null; +} + async function editArtist(ar) { let meta = ar.meta || {}; const bio = h("textarea", { class: "text area", rows: "6", placeholder: "A few lines about this artist…" }, meta.bio || ""); @@ -888,20 +1012,26 @@ function albumView(root, key) { cover(a.art, "hero-cover", a.title), h("div", { class: "hero-meta" }, h("div", { class: "kind-line" }, h("span", { class: "kind-btn", style: "cursor:default" }, albumKind(a)), a.year ? h("span", {}, String(a.year)) : null, a.tracks[0]?.genre ? h("span", { class: "sep" }, "·") : null, a.tracks[0]?.genre || null), - h("h1", { class: "hero-title" }, a.title), + a.meta?.logo ? h("h1", { class: "hero-title has-logo" }, h("img", { class: `artist-logo album-logo ${a.meta.logoDark ? "dark" : ""}`, src: artUrl(a.meta.logo), alt: a.title })) : h("h1", { class: "hero-title" }, a.title), h("button", { class: "link hero-artist", onclick: () => openLib("artist", lnorm(a.artist)) }, a.artist), h("p", { class: "view-sub" }, `${plural(a.tracks.length, "song")} · ${fmtLong(a.duration)}`), h("div", { class: "row" }, ...playBtns(a.tracks), h("button", { class: "btn ghost", onclick: (e) => menuAt(e.clientX, e.clientY, playlistItems(a.tracks)()) }, icon("playlist-add"), "Add to playlist"), h("button", { class: "btn ghost", onclick: () => editAlbum(a) }, icon("pencil"), "Edit")))) ); if (Lib.back.length) root.firstChild.prepend(h("button", { class: "icon-btn back on-hero", "aria-label": "Back", onclick: libBack }, icon("arrow-left"))); const ctx = { hideAlbum: true, hideArtist: !multiArtist, showArtistFor: (t) => lnorm(primaryArtist(t.artist)) !== lnorm(a.artist), numbers: (t, i) => t.trackNo || i + 1 }; - if (!discs) return root.append(h("div", { class: "pad-x" }, trackList(a.tracks, ctx))); const body = h("div", { class: "pad-x" }); - for (const d of [...new Set(a.tracks.map((t) => t.discNo || 1))]) { - body.append(h("h3", { class: "disc" }, icon("disc"), `Disc ${d}`)); - body.append(trackList(a.tracks.filter((t) => (t.discNo || 1) === d), { ...ctx, list: a.tracks, numbers: (t) => t.trackNo || a.tracks.indexOf(t) + 1 })); - } + if (!discs) body.append(trackList(a.tracks, ctx)); + else + for (const d of [...new Set(a.tracks.map((t) => t.discNo || 1))]) { + body.append(h("h3", { class: "disc" }, icon("disc"), `Disc ${d}`)); + body.append(trackList(a.tracks.filter((t) => (t.discNo || 1) === d), { ...ctx, list: a.tracks, numbers: (t) => t.trackNo || a.tracks.indexOf(t) + 1 })); + } + const m = a.meta; + body.append(h("section", { class: "about album-about" }, h("h2", { class: "sec" }, "About"), + m?.bio ? h("p", { class: "bio" }, m.bio) : h("button", { class: "link muted", onclick: () => editAlbum(a) }, `Add a description for this ${kindWord(a)}`), + m?.bio && m?.bioSource ? h("button", { class: "link muted small source", onclick: () => invoke("open_link", { url: m.bioSource }).catch(() => {}) }, creditFor(m.bioSource)) : null)); root.append(body); + fetchAlbumInfo(a); } function artistCard(ar) { @@ -945,7 +1075,7 @@ function artistView(root, key) { if (ar.featured.length) body.append(h("section", {}, h("h2", { class: "sec" }, "Featured on"), h("div", { class: "grid" }, ...ar.featured.map(featuredCard)))); body.append(h("section", { class: "about" }, h("h2", { class: "sec" }, "About"), ar.meta?.bio ? h("p", { class: "bio" }, ar.meta.bio) : h("button", { class: "link muted", onclick: () => editArtist(ar) }, "Add a bio and photo for this artist"), - ar.meta?.bio && ar.meta?.bioSource ? h("button", { class: "link muted small source", onclick: () => invoke("open_link", { url: ar.meta.bioSource }).catch(() => {}) }, "From Wikipedia, under CC BY-SA") : null)); + ar.meta?.bio && ar.meta?.bioSource ? h("button", { class: "link muted small source", onclick: () => invoke("open_link", { url: ar.meta.bioSource }).catch(() => {}) }, creditFor(ar.meta.bioSource)) : null)); if (!ar.meta?.checked) queueArtistInfo([ar.name], true); root.append(body); } diff --git a/ui/styles.css b/ui/styles.css index e0c37bb..0070a64 100644 --- a/ui/styles.css +++ b/ui/styles.css @@ -776,7 +776,7 @@ label.setting { cursor: pointer; } .tb-drag { min-width: 0; } .tb-controls { display: flex; } .tb-btn { width: 46px; height: var(--titlebar); display: grid; place-items: center; color: var(--text-2); transition: background-color 100ms var(--ease), color 100ms var(--ease); } -.tb-btn svg { width: 10px; height: 10px; fill: none; stroke: currentColor; stroke-width: 1; shape-rendering: crispEdges; } +.tb-glyph { font: 10px/1 "Segoe Fluent Icons", "Segoe MDL2 Assets"; } .tb-btn:hover { background: var(--hover); color: var(--text); } .tb-btn:active { background: var(--press); } .tb-btn.close:hover { background: #c42b1c; color: #fff; } @@ -1115,7 +1115,19 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa .home-hint { margin: 0; } .sec-row { display: flex; align-items: baseline; justify-content: space-between; gap: var(--s3); margin-bottom: var(--s3); } .sec-row .sec { margin: 0; } -.grid.shelf { grid-template-rows: auto; grid-auto-rows: 0; overflow: hidden; row-gap: 0; padding: var(--s2); margin: calc(var(--s2) * -1); } +.shelf-sec { container-type: inline-size; min-width: 0; } +.grid.shelf { padding: var(--s2); margin: calc(var(--s2) * -1); } +@container (width < 2192px) { .grid.shelf > :nth-child(n+12) { display: none; } } +@container (width < 2008px) { .grid.shelf > :nth-child(n+11) { display: none; } } +@container (width < 1824px) { .grid.shelf > :nth-child(n+10) { display: none; } } +@container (width < 1640px) { .grid.shelf > :nth-child(n+9) { display: none; } } +@container (width < 1456px) { .grid.shelf > :nth-child(n+8) { display: none; } } +@container (width < 1272px) { .grid.shelf > :nth-child(n+7) { display: none; } } +@container (width < 1088px) { .grid.shelf > :nth-child(n+6) { display: none; } } +@container (width < 904px) { .grid.shelf > :nth-child(n+5) { display: none; } } +@container (width < 720px) { .grid.shelf > :nth-child(n+4) { display: none; } } +@container (width < 536px) { .grid.shelf > :nth-child(n+3) { display: none; } } +@container (width < 352px) { .grid.shelf > :nth-child(n+2) { display: none; } } .tile-mosaic { display: grid; grid-template-columns: 1fr 1fr; overflow: hidden; } .tile-mosaic img, .tile-mosaic .cover { width: 100%; height: 100%; object-fit: cover; border-radius: 0; } .tile-img.ph { display: grid; place-items: center; background: var(--surface); color: var(--text-3); } @@ -1239,6 +1251,23 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa .pick-logo img { width: 100%; height: 56px; object-fit: contain; } .pick-logo.on { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); } +/* album cover picker, logo and about */ +.row.wrap { flex-wrap: wrap; } +.modal:has(.pick-covers) { max-width: 760px; } +.pick-covers { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: var(--s2); } +.pick-cover { display: grid; gap: 3px; padding: 6px; border-radius: 10px; border: 2px solid transparent; text-align: left; min-width: 0; } +.pick-cover:hover { background: var(--hover); } +.pick-cover.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); } +.pick-cover img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 6px; background: var(--surface-2); } +.pick-cover span { font-size: 12px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pick-cover small { font-size: 11px; color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pick-logos > p { grid-column: 1 / -1; margin: 0; } +.pick-logo { grid-template-columns: minmax(0, 1fr); min-width: 0; } +.pick-logo span, .pick-logo small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pick-logo small { margin-top: -4px; font-size: 11px; color: var(--text-3); } +.album-logo { max-height: 88px; } +.album-about { margin-top: var(--s8); } + /* update notice */ .update-notice { position: fixed; right: var(--s5); bottom: 100px; z-index: 95; width: min(380px, calc(100vw - 32px)); display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: var(--s2) var(--s3); align-items: start; padding: var(--s4); border-radius: var(--r-card); background: var(--surface); border: 1px solid var(--border); box-shadow: var(--shadow); animation: menuIn 200ms var(--ease); } .update-notice.out { opacity: 0; transform: translateY(6px); transition: opacity 180ms var(--ease), transform 180ms var(--ease); }