From ec1c73e1283c9522f7d6a0f59f73cf4038d76b9e Mon Sep 17 00:00:00 2001 From: hex-ronin Date: Wed, 18 Nov 2026 18:39:09 -0800 Subject: [PATCH 1/5] Fix 400 Bad Request errors with lrclib API and comma-separated --ignore - Replace audiotags with lofty so audio duration is read in seconds rather than ID3v2 TLEN milliseconds - Parse comma-separated --ignore values with clap value_delimiter - Guard /api/get against empty track_name/artist_name and out-of-range duration (1..=3600s), allowing --search fallback - Filter search candidates for non-empty syncedLyrics even when duration is absent - Include HTTP response body in lrclib API error messages --- Cargo.toml | 2 +- src/main.rs | 100 ++++++++++++++++++++++++++++++++++++---------------- 2 files changed, 71 insertions(+), 31 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 77c3018..93d9d96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ readme = "README.md" [dependencies] anyhow = "1.0.93" -audiotags = "0.5.0" +lofty = "0.25" clap = { version = "4.5.20", features = ["derive"] } ignore = "0.4.23" mime_guess = "2.0.5" diff --git a/src/main.rs b/src/main.rs index aa1ffe0..b0817cc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use anyhow::bail; -use audiotags::Tag; +use lofty::prelude::*; +use lofty::probe::Probe; use clap::Parser; use ignore::{DirEntry, WalkBuilder}; use serde::{Serialize, Deserialize}; @@ -15,7 +16,7 @@ pub struct CliConfig { pub hidden: bool, #[arg(short = 'f', long = "force", default_value_t = false, help = "overwrite existing lrc files")] pub force: bool, - #[arg(short = 'i', long = "ignore", value_parser, num_args = 1, help = "ignore the follow properties when searching lrclib by not sending them, comma seperated")] + #[arg(short = 'i', long = "ignore", value_parser, value_delimiter = ',', help = "ignore the follow properties when searching lrclib by not sending them, comma seperated")] pub ignore: Vec, #[arg(short = 's', long = "search", default_value_t = false, help = "use searching on lrclib as a fallback")] pub search: bool, @@ -64,22 +65,30 @@ impl LrclibQuery { query } + pub fn can_use_get(&self) -> bool { + !self.track_name.trim().is_empty() && !self.artist_name.trim().is_empty() + } + pub fn to_get_query(&self) -> Vec<(String, String)> { let mut query = self.to_search_query(); if let Some(duration) = &self.duration { - query.push(("duration".to_string(), duration.to_string())); + if duration.is_finite() && (1.0..=3600.0).contains(duration) { + query.push(("duration".to_string(), duration.to_string())); + } } query } pub fn to_search_query(&self) -> Vec<(String, String)> { let mut query = Vec::new(); - query.push(("track_name".to_string(), self.track_name.clone())); - if self.artist_name.len() > 0 { - query.push(("artist_name".to_string(), self.artist_name.clone())); + query.push(("track_name".to_string(), self.track_name.trim().to_string())); + if !self.artist_name.trim().is_empty() { + query.push(("artist_name".to_string(), self.artist_name.trim().to_string())); } if let Some(album_name) = &self.album_name { - query.push(("album_name".to_string(), album_name.clone())); + if !album_name.trim().is_empty() { + query.push(("album_name".to_string(), album_name.trim().to_string())); + } } query } @@ -120,10 +129,14 @@ impl LrcLibClient { } pub async fn get(&self, query: &LrclibQuery) -> anyhow::Result> { + if !query.can_use_get() { + return Ok(None); + } let url = format!("{}/api/get" ,self.url); let request_builder = self.client.get(url).query(&query.to_get_query()); let response = request_builder.send().await?; - if response.status().is_success() { + let status = response.status(); + if status.is_success() { let body = response.text().await?; match serde_json::from_str::(&body) { Ok(item) => Ok(Some(item)), @@ -132,10 +145,16 @@ impl LrcLibClient { }, } } else { - if response.status() == reqwest::StatusCode::NOT_FOUND { + if status == reqwest::StatusCode::NOT_FOUND { Ok(None) } else { - Err(anyhow::anyhow!("Error getting lrclib item: {}", response.status())) + let body = response.text().await.unwrap_or_default(); + let body = body.trim(); + if body.is_empty() { + Err(anyhow::anyhow!("Error getting lrclib item: {}", status)) + } else { + Err(anyhow::anyhow!("Error getting lrclib item: {} ({})", status, body)) + } } } } @@ -144,7 +163,8 @@ impl LrcLibClient { let url = format!("{}/api/search" ,self.url); let request_builder = self.client.get(url).query(&query.to_search_query()); let response = request_builder.send().await?; - if response.status().is_success() { + let status = response.status(); + if status.is_success() { let body = response.text().await?; match serde_json::from_str::>(&body) { Ok(items) => Ok(Some(items)), @@ -153,10 +173,16 @@ impl LrcLibClient { }, } } else { - if response.status() == reqwest::StatusCode::NOT_FOUND { + if status == reqwest::StatusCode::NOT_FOUND { Ok(None) } else { - Err(anyhow::anyhow!("Error getting lrclib item: {}", response.status())) + let body = response.text().await.unwrap_or_default(); + let body = body.trim(); + if body.is_empty() { + Err(anyhow::anyhow!("Error getting lrclib item: {}", status)) + } else { + Err(anyhow::anyhow!("Error getting lrclib item: {} ({})", status, body)) + } } } } @@ -208,23 +234,36 @@ async fn main() { continue; } // read file - match Tag::new().read_from_path(entry.path()) { - Ok(tag) => { + match Probe::open(entry.path()).and_then(|p| p.read()) { + Ok(tagged_file) => { let mut album_name: Option = None; let mut track_name = "".to_string(); let mut artist_name = "".to_string(); - if let Some(album) = tag.album() { - album_name = Some(album.title.to_string()); - } - if let Some(title) = tag.title() { - track_name = title.to_string(); + if let Some(tag) = tagged_file.primary_tag().or_else(|| tagged_file.first_tag()) { + if let Some(album) = tag.album() { + if !album.trim().is_empty() { + album_name = Some(album.trim().to_string()); + } + } + if let Some(title) = tag.title() { + track_name = title.trim().to_string(); + } + let artists: Vec<&str> = tag.get_strings(ItemKey::TrackArtist).map(str::trim).filter(|s| !s.is_empty()).collect(); + if !artists.is_empty() { + artist_name = artists.join(", "); + } else if let Some(artist) = tag.artist() { + artist_name = artist.trim().to_string(); + } } - if let Some(artists) = tag.artists() { - artist_name = artists.join(", "); + if track_name.is_empty() { + println!("Skipping {}: missing track title metadata", entry.path().display()); + continue; } - let duration: Option = match tag.duration() { - Some(duration) => Some(duration as f32), - None => None, + let duration_secs = tagged_file.properties().duration().as_secs_f64(); + let duration: Option = if duration_secs.is_finite() && duration_secs > 0.0 { + Some(duration_secs as f32) + } else { + None }; let mut lrc_query = LrclibQuery { track_name: track_name.clone(), @@ -238,6 +277,9 @@ async fn main() { if config.ignore.contains(&"album_name".to_string()) || config.ignore.contains(&"album".to_string()) { lrc_query.remove_album_name(); } + if config.search && (config.ignore.contains(&"artist_name".to_string()) || config.ignore.contains(&"artist".to_string())) { + lrc_query.artist_name.clear(); + } match client.get(&lrc_query).await { Ok(Some(lrc_item)) => { if let Some(synced_lyrics) = &lrc_item.syncedLyrics { @@ -265,7 +307,9 @@ async fn main() { if lrc_items.len() == 0 { println!("Did not find lrc for (no results) {}",entry.path().display()); } else { - let mut canidates = lrc_items; + let mut canidates: Vec = lrc_items.into_iter().filter(|item| { + item.syncedLyrics.is_some() && !item.syncedLyrics.as_ref().unwrap().is_empty() + }).collect(); if let Some(duration) = &lrc_query.duration { // sort by closed to target duration canidates.sort_by(|a, b| { @@ -275,10 +319,6 @@ async fn main() { let b_delta = b_duration - duration; return a_delta.abs().partial_cmp(&b_delta.abs()).unwrap(); }); - - canidates = canidates.into_iter().filter(|item| { - return item.syncedLyrics.is_some() && item.syncedLyrics.as_ref().unwrap().len() > 0; - }).collect(); if config.tolerance > 0.0 { canidates = canidates.into_iter().filter(|item| { From 5d8caf317a0503c4532d5788b363b97a04b03e2d Mon Sep 17 00:00:00 2001 From: hex-ronin Date: Wed, 18 Nov 2026 18:59:23 -0800 Subject: [PATCH 2/5] Add --delay option to throttle requests between lrclib API calls Adds -d/--delay (default 500ms, per lrclib.net request throttling guidance) to sleep between consecutive HTTP requests and avoid 429 Too Many Requests responses. Pass --delay 0 to disable. --- src/main.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/main.rs b/src/main.rs index b0817cc..ccb65c3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,6 +22,8 @@ pub struct CliConfig { pub search: bool, #[arg(short = 't', long = "tolerance", default_value_t = 5.0, help = "tolerance in seconds for searching lrclib")] pub tolerance: f32, + #[arg(short = 'd', long = "delay", default_value_t = 500, help = "delay in milliseconds between lrclib requests")] + pub delay: u64, } static DEFAULT_USER_AGENT: &str = concat!( @@ -37,6 +39,8 @@ static DEFAULT_USER_AGENT: &str = concat!( pub struct LrcLibClient { pub url: String, pub client: reqwest::Client, + pub delay_ms: u64, + has_requested: std::sync::atomic::AtomicBool, } pub struct LrclibQuery { @@ -121,6 +125,8 @@ impl LrcLibClient { Self { url: "https://lrclib.net".to_string(), client: reqwest::Client::builder().default_headers(headers).user_agent(DEFAULT_USER_AGENT).build().expect("Failed to create reqwest client"), + delay_ms: 0, + has_requested: std::sync::atomic::AtomicBool::new(false), } } @@ -128,10 +134,21 @@ impl LrcLibClient { self.url = url.to_string(); } + pub fn set_delay_ms(&mut self, delay_ms: u64) { + self.delay_ms = delay_ms; + } + + async fn throttle(&self) { + if self.delay_ms > 0 && self.has_requested.swap(true, std::sync::atomic::Ordering::Relaxed) { + tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await; + } + } + pub async fn get(&self, query: &LrclibQuery) -> anyhow::Result> { if !query.can_use_get() { return Ok(None); } + self.throttle().await; let url = format!("{}/api/get" ,self.url); let request_builder = self.client.get(url).query(&query.to_get_query()); let response = request_builder.send().await?; @@ -160,6 +177,7 @@ impl LrcLibClient { } pub async fn search(&self, query: &LrclibQuery) -> anyhow::Result>> { + self.throttle().await; let url = format!("{}/api/search" ,self.url); let request_builder = self.client.get(url).query(&query.to_search_query()); let response = request_builder.send().await?; @@ -215,6 +233,7 @@ async fn main() { let config = CliConfig::parse(); let mut client = LrcLibClient::new(&config.lrclib_url); client.set_url(&config.lrclib_url); + client.set_delay_ms(config.delay); for result in WalkBuilder::new(".").hidden(config.hidden).add_custom_ignore_filename(".lrcsyncignore").build() { match result { Ok(entry) => { From dee4db75bd48b1beb6a906c3bd51e46efc6b48e8 Mon Sep 17 00:00:00 2001 From: hex-ronin Date: Wed, 18 Nov 2026 19:02:46 -0800 Subject: [PATCH 3/5] Fix compiler warnings in src/main.rs - Use url parameter in LrcLibClient::new - Remove unused config parameter from write_lrc_for_file - Rename LrclibItem fields to snake_case with serde camelCase --- src/main.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index ccb65c3..3d1113c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,15 +107,16 @@ impl LrclibQuery { } #[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] pub struct LrclibItem { pub id: u32, - pub trackName: String, - pub artistName: String, - pub albumName: String, + pub track_name: String, + pub artist_name: String, + pub album_name: String, pub duration: f32, pub instrumental: bool, - pub plainLyrics: Option, - pub syncedLyrics: Option, + pub plain_lyrics: Option, + pub synced_lyrics: Option, } impl LrcLibClient { @@ -123,7 +124,7 @@ impl LrcLibClient { let mut headers = reqwest::header::HeaderMap::new(); headers.insert("Lrclib-Client", DEFAULT_USER_AGENT.parse().unwrap()); Self { - url: "https://lrclib.net".to_string(), + url: url.to_string(), client: reqwest::Client::builder().default_headers(headers).user_agent(DEFAULT_USER_AGENT).build().expect("Failed to create reqwest client"), delay_ms: 0, has_requested: std::sync::atomic::AtomicBool::new(false), @@ -206,7 +207,7 @@ impl LrcLibClient { } } -pub async fn write_lrc_for_file(entry: &DirEntry, synced_lyrics: &str, config: &CliConfig) -> anyhow::Result<()> { +pub async fn write_lrc_for_file(entry: &DirEntry, synced_lyrics: &str) -> anyhow::Result<()> { let lrc_path = entry.path().with_extension("lrc"); match File::create(lrc_path).await { @@ -301,10 +302,10 @@ async fn main() { } match client.get(&lrc_query).await { Ok(Some(lrc_item)) => { - if let Some(synced_lyrics) = &lrc_item.syncedLyrics { + if let Some(synced_lyrics) = &lrc_item.synced_lyrics { println!("Found synced lrc for {}", entry.path().display()); // write to file with extension changed to .lrc - match write_lrc_for_file(&entry, synced_lyrics, &config).await { + match write_lrc_for_file(&entry, synced_lyrics).await { Ok(_) => {}, Err(err) => { println!("Error in saving lrc {}: {}",entry.path().display(), err); @@ -327,7 +328,7 @@ async fn main() { println!("Did not find lrc for (no results) {}",entry.path().display()); } else { let mut canidates: Vec = lrc_items.into_iter().filter(|item| { - item.syncedLyrics.is_some() && !item.syncedLyrics.as_ref().unwrap().is_empty() + item.synced_lyrics.is_some() && !item.synced_lyrics.as_ref().unwrap().is_empty() }).collect(); if let Some(duration) = &lrc_query.duration { // sort by closed to target duration @@ -353,7 +354,7 @@ async fn main() { println!("Searched lrc (found {}secs vs actual {}secs out of {} filtered results) for {}",canidates[0].duration,lrc_query.duration.unwrap_or(-1.0), canidates.len(), entry.path().display()); // write to file with extension changed to .lrc // TODO: manual duration tolerance? - match write_lrc_for_file(&entry, &canidates[0].syncedLyrics.as_ref().unwrap(), &config).await { + match write_lrc_for_file(&entry, canidates[0].synced_lyrics.as_ref().unwrap()).await { Ok(_) => {}, Err(err) => { println!("Error in saving lrc {}: {}",entry.path().display(), err); From c10543a990b5507ec1da8cb33cfc5dd3578feabb Mon Sep 17 00:00:00 2001 From: hex-ronin Date: Wed, 18 Nov 2026 19:06:21 -0800 Subject: [PATCH 4/5] Default --delay to 0ms for backwards compatibility --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 3d1113c..91a860b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,7 +22,7 @@ pub struct CliConfig { pub search: bool, #[arg(short = 't', long = "tolerance", default_value_t = 5.0, help = "tolerance in seconds for searching lrclib")] pub tolerance: f32, - #[arg(short = 'd', long = "delay", default_value_t = 500, help = "delay in milliseconds between lrclib requests")] + #[arg(short = 'd', long = "delay", default_value_t = 0, help = "delay in milliseconds between lrclib requests")] pub delay: u64, } From ff02b862b7c40bac571f404473130844f169a816 Mon Sep 17 00:00:00 2001 From: hex-ronin Date: Thu, 19 Nov 2026 10:35:16 -0800 Subject: [PATCH 5/5] Handle nullable fields in lrclib API responses LRCLIB TrackResponse can return null for duration, trackName, artistName, and albumName (and uses i64 for id). Make those fields Option in LrclibItem and handle missing durations cleanly when sorting/filtering search candidates. --- src/main.rs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index 91a860b..764da6b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -109,11 +109,12 @@ impl LrclibQuery { #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct LrclibItem { - pub id: u32, - pub track_name: String, - pub artist_name: String, - pub album_name: String, - pub duration: f32, + pub id: i64, + pub track_name: Option, + pub artist_name: Option, + pub album_name: Option, + pub duration: Option, + #[serde(default)] pub instrumental: bool, pub plain_lyrics: Option, pub synced_lyrics: Option, @@ -333,25 +334,21 @@ async fn main() { if let Some(duration) = &lrc_query.duration { // sort by closed to target duration canidates.sort_by(|a, b| { - let a_duration = a.duration as f32; - let b_duration = b.duration as f32; - let a_delta = a_duration - duration; - let b_delta = b_duration - duration; - return a_delta.abs().partial_cmp(&b_delta.abs()).unwrap(); + let a_delta = a.duration.map(|d| (d - duration).abs()).unwrap_or(f32::INFINITY); + let b_delta = b.duration.map(|d| (d - duration).abs()).unwrap_or(f32::INFINITY); + a_delta.total_cmp(&b_delta) }); if config.tolerance > 0.0 { canidates = canidates.into_iter().filter(|item| { - let item_duration = item.duration as f32; - let delta = item_duration - duration; - return delta.abs() < config.tolerance; + item.duration.map(|d| (d - duration).abs() < config.tolerance).unwrap_or(false) }).collect(); } } if canidates.len() > 0 { - println!("Searched lrc (found {}secs vs actual {}secs out of {} filtered results) for {}",canidates[0].duration,lrc_query.duration.unwrap_or(-1.0), canidates.len(), entry.path().display()); + println!("Searched lrc (found {}secs vs actual {}secs out of {} filtered results) for {}",canidates[0].duration.unwrap_or(-1.0),lrc_query.duration.unwrap_or(-1.0), canidates.len(), entry.path().display()); // write to file with extension changed to .lrc // TODO: manual duration tolerance? match write_lrc_for_file(&entry, canidates[0].synced_lyrics.as_ref().unwrap()).await {