S020: MusicBrainz and Cover Art Archive client with rate limit and track matching

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 10:33:54 -06:00
commit a02c8c7cf7
12 changed files with 888 additions and 7 deletions

143
Cargo.lock generated
View file

@ -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"

View file

@ -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"

View file

@ -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.

View file

@ -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

View file

@ -7,3 +7,6 @@ publish.workspace = true
[dependencies]
lofty.workspace = true
ureq.workspace = true
serde.workspace = true
serde_json.workspace = true

View file

@ -0,0 +1,80 @@
//! `mb <base-url> <artist> <album>`: 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<String> = std::env::args().skip(1).collect();
let [base, artist, album] = args.as_slice() else {
eprintln!("usage: mb <base-url> <artist> <album>");
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));
}
}

View file

@ -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<Option<Cover>, 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,
}))
}
}

View file

@ -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<Option<Instant>> = 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<Option<Vec<u8>>, 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<T: serde::de::DeserializeOwned>(
&self,
url: &str,
query: &[(&str, &str)],
) -> Result<Option<T>, 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),
}
}
}

View file

@ -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};

View file

@ -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<u32>,
pub track: Option<u32>,
pub title: Option<String>,
pub duration_ms: Option<u32>,
}
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<Option<usize>> {
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<char> {
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
}

371
crates/tunal-tags/src/mb.rs Normal file
View file

@ -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<String>,
pub country: Option<String>,
pub track_count: Option<u32>,
pub release_group_id: Option<String>,
/// 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<u32>,
/// `(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<String>,
pub recording_id: String,
pub track_id: String,
pub length_ms: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Release {
pub id: String,
pub title: String,
pub artist: String,
pub artist_ids: Vec<String>,
pub date: Option<String>,
pub country: Option<String>,
pub release_group_id: Option<String>,
/// Genres of the release and its release group, most voted first, without duplicates.
pub genres: Vec<String>,
pub disc_total: u32,
pub tracks: Vec<Track>,
}
#[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<String> {
credits.iter().map(|c| c.artist.id.clone()).collect()
}
#[derive(Deserialize)]
struct ReleaseSearch {
#[serde(default)]
releases: Vec<RawReleaseHit>,
}
#[derive(Deserialize)]
struct RawReleaseHit {
id: String,
#[serde(default)]
title: String,
#[serde(default)]
score: u32,
date: Option<String>,
country: Option<String>,
#[serde(rename = "track-count")]
track_count: Option<u32>,
#[serde(rename = "artist-credit", default)]
artist_credit: Vec<Credit>,
#[serde(rename = "release-group")]
release_group: Option<IdOnly>,
}
#[derive(Deserialize)]
struct RecordingSearch {
#[serde(default)]
recordings: Vec<RawRecordingHit>,
}
#[derive(Deserialize)]
struct RawRecordingHit {
id: String,
#[serde(default)]
title: String,
#[serde(default)]
score: u32,
length: Option<u32>,
#[serde(rename = "artist-credit", default)]
artist_credit: Vec<Credit>,
#[serde(default)]
releases: Vec<RawTitled>,
}
#[derive(Deserialize)]
struct RawTitled {
id: String,
#[serde(default)]
title: String,
}
#[derive(Deserialize)]
struct RawRelease {
id: String,
#[serde(default)]
title: String,
date: Option<String>,
country: Option<String>,
#[serde(rename = "artist-credit", default)]
artist_credit: Vec<Credit>,
#[serde(rename = "release-group")]
release_group: Option<RawGroup>,
#[serde(default)]
genres: Vec<Genre>,
#[serde(default)]
media: Vec<RawMedium>,
}
#[derive(Deserialize)]
struct RawGroup {
id: String,
#[serde(default)]
genres: Vec<Genre>,
}
#[derive(Deserialize)]
struct RawMedium {
position: Option<u32>,
#[serde(default)]
tracks: Vec<RawTrack>,
}
#[derive(Deserialize)]
struct RawTrack {
#[serde(default)]
id: String,
position: Option<u32>,
#[serde(default)]
title: String,
length: Option<u32>,
#[serde(rename = "artist-credit", default)]
artist_credit: Vec<Credit>,
recording: Option<RawRecording>,
}
#[derive(Deserialize)]
struct RawRecording {
#[serde(default)]
id: String,
length: Option<u32>,
}
/// 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>)]) -> String {
parts
.iter()
.filter_map(|(field, value)| value.as_ref().map(|v| format!("{field}:{v}")))
.collect::<Vec<_>>()
.join(" AND ")
}
fn non_empty(s: Option<&str>) -> Option<String> {
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<u32>,
limit: u32,
) -> Result<Vec<ReleaseHit>, 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<ReleaseSearch> = 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<Vec<RecordingHit>, 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<RecordingSearch> = 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<Option<Release>, NetError> {
check_id(id)?;
let url = format!("{}/ws/2/release/{id}", self.musicbrainz);
let raw: Option<RawRelease> = 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<String> = 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,
}
}

View file

@ -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<ReleaseHit { id, title, artist, date, country, track_count, release_group_id, score }>`, `search_recordings(title, artist, album, limit) -> Vec<RecordingHit { id, title, artist, length_ms, releases, score }>`, `release(id) -> Option<Release { id, title, artist, artist_ids, date, country, release_group_id, genres, disc_total, tracks: Vec<Track { disc, position, disc_track_count, title, artist, artist_ids, recording_id, track_id, length_ms }> }>`, `front_cover(release_id) -> Option<Cover>` (front-500, redirects followed, JPEG/PNG only; same `Cover` as S019). `match_tracks(&[FileInfo { disc, track, title, duration_ms }], &Release) -> Vec<Option<usize>>` (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/<version> ( … )`, 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
-