From a02c8c7cf772574fa84117f3c37482186d632a47 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 10:33:54 -0600 Subject: [PATCH] S020: MusicBrainz and Cover Art Archive client with rate limit and track matching Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 143 +++++++ Cargo.toml | 3 + .../07 Tag editor/S020-musicbrainz-client.md | 12 +- Plans/INDEX.md | 2 +- crates/tunal-tags/Cargo.toml | 3 + crates/tunal-tags/examples/mb.rs | 80 ++++ crates/tunal-tags/src/caa.rs | 30 ++ crates/tunal-tags/src/http.rs | 138 +++++++ crates/tunal-tags/src/lib.rs | 7 + crates/tunal-tags/src/matching.rs | 99 +++++ crates/tunal-tags/src/mb.rs | 371 ++++++++++++++++++ docs/PROGRESS.md | 7 + 12 files changed, 888 insertions(+), 7 deletions(-) create mode 100644 crates/tunal-tags/examples/mb.rs create mode 100644 crates/tunal-tags/src/caa.rs create mode 100644 crates/tunal-tags/src/http.rs create mode 100644 crates/tunal-tags/src/matching.rs create mode 100644 crates/tunal-tags/src/mb.rs diff --git a/Cargo.lock b/Cargo.lock index 869349c..bd4ccf6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1507,6 +1507,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1742,6 +1753,22 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -4009,6 +4036,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rowan" version = "0.17.0" @@ -4097,6 +4138,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -4576,6 +4652,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.16.2" @@ -4929,9 +5011,11 @@ checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" name = "tunal" version = "0.1.0" dependencies = [ + "jiff", "png", "slint", "slint-build", + "tunal-core", "tunal-theme", ] @@ -4969,6 +5053,9 @@ name = "tunal-tags" version = "0.1.0" dependencies = [ "lofty", + "serde", + "serde_json", + "ureq", ] [[package]] @@ -5084,12 +5171,47 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "unty" version = "0.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -5158,6 +5280,12 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -5464,6 +5592,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -6261,6 +6398,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index e87a68b..1e2172d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,3 +21,6 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", resvg = "0.50" lofty = "0.25" md-5 = "0.11" +ureq = { version = "3", default-features = false, features = ["rustls", "gzip"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/Plans/07 Tag editor/S020-musicbrainz-client.md b/Plans/07 Tag editor/S020-musicbrainz-client.md index 1edac4e..45c4f17 100644 --- a/Plans/07 Tag editor/S020-musicbrainz-client.md +++ b/Plans/07 Tag editor/S020-musicbrainz-client.md @@ -10,12 +10,12 @@ Search releases and recordings on MusicBrainz, fetch release details and front c CLAUDE.md §2 MusicBrainz; docs/DECISIONS.md D-019 (TLS). ## Steps -- [ ] HTTP: `ureq` with rustls + ring (D-019), User-Agent from CLAUDE.md, base URLs overridable for mocks; one global limiter (≥ 1 s between requests to either service); 503 → back off and retry. -- [ ] MusicBrainz: release search (artist, album, track count), recording search, release lookup with recordings, artist credits, release group, genres; JSON → our types. -- [ ] Cover Art Archive: front cover (500 px) for a release, following redirects. -- [ ] Track matching helper: map files to release tracks by disc/position, then duration and title similarity. -- [ ] Example against a local mock (canned JSON served from the scratchpad with `python -m http.server`). -- [ ] PROGRESS entry, INDEX line, commit `S020: …` +- [x] HTTP: `ureq` with rustls + ring (D-019), User-Agent from CLAUDE.md, base URLs overridable for mocks; one global limiter (≥ 1 s between requests to either service); 503 → back off and retry. +- [x] MusicBrainz: release search (artist, album, track count), recording search, release lookup with recordings, artist credits, release group, genres; JSON → our types. +- [x] Cover Art Archive: front cover (500 px) for a release, following redirects. +- [x] Track matching helper: map files to release tracks by disc/position, then duration and title similarity. +- [x] Example against a local mock (canned JSON served from the scratchpad with `python -m http.server`). +- [x] PROGRESS entry, INDEX line, commit `S020: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 19e1fef..7e7fd7d 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -43,7 +43,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 07 Tag editor - [x] [S019 — Tag model with lofty](07%20Tag%20editor/S019-tag-model.md) · Sonnet medium -- [ ] [S020 — MusicBrainz and Cover Art Archive client](07%20Tag%20editor/S020-musicbrainz-client.md) · Sonnet high +- [x] [S020 — MusicBrainz and Cover Art Archive client](07%20Tag%20editor/S020-musicbrainz-client.md) · Sonnet high - [ ] [S021 — Tag editor UI](07%20Tag%20editor/S021-tag-editor-ui.md) · Opus medium ## 08 Audio player diff --git a/crates/tunal-tags/Cargo.toml b/crates/tunal-tags/Cargo.toml index 772698c..865caf3 100644 --- a/crates/tunal-tags/Cargo.toml +++ b/crates/tunal-tags/Cargo.toml @@ -7,3 +7,6 @@ publish.workspace = true [dependencies] lofty.workspace = true +ureq.workspace = true +serde.workspace = true +serde_json.workspace = true diff --git a/crates/tunal-tags/examples/mb.rs b/crates/tunal-tags/examples/mb.rs new file mode 100644 index 0000000..0f0cc4c --- /dev/null +++ b/crates/tunal-tags/examples/mb.rs @@ -0,0 +1,80 @@ +//! `mb `: searches, looks up the best release, fetches its cover and +//! matches three made-up files to its tracks. The base URL serves both MusicBrainz and the +//! Cover Art Archive (a local mock); every request prints its time. + +use std::time::Instant; + +use tunal_tags::{Client, FileInfo}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let [base, artist, album] = args.as_slice() else { + eprintln!("usage: mb "); + std::process::exit(1); + }; + let start = Instant::now(); + let stamp = |what: &str| println!("[{:6.2}s] {what}", start.elapsed().as_secs_f64()); + let client = Client::with_bases(base, base); + + let releases = client + .search_releases(Some(artist), Some(album), None, 5) + .unwrap(); + stamp(&format!("release search: {} hits", releases.len())); + let Some(best) = releases.first() else { return }; + println!(" {best:?}"); + + let recordings = client + .search_recordings(Some("Second Tune"), Some(artist), None, 5) + .unwrap(); + stamp(&format!("recording search: {} hits", recordings.len())); + + let release = client + .release(&best.id) + .unwrap() + .expect("release not found"); + stamp(&format!( + "release lookup: {} by {}, {} tracks, genres {:?}", + release.title, + release.artist, + release.tracks.len(), + release.genres + )); + for t in &release.tracks { + println!( + " {}-{} {} ({:?} ms)", + t.disc, t.position, t.title, t.length_ms + ); + } + + let cover = client.front_cover(&best.id).unwrap(); + stamp(&format!( + "cover: {:?}", + cover.as_ref().map(|c| (&c.mime, c.data.len())) + )); + + let files = [ + FileInfo { + track: Some(2), + title: Some("second tune".into()), + duration_ms: Some(201_000), + ..Default::default() + }, + FileInfo { + title: Some("Opening Song (live)".into()), + duration_ms: Some(181_500), + ..Default::default() + }, + FileInfo { + track: Some(1), + title: Some("Unrelated".into()), + duration_ms: Some(30_000), + ..Default::default() + }, + ]; + for (i, m) in tunal_tags::match_tracks(&files, &release) + .iter() + .enumerate() + { + println!(" file {i} -> {:?}", m.map(|t| &release.tracks[t].title)); + } +} diff --git a/crates/tunal-tags/src/caa.rs b/crates/tunal-tags/src/caa.rs new file mode 100644 index 0000000..bd05082 --- /dev/null +++ b/crates/tunal-tags/src/caa.rs @@ -0,0 +1,30 @@ +//! Cover Art Archive: the front cover of a release. + +use crate::http::{Client, NetError}; +use crate::mb::check_id; +use crate::model::Cover; + +impl Client { + /// The front cover of a release at 500 px; `None` when the release has none. + /// Redirects (the archive forwards to its storage) are followed. + pub fn front_cover(&self, release_id: &str) -> Result, NetError> { + check_id(release_id)?; + let url = format!("{}/release/{release_id}/front-500", self.cover_art); + let Some(data) = self.get(&url, &[], "image/*")? else { + return Ok(None); + }; + let mime = if data.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if data.starts_with(&[0x89, b'P', b'N', b'G']) { + "image/png" + } else { + return Err(NetError::Parse( + "the cover is not a JPEG or PNG image".into(), + )); + }; + Ok(Some(Cover { + mime: mime.into(), + data, + })) + } +} diff --git a/crates/tunal-tags/src/http.rs b/crates/tunal-tags/src/http.rs new file mode 100644 index 0000000..c94a96e --- /dev/null +++ b/crates/tunal-tags/src/http.rs @@ -0,0 +1,138 @@ +//! HTTP for MusicBrainz and the Cover Art Archive: one shared rate limit, retries on 503. + +use std::fmt; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use ureq::Agent; + +const MUSICBRAINZ: &str = "https://musicbrainz.org"; +const COVER_ART_ARCHIVE: &str = "https://coverartarchive.org"; +/// Minimum time between two requests to either service, across the whole app. +const MIN_INTERVAL: Duration = Duration::from_secs(1); +const MAX_ATTEMPTS: u32 = 4; +const MAX_BODY: u64 = 16 * 1024 * 1024; + +static LAST_REQUEST: Mutex> = Mutex::new(None); + +#[derive(Debug)] +pub enum NetError { + /// Connection, TLS or timeout failure. + Http(String), + /// The server answered with an error status. + Status(u16), + /// The answer was not what we expected. + Parse(String), +} + +impl fmt::Display for NetError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + NetError::Http(e) => write!(f, "network error: {e}"), + NetError::Status(s) => write!(f, "the server answered {s}"), + NetError::Parse(e) => write!(f, "unexpected answer: {e}"), + } + } +} + +impl std::error::Error for NetError {} + +/// Waits until at least `MIN_INTERVAL` has passed since the last request, then marks a new one. +fn throttle() { + let mut last = LAST_REQUEST.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = *last { + let ready = at + MIN_INTERVAL; + let now = Instant::now(); + if ready > now { + std::thread::sleep(ready - now); + } + } + *last = Some(Instant::now()); +} + +#[derive(Clone)] +pub struct Client { + agent: Agent, + pub(crate) musicbrainz: String, + pub(crate) cover_art: String, +} + +impl Default for Client { + fn default() -> Self { + Client::with_bases(MUSICBRAINZ, COVER_ART_ARCHIVE) + } +} + +impl Client { + pub fn new() -> Client { + Client::default() + } + + /// A client for other base URLs (no trailing slash), for mocks. + pub fn with_bases(musicbrainz: &str, cover_art: &str) -> Client { + let user_agent = format!( + "Tunal/{} ( https://archlinux.tail7c4f5e.ts.net/git/astar76/Tunal )", + env!("CARGO_PKG_VERSION") + ); + let agent: Agent = Agent::config_builder() + .user_agent(user_agent) + .timeout_global(Some(Duration::from_secs(30))) + .http_status_as_error(false) + .build() + .into(); + Client { + agent, + musicbrainz: musicbrainz.trim_end_matches('/').to_owned(), + cover_art: cover_art.trim_end_matches('/').to_owned(), + } + } + + /// GET with the rate limit. `Ok(None)` for 404. 503 and 429 are retried with a growing pause. + pub(crate) fn get( + &self, + url: &str, + query: &[(&str, &str)], + accept: &str, + ) -> Result>, NetError> { + let mut attempt = 0; + loop { + throttle(); + let mut request = self.agent.get(url).header("Accept", accept); + for (k, v) in query { + request = request.query(k, v); + } + let mut response = request.call().map_err(|e| NetError::Http(e.to_string()))?; + let status = response.status().as_u16(); + match status { + 200..=299 => { + let body = response + .body_mut() + .with_config() + .limit(MAX_BODY) + .read_to_vec() + .map_err(|e| NetError::Http(e.to_string()))?; + return Ok(Some(body)); + } + 404 => return Ok(None), + 503 | 429 if attempt + 1 < MAX_ATTEMPTS => { + attempt += 1; + std::thread::sleep(Duration::from_secs(1 << attempt)); + } + _ => return Err(NetError::Status(status)), + } + } + } + + pub(crate) fn get_json( + &self, + url: &str, + query: &[(&str, &str)], + ) -> Result, NetError> { + match self.get(url, query, "application/json")? { + Some(body) => serde_json::from_slice(&body) + .map(Some) + .map_err(|e| NetError::Parse(e.to_string())), + None => Ok(None), + } + } +} diff --git a/crates/tunal-tags/src/lib.rs b/crates/tunal-tags/src/lib.rs index 31e1685..b564230 100644 --- a/crates/tunal-tags/src/lib.rs +++ b/crates/tunal-tags/src/lib.rs @@ -1,7 +1,14 @@ //! Music tags and the MusicBrainz and Cover Art Archive client. +mod caa; +mod http; mod io; +mod matching; +mod mb; mod model; +pub use http::{Client, NetError}; pub use io::{Error, read, read_set, write, write_many}; +pub use matching::{FileInfo, match_tracks}; +pub use mb::{RecordingHit, Release, ReleaseHit, Track}; pub use model::{Cover, CoverEdit, Edit, Merged, TagEdit, TagSet, TrackTags}; diff --git a/crates/tunal-tags/src/matching.rs b/crates/tunal-tags/src/matching.rs new file mode 100644 index 0000000..c179624 --- /dev/null +++ b/crates/tunal-tags/src/matching.rs @@ -0,0 +1,99 @@ +//! Maps files to the tracks of a release. + +use crate::mb::Release; + +/// What we know about a file before matching. +#[derive(Clone, Debug, Default)] +pub struct FileInfo { + pub disc: Option, + pub track: Option, + pub title: Option, + pub duration_ms: Option, +} + +const MIN_SCORE: f64 = 40.0; + +/// For each file, the index into `release.tracks` it belongs to, or `None`. +/// Disc and position decide first; duration (within a few seconds) and title similarity +/// break ties and reject a position that clearly belongs to another song. A track is used once. +pub fn match_tracks(files: &[FileInfo], release: &Release) -> Vec> { + let mut pairs: Vec<(f64, usize, usize)> = Vec::new(); + for (f, file) in files.iter().enumerate() { + for (t, track) in release.tracks.iter().enumerate() { + let score = score(file, track, release.disc_total); + if score >= MIN_SCORE { + pairs.push((score, f, t)); + } + } + } + pairs.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2))); + let mut result = vec![None; files.len()]; + let mut taken = vec![false; release.tracks.len()]; + for (_, f, t) in pairs { + if result[f].is_none() && !taken[t] { + result[f] = Some(t); + taken[t] = true; + } + } + result +} + +fn score(file: &FileInfo, track: &crate::mb::Track, disc_total: u32) -> f64 { + let mut score = 0.0; + let disc_ok = match file.disc { + Some(d) => d == track.disc, + None => disc_total <= 1 || track.disc == 1, + }; + if disc_ok && file.track == Some(track.position) { + score += 60.0; + } + let mut duration_far = false; + if let (Some(a), Some(b)) = (file.duration_ms, track.length_ms) { + let diff = a.abs_diff(b) as f64 / 1000.0; + if diff <= 3.0 { + score += 20.0 * (1.0 - diff / 3.0); + } + duration_far = diff > 10.0; + } + let similarity = file + .title + .as_deref() + .map(|t| similarity(t, &track.title)) + .unwrap_or(0.0); + score += 40.0 * similarity; + if file.title.is_some() && similarity < 0.3 && duration_far { + score -= 30.0; + } + score +} + +fn normalize(s: &str) -> Vec { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() +} + +/// Dice coefficient over character bigrams of the alphanumeric lowercase text, 0–1. +fn similarity(a: &str, b: &str) -> f64 { + let (a, b) = (normalize(a), normalize(b)); + if a.is_empty() || b.is_empty() { + return 0.0; + } + if a == b { + return 1.0; + } + if a.len() < 2 || b.len() < 2 { + return 0.0; + } + let mut pool: Vec<[char; 2]> = b.windows(2).map(|w| [w[0], w[1]]).collect(); + let total = (a.len() - 1) + pool.len(); + let mut shared = 0; + for w in a.windows(2) { + if let Some(i) = pool.iter().position(|p| *p == [w[0], w[1]]) { + pool.swap_remove(i); + shared += 1; + } + } + 2.0 * shared as f64 / total as f64 +} diff --git a/crates/tunal-tags/src/mb.rs b/crates/tunal-tags/src/mb.rs new file mode 100644 index 0000000..c6ea07b --- /dev/null +++ b/crates/tunal-tags/src/mb.rs @@ -0,0 +1,371 @@ +//! MusicBrainz web service: release and recording search, release lookup. + +use serde::Deserialize; + +use crate::http::{Client, NetError}; + +/// A release found by a search. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReleaseHit { + pub id: String, + pub title: String, + pub artist: String, + pub date: Option, + pub country: Option, + pub track_count: Option, + pub release_group_id: Option, + /// MusicBrainz relevance, 0–100. + pub score: u32, +} + +/// A recording found by a search. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordingHit { + pub id: String, + pub title: String, + pub artist: String, + pub length_ms: Option, + /// `(release id, release title)` the recording appears on. + pub releases: Vec<(String, String)>, + pub score: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Track { + /// Disc number (the medium's position, from 1). + pub disc: u32, + /// Position on the disc, from 1. + pub position: u32, + /// Tracks on that disc. + pub disc_track_count: u32, + pub title: String, + pub artist: String, + pub artist_ids: Vec, + pub recording_id: String, + pub track_id: String, + pub length_ms: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + pub id: String, + pub title: String, + pub artist: String, + pub artist_ids: Vec, + pub date: Option, + pub country: Option, + pub release_group_id: Option, + /// Genres of the release and its release group, most voted first, without duplicates. + pub genres: Vec, + pub disc_total: u32, + pub tracks: Vec, +} + +#[derive(Deserialize, Default)] +struct Credit { + #[serde(default)] + name: String, + #[serde(default)] + joinphrase: String, + #[serde(default)] + artist: IdOnly, +} + +#[derive(Deserialize, Default)] +struct IdOnly { + #[serde(default)] + id: String, +} + +#[derive(Deserialize, Default)] +struct Genre { + name: String, + #[serde(default)] + count: i64, +} + +fn credit_text(credits: &[Credit]) -> String { + credits + .iter() + .map(|c| format!("{}{}", c.name, c.joinphrase)) + .collect() +} + +fn credit_ids(credits: &[Credit]) -> Vec { + credits.iter().map(|c| c.artist.id.clone()).collect() +} + +#[derive(Deserialize)] +struct ReleaseSearch { + #[serde(default)] + releases: Vec, +} + +#[derive(Deserialize)] +struct RawReleaseHit { + id: String, + #[serde(default)] + title: String, + #[serde(default)] + score: u32, + date: Option, + country: Option, + #[serde(rename = "track-count")] + track_count: Option, + #[serde(rename = "artist-credit", default)] + artist_credit: Vec, + #[serde(rename = "release-group")] + release_group: Option, +} + +#[derive(Deserialize)] +struct RecordingSearch { + #[serde(default)] + recordings: Vec, +} + +#[derive(Deserialize)] +struct RawRecordingHit { + id: String, + #[serde(default)] + title: String, + #[serde(default)] + score: u32, + length: Option, + #[serde(rename = "artist-credit", default)] + artist_credit: Vec, + #[serde(default)] + releases: Vec, +} + +#[derive(Deserialize)] +struct RawTitled { + id: String, + #[serde(default)] + title: String, +} + +#[derive(Deserialize)] +struct RawRelease { + id: String, + #[serde(default)] + title: String, + date: Option, + country: Option, + #[serde(rename = "artist-credit", default)] + artist_credit: Vec, + #[serde(rename = "release-group")] + release_group: Option, + #[serde(default)] + genres: Vec, + #[serde(default)] + media: Vec, +} + +#[derive(Deserialize)] +struct RawGroup { + id: String, + #[serde(default)] + genres: Vec, +} + +#[derive(Deserialize)] +struct RawMedium { + position: Option, + #[serde(default)] + tracks: Vec, +} + +#[derive(Deserialize)] +struct RawTrack { + #[serde(default)] + id: String, + position: Option, + #[serde(default)] + title: String, + length: Option, + #[serde(rename = "artist-credit", default)] + artist_credit: Vec, + recording: Option, +} + +#[derive(Deserialize)] +struct RawRecording { + #[serde(default)] + id: String, + length: Option, +} + +/// MusicBrainz ids are UUIDs; anything else must not end up in a URL path. +pub(crate) fn check_id(id: &str) -> Result<(), NetError> { + if !id.is_empty() && id.chars().all(|c| c.is_ascii_hexdigit() || c == '-') { + Ok(()) + } else { + Err(NetError::Parse(format!("not a MusicBrainz id: {id:?}"))) + } +} + +/// Quotes a value for a Lucene query phrase. +fn phrase(value: &str) -> String { + let escaped: String = value + .chars() + .flat_map(|c| match c { + '"' | '\\' => vec!['\\', c], + _ => vec![c], + }) + .collect(); + format!("\"{escaped}\"") +} + +fn query_of(parts: &[(&str, Option)]) -> String { + parts + .iter() + .filter_map(|(field, value)| value.as_ref().map(|v| format!("{field}:{v}"))) + .collect::>() + .join(" AND ") +} + +fn non_empty(s: Option<&str>) -> Option { + s.map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} + +impl Client { + /// Searches releases by artist, album title and track count. + pub fn search_releases( + &self, + artist: Option<&str>, + album: Option<&str>, + track_count: Option, + limit: u32, + ) -> Result, NetError> { + let query = query_of(&[ + ("artist", non_empty(artist).map(|v| phrase(&v))), + ("release", non_empty(album).map(|v| phrase(&v))), + ("tracks", track_count.map(|n| n.to_string())), + ]); + if query.is_empty() { + return Ok(Vec::new()); + } + let url = format!("{}/ws/2/release", self.musicbrainz); + let limit = limit.to_string(); + let found: Option = self.get_json( + &url, + &[("query", &query), ("fmt", "json"), ("limit", &limit)], + )?; + Ok(found + .map(|f| f.releases) + .unwrap_or_default() + .into_iter() + .map(|r| ReleaseHit { + artist: credit_text(&r.artist_credit), + id: r.id, + title: r.title, + date: r.date.filter(|d| !d.is_empty()), + country: r.country, + track_count: r.track_count, + release_group_id: r.release_group.map(|g| g.id), + score: r.score, + }) + .collect()) + } + + /// Searches recordings by title, artist and album. + pub fn search_recordings( + &self, + title: Option<&str>, + artist: Option<&str>, + album: Option<&str>, + limit: u32, + ) -> Result, NetError> { + let query = query_of(&[ + ("recording", non_empty(title).map(|v| phrase(&v))), + ("artist", non_empty(artist).map(|v| phrase(&v))), + ("release", non_empty(album).map(|v| phrase(&v))), + ]); + if query.is_empty() { + return Ok(Vec::new()); + } + let url = format!("{}/ws/2/recording", self.musicbrainz); + let limit = limit.to_string(); + let found: Option = self.get_json( + &url, + &[("query", &query), ("fmt", "json"), ("limit", &limit)], + )?; + Ok(found + .map(|f| f.recordings) + .unwrap_or_default() + .into_iter() + .map(|r| RecordingHit { + artist: credit_text(&r.artist_credit), + id: r.id, + title: r.title, + length_ms: r.length, + releases: r.releases.into_iter().map(|x| (x.id, x.title)).collect(), + score: r.score, + }) + .collect()) + } + + /// Looks up a release with its tracks, artist credits, release group and genres. + pub fn release(&self, id: &str) -> Result, NetError> { + check_id(id)?; + let url = format!("{}/ws/2/release/{id}", self.musicbrainz); + let raw: Option = self.get_json( + &url, + &[ + ("inc", "recordings artist-credits release-groups genres"), + ("fmt", "json"), + ], + )?; + Ok(raw.map(into_release)) + } +} + +fn into_release(raw: RawRelease) -> Release { + let mut genres: Vec<&Genre> = raw + .genres + .iter() + .chain(raw.release_group.iter().flat_map(|g| g.genres.iter())) + .collect(); + genres.sort_by_key(|g| std::cmp::Reverse(g.count)); + let mut names: Vec = Vec::new(); + for g in genres { + if !names.iter().any(|n| n.eq_ignore_ascii_case(&g.name)) { + names.push(g.name.clone()); + } + } + + let mut tracks = Vec::new(); + for (i, medium) in raw.media.iter().enumerate() { + let disc = medium.position.unwrap_or(i as u32 + 1); + let count = medium.tracks.len() as u32; + for (j, t) in medium.tracks.iter().enumerate() { + let recording = t.recording.as_ref(); + tracks.push(Track { + disc, + position: t.position.unwrap_or(j as u32 + 1), + disc_track_count: count, + title: t.title.clone(), + artist: credit_text(&t.artist_credit), + artist_ids: credit_ids(&t.artist_credit), + recording_id: recording.map(|r| r.id.clone()).unwrap_or_default(), + track_id: t.id.clone(), + length_ms: t.length.or(recording.and_then(|r| r.length)), + }); + } + } + Release { + artist: credit_text(&raw.artist_credit), + artist_ids: credit_ids(&raw.artist_credit), + id: raw.id, + title: raw.title, + date: raw.date.filter(|d| !d.is_empty()), + country: raw.country, + release_group_id: raw.release_group.map(|g| g.id), + genres: names, + disc_total: raw.media.len() as u32, + tracks, + } +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 40bb1d8..61a61ef 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -62,5 +62,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: tracker artifact not updated (session had no ArtifactData). Dates are the raw string (`RecordingDate`, falls back to `Year`); no Timestamp parsing. - Later: Vorbis `COMMENT` key (non-standard, ffmpeg writes it) is not read as the comment, only `DESCRIPTION`; lofty rewrites the file in place (no temp-file + rename); sort-order and lyrics fields; multi-value artists. +## S020 — MusicBrainz and Cover Art Archive client +- Done: `tunal_tags::Client` (`Client::new()` real services; `Client::with_bases(mb, caa)` for mocks). `search_releases(artist, album, track_count, limit) -> Vec`, `search_recordings(title, artist, album, limit) -> Vec`, `release(id) -> Option }>`, `front_cover(release_id) -> Option` (front-500, redirects followed, JPEG/PNG only; same `Cover` as S019). `match_tracks(&[FileInfo { disc, track, title, duration_ms }], &Release) -> Vec>` (index into `release.tracks`; position 60 + duration ≤ 3 s up to 20 + title bigram similarity up to 40, threshold 40, each track once). Errors `NetError::{Http, Status, Parse}`; all calls are blocking (run off the UI thread). +- HTTP: `ureq` 3 with rustls + ring (`cargo tree -i aws-lc-rs` empty), User-Agent `Tunal/ ( … )`, one process-wide limiter (≥ 1 s between requests to either service, shared by all `Client`s), 503/429 retried after 2 s, 4 s, 8 s then `Status`; 404 → `None`; 30 s timeout, 16 MiB body cap. Workspace deps added: ureq, serde, serde_json. Mapping of `Release` to tags (`mb_*` ids, track/disc totals, genre) is left to the editor plan (S021) via `TagEdit`. +- Verified: build and clippy -D warnings and fmt --check for `tunal-tags`; example `mb` against a scratchpad mock (python, not committed): requests 1 s apart (stamps 0.00/1.00/…), lookup got 503 once and succeeded after the 2 s pause, cover via 307 redirect, matching of 3 made-up files. Real services never contacted. +- Not done: workspace-wide clippy currently fails in `tunal-core` (S008's in-progress `playlist.rs`), not in this plan's files. Real MusicBrainz JSON shape checked against docs only, not live. No search by AcoustID. +- Later: `inc` for labels/barcode; honour `Retry-After`; cache of lookups. + ## Later -