diff --git a/src/app.rs b/src/app.rs index e38c304..85449de 100644 --- a/src/app.rs +++ b/src/app.rs @@ -283,6 +283,7 @@ impl App { Msg::CoverFull { token, bytes } => crate::ui::dialogs::on_cover_full(self, token, bytes), Msg::MbResults { token, items } => crate::ui::dialogs::on_mb_results(self, token, items), Msg::ConnectLastFm(r) => crate::ui::dialogs::on_lastfm_connected(self, r), + Msg::ConnectListenBrainz(r) => crate::ui::dialogs::on_listenbrainz_connected(self, r), } } } diff --git a/src/bus.rs b/src/bus.rs index 978a425..f12c455 100644 --- a/src/bus.rs +++ b/src/bus.rs @@ -33,6 +33,8 @@ pub enum Msg { /// Result of a background job the UI shows as a toast. Done { toast: String }, ConnectLastFm(Result<(String, String), String>), + /// (token, user name) after checking a ListenBrainz token. + ConnectListenBrainz(Result<(String, String), String>), } #[derive(Clone, Debug, Default)] diff --git a/src/config.rs b/src/config.rs index a41c578..eac7a65 100644 --- a/src/config.rs +++ b/src/config.rs @@ -111,6 +111,7 @@ fn defaults() -> BTreeMap<&'static str, Value> { ("lastfm/user", json!("")), ("listenbrainz/enabled", json!(false)), ("listenbrainz/token", json!("")), + ("listenbrainz/user", json!("")), ("online/auto_lyrics", json!(true)), ("online/auto_covers", json!(true)), ("online/save_covers_to_folder", json!(false)), diff --git a/src/library.rs b/src/library.rs index 65fabf6..cd270f1 100644 --- a/src/library.rs +++ b/src/library.rs @@ -143,6 +143,11 @@ impl Library { con.execute_batch(SCHEMA).expect("create schema"); let lib = Library { con: Mutex::new(con), scanning: Arc::new(AtomicBool::new(false)), abort: Arc::new(AtomicBool::new(false)) }; let empty = lib.con().query_row("SELECT 1 FROM radio LIMIT 1", [], |_| Ok(())).is_err(); + if lib.kv("mbid_recording_fix").is_none() { + // Older builds stored the release-track MBID as mb_trackid; re-read those files on the next scan. + let _ = lib.con().execute("UPDATE songs SET mtime=0 WHERE mb_trackid<>''", []); + lib.set_kv("mbid_recording_fix", "1"); + } if empty && lib.kv("radio_seeded").is_none() { let c = lib.con(); for (i, (name, url)) in DEFAULT_RADIO.iter().enumerate() { diff --git a/src/online.rs b/src/online.rs index 8fd0820..ecb68b8 100644 --- a/src/online.rs +++ b/src/online.rs @@ -42,19 +42,44 @@ pub fn http_get_bytes(url: &str) -> Res> { resp.body_mut().with_config().limit(40 * 1024 * 1024).read_to_vec().map_err(|e| e.to_string()) } -pub fn http_post_form(url: &str, form: &[(String, String)]) -> Res { - let items: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); - let mut resp = agent().post(url).send_form(items).map_err(|e| e.to_string())?; - resp.body_mut().read_json::().map_err(|e| e.to_string()) +/// Agent that hands back 4xx/5xx bodies instead of erroring (Last.fm and ListenBrainz put the reason there). +fn agent_raw() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(20))) + .user_agent(USER_AGENT) + .http_status_as_error(false) + .build() + .into() } -pub fn http_post_json(url: &str, body: &Value, headers: &[(&str, &str)]) -> Res { - let mut req = agent().post(url); +fn read_st(mut resp: ureq::http::Response) -> (u16, Value) { + let st = resp.status().as_u16(); + (st, resp.body_mut().read_json::().unwrap_or(Value::Null)) +} + +/// GET returning (status, json body); Err only for network failures. +pub fn http_get_json_st(url: &str, params: &[(&str, String)], headers: &[(&str, &str)]) -> Res<(u16, Value)> { + let mut req = agent_raw().get(url); + for (k, v) in params { + req = req.query(*k, v); + } for (k, v) in headers { req = req.header(*k, *v); } - let mut resp = req.send_json(body).map_err(|e| e.to_string())?; - resp.body_mut().read_json::().map_err(|e| e.to_string()) + req.call().map(read_st).map_err(|e| e.to_string()) +} + +pub fn http_post_form_st(url: &str, form: &[(String, String)]) -> Res<(u16, Value)> { + let items: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + agent_raw().post(url).send_form(items).map(read_st).map_err(|e| e.to_string()) +} + +pub fn http_post_json_st(url: &str, body: &Value, headers: &[(&str, &str)]) -> Res<(u16, Value)> { + let mut req = agent_raw().post(url); + for (k, v) in headers { + req = req.header(*k, *v); + } + req.send_json(body).map(read_st).map_err(|e| e.to_string()) } static MB_LAST: LazyLock> = LazyLock::new(|| Mutex::new(Instant::now() - Duration::from_secs(5))); diff --git a/src/scrobble.rs b/src/scrobble.rs index 7de7c5e..7e219b6 100644 --- a/src/scrobble.rs +++ b/src/scrobble.rs @@ -3,7 +3,7 @@ use crate::bus::{Bus, Msg}; use crate::config::{settings, PATHS}; use crate::library::{song_from_json, song_to_json}; -use crate::online::{http_get_json, http_post_form, http_post_json, lastfm_key}; +use crate::online::{http_get_json_st, http_post_form_st, http_post_json_st, lastfm_key}; use crate::song::Song; use serde_json::{json, Value}; use std::sync::{Arc, Mutex}; @@ -26,7 +26,13 @@ fn sign(params: &mut Vec<(String, String)>) { params.push(("api_sig".into(), sig)); } -pub fn lfm_call(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { +/// Last.fm error codes that mean the saved session no longer works. +const LFM_AUTH_ERRORS: [i64; 3] = [4, 9, 14]; +/// Last.fm error codes worth retrying later (offline, temporary, rate limit). +const LFM_RETRY_ERRORS: [i64; 3] = [11, 16, 29]; + +/// Last.fm call; on failure gives (error code, message). Code 0 = network/HTTP problem. +pub fn lfm_raw(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { let (key, _) = lastfm_key(); let mut p: Vec<(String, String)> = vec![("method".into(), method.into()), ("api_key".into(), key)]; p.extend(params.into_iter().filter(|(_, v)| !v.is_empty())); @@ -35,18 +41,38 @@ pub fn lfm_call(method: &str, params: Vec<(String, String)>, post: bool, auth: b } sign(&mut p); p.push(("format".into(), "json".into())); - let res = if post { - http_post_form(LFM_API, &p)? + let (st, res) = if post { + http_post_form_st(LFM_API, &p) } else { let q: Vec<(&str, String)> = p.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); - http_get_json(LFM_API, &q, &[])? - }; - if let Some(err) = res.get("error") { - return Err(format!("Last.fm: {}", res["message"].as_str().unwrap_or(&err.to_string()))); + http_get_json_st(LFM_API, &q, &[]) + } + .map_err(|e| (0, format!("Last.fm: {e}")))?; + if let Some(code) = res.get("error").and_then(Value::as_i64) { + return Err((code, format!("Last.fm: {}", res["message"].as_str().unwrap_or("error")))); + } + if st >= 400 { + return Err((0, format!("Last.fm: HTTP {st}"))); } Ok(res) } +pub fn lfm_call(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { + lfm_raw(method, params, post, auth).map_err(|(code, msg)| { + if auth && LFM_AUTH_ERRORS.contains(&code) { + lfm_session_expired() + } else { + msg + } + }) +} + +/// Forget a dead session so we stop hammering Last.fm; queued scrobbles wait for the next login. +fn lfm_session_expired() -> String { + settings().set("lastfm/session", ""); + "Last.fm logged Mulberry out. Log in again in Settings › Scrobbling; queued scrobbles are kept.".into() +} + pub fn begin_auth() -> Result { let res = lfm_call("auth.getToken", vec![], false, false)?; res["token"].as_str().map(String::from).ok_or_else(|| "no token".into()) @@ -95,52 +121,111 @@ pub fn start_login(bus: Bus) -> Result<(), String> { Ok(()) } -fn track_params(s: &Song, idx: Option) -> Vec<(String, String)> { - let sfx = idx.map(|i| format!("[{i}]")).unwrap_or_default(); - let (mut artist, mut title) = (s.display_artist(), s.display_title()); +/// Artist and title, split from "Artist - Title" for radio streams. +fn artist_title(s: &Song) -> (String, String) { if s.is_stream() && s.stream_title.contains(" - ") { let (a, t) = s.stream_title.split_once(" - ").unwrap(); - artist = a.trim().into(); - title = t.trim().into(); + return (a.trim().into(), t.trim().into()); } + (s.display_artist(), s.display_title()) +} + +/// MusicBrainz ids / ISRC read fresh from a local file (not for cue sheet tracks, whose tags describe the whole file). +fn file_ids(s: &Song) -> serde_json::Map { + if s.is_local() && !s.is_cd() && s.end <= 0.0 { + crate::tags::scrobble_ids(&s.path()) + } else { + Default::default() + } +} + +fn recording_mbid(s: &Song, ids: &serde_json::Map) -> String { + ids.get("recording_mbid").and_then(Value::as_str).map(String::from).unwrap_or_else(|| s.mb_trackid.clone()) +} + +fn track_params(s: &Song, idx: Option) -> Vec<(String, String)> { + let sfx = idx.map(|i| format!("[{i}]")).unwrap_or_default(); + let (artist, title) = artist_title(s); let mut p = vec![(format!("artist{sfx}"), artist), (format!("track{sfx}"), title)]; if !s.album.is_empty() && !s.is_stream() { p.push((format!("album{sfx}"), s.album.clone())); } - if !s.albumartist.is_empty() && s.albumartist != s.artist { + if !s.albumartist.is_empty() && !s.is_stream() { p.push((format!("albumArtist{sfx}"), s.albumartist.clone())); } - if s.track > 0 { + if s.track > 0 && !s.is_stream() { p.push((format!("trackNumber{sfx}"), s.track.to_string())); } if s.duration() > 0.0 { p.push((format!("duration{sfx}"), (s.duration() as i64).to_string())); } - if !s.mb_trackid.is_empty() { - p.push((format!("mbid{sfx}"), s.mb_trackid.clone())); + let mbid = recording_mbid(s, &file_ids(s)); + if !mbid.is_empty() { + p.push((format!("mbid{sfx}"), mbid)); + } + if idx.is_some() { + p.push((format!("chosenByUser{sfx}"), if s.is_stream() { "0" } else { "1" }.into())); } p } +fn host_of(url: &str) -> String { + url.split("://").nth(1).unwrap_or("").split(['/', ':', '?']).next().unwrap_or("").trim_start_matches("www.").to_string() +} + +/// Full ListenBrainz listen: https://listenbrainz.readthedocs.io/en/latest/users/json.html fn lb_payload(s: &Song, ts: Option) -> Value { - let (mut artist, mut title) = (s.display_artist(), s.display_title()); - if s.is_stream() && s.stream_title.contains(" - ") { - let (a, t) = s.stream_title.split_once(" - ").unwrap(); - artist = a.trim().into(); - title = t.trim().into(); + let (artist, title) = artist_title(s); + let ids = file_ids(s); + let mut info = json!({ + "media_player": "Mulberry", + "media_player_version": crate::config::VERSION, + "submission_client": "Mulberry", + "submission_client_version": crate::config::VERSION, + }); + let a = info.as_object_mut().unwrap(); + for (k, v) in &ids { + a.insert(k.clone(), v.clone()); + } + let rec = recording_mbid(s, &ids); + if !rec.is_empty() { + a.insert("recording_mbid".into(), json!(rec)); + } + if !a.contains_key("release_mbid") && !s.mb_albumid.is_empty() { + a.insert("release_mbid".into(), json!(s.mb_albumid)); } - let mut info = json!({"media_player": "Mulberry", "submission_client": "Mulberry", "submission_client_version": crate::config::VERSION}); if s.duration() > 0.0 { - info["duration_ms"] = json!((s.duration() * 1000.0) as i64); + a.insert("duration_ms".into(), json!((s.duration() * 1000.0) as i64)); } - if !s.mb_trackid.is_empty() { - info["recording_mbid"] = json!(s.mb_trackid); - } - if !s.mb_albumid.is_empty() { - info["release_mbid"] = json!(s.mb_albumid); + if s.is_stream() { + a.insert("origin_url".into(), json!(s.url)); + let host = host_of(&s.url); + if !host.is_empty() { + a.insert("music_service".into(), json!(host)); + } + } else { + if s.track > 0 { + a.insert("tracknumber".into(), json!(s.track)); + } + if s.disc > 0 { + a.insert("discnumber".into(), json!(s.disc)); + } + if !s.albumartist.is_empty() { + a.insert("release_artist_name".into(), json!(s.albumartist)); + } + let tags: Vec<&str> = s.genre.split([';', '/', ',']).map(str::trim).filter(|g| !g.is_empty()).collect(); + if !tags.is_empty() { + a.insert("tags".into(), json!(tags)); + } + if let Some(i) = s.comment.find("open.spotify.com/track/") { + let id: String = s.comment[i + 23..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); + if !id.is_empty() { + a.insert("spotify_id".into(), json!(format!("https://open.spotify.com/track/{id}"))); + } + } } let mut meta = json!({"artist_name": artist, "track_name": title, "additional_info": info}); - if !s.album.is_empty() { + if !s.album.is_empty() && !s.is_stream() { meta["release_name"] = json!(s.album); } let mut p = json!({"track_metadata": meta}); @@ -150,9 +235,32 @@ fn lb_payload(s: &Song, ts: Option) -> Value { p } -fn lb_submit(kind: &str, payload: Vec) -> Result { +const LB_API: &str = "https://api.listenbrainz.org/1"; + +/// POST to ListenBrainz; Err gives (HTTP status, message). Status 0 = network problem. +fn lb_post(path: &str, body: &Value) -> Result { let token = format!("Token {}", settings().get_str("listenbrainz/token")); - http_post_json("https://api.listenbrainz.org/1/submit-listens", &json!({"listen_type": kind, "payload": payload}), &[("Authorization", &token)]) + let (st, res) = http_post_json_st(&format!("{LB_API}/{path}"), body, &[("Authorization", &token)]).map_err(|e| (0, format!("ListenBrainz: {e}")))?; + if st >= 400 { + let msg = res["error"].as_str().map(String::from).unwrap_or_else(|| format!("HTTP {st}")); + return Err((st, format!("ListenBrainz: {msg}"))); + } + Ok(res) +} + +fn lb_submit(kind: &str, payload: Vec) -> Result { + lb_post("submit-listens", &json!({"listen_type": kind, "payload": payload})) +} + +/// Check a user token; gives the ListenBrainz user name. +pub fn lb_validate(token: &str) -> Result { + let auth = format!("Token {}", token.trim()); + let (_, res) = http_get_json_st(&format!("{LB_API}/validate-token"), &[], &[("Authorization", &auth)])?; + if res["valid"].as_bool() == Some(true) { + Ok(res["user_name"].as_str().unwrap_or("").to_string()) + } else { + Err(res["message"].as_str().unwrap_or("Token not valid").to_string()) + } } pub fn lfm_on() -> bool { @@ -186,6 +294,18 @@ impl Scrobbler { self.cache.lock().unwrap().len() } + /// Queued scrobbles for one service ("lastfm" / "listenbrainz"). + pub fn pending_for(&self, svc: &str) -> usize { + self.cache.lock().unwrap().iter().filter(|e| e["svc"] == svc).count() + } + + /// Drop the queue of a service the user disconnected. + pub fn purge(&self, svc: &str) { + let mut c = self.cache.lock().unwrap(); + c.retain(|e| e["svc"] != svc); + Self::save(&c); + } + /// Announce "now playing" (also when playback resumes after a long pause). pub fn track_started(&mut self, s: &Song) { self.announced = Some((s.key(), Instant::now())); @@ -203,7 +323,7 @@ impl Scrobbler { } if lb_on() { std::thread::spawn(move || { - if let Err(e) = lb_submit("playing_now", vec![lb_payload(&song, None)]) { + if let Err((_, e)) = lb_submit("playing_now", vec![lb_payload(&song, None)]) { bus.toast(e); } }); @@ -281,46 +401,141 @@ impl Scrobbler { } }); } - if lb_on() && !s.mb_trackid.is_empty() { - let mbid = s.mb_trackid.clone(); + if lb_on() { + let mbid = recording_mbid(s, &file_ids(s)); + if mbid.is_empty() { + if loved { + bus.toast("ListenBrainz needs a MusicBrainz recording id to love a track"); + } + return; + } std::thread::spawn(move || { - let token = format!("Token {}", settings().get_str("listenbrainz/token")); - let _ = http_post_json("https://api.listenbrainz.org/1/feedback/recording-feedback", &json!({"recording_mbid": mbid, "score": if loved { 1 } else { 0 }}), &[("Authorization", &token)]); + match lb_post("feedback/recording-feedback", &json!({"recording_mbid": mbid, "score": if loved { 1 } else { 0 }})) { + Ok(_) => bus.toast(if loved { "Loved on ListenBrainz" } else { "Unloved on ListenBrainz" }), + Err((_, e)) => bus.toast(e), + } }); } } } +/// Send queued scrobbles. Each service goes on its own, so one failing never blocks the other. fn flush_work(cache: &Arc>>) -> Result { let pending: Vec = cache.lock().unwrap().clone(); let svc = |e: &Value, n: &str| e["svc"] == n; - let lfm: Vec<&Value> = pending.iter().filter(|e| svc(e, "lastfm")).take(50).collect(); - let lb: Vec<&Value> = pending.iter().filter(|e| svc(e, "listenbrainz")).take(100).collect(); - let mut sent = 0; - let mut done: Vec = vec![]; let song_of = |e: &Value| { let mut s = song_from_json(&e["song"]); s.stream_title = e["stream_title"].as_str().unwrap_or("").into(); s }; + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + let mut sent = 0; + let mut done: Vec = vec![]; + let mut errors: Vec = vec![]; + + // Last.fm refuses scrobbles older than 14 days. + let (old, lfm): (Vec<&Value>, Vec<&Value>) = pending.iter().filter(|e| svc(e, "lastfm")).partition(|e| now - e["ts"].as_i64().unwrap_or(now) > 14 * 86400); + done.extend(old.into_iter().cloned()); if !lfm.is_empty() && lfm_on() { - let mut params = vec![]; - for (i, e) in lfm.iter().enumerate() { - params.extend(track_params(&song_of(e), Some(i))); - params.push((format!("timestamp[{i}]"), e["ts"].to_string())); + for chunk in lfm.chunks(50) { + let mut params = vec![]; + for (i, e) in chunk.iter().enumerate() { + params.extend(track_params(&song_of(e), Some(i))); + params.push((format!("timestamp[{i}]"), e["ts"].to_string())); + } + match lfm_raw("track.scrobble", params, true, true) { + Ok(_) => { + sent += chunk.len(); + done.extend(chunk.iter().map(|e| (*e).clone())); + } + Err((code, _)) if LFM_AUTH_ERRORS.contains(&code) => { + errors.push(lfm_session_expired()); + break; + } + Err((code, msg)) if code == 0 || LFM_RETRY_ERRORS.contains(&code) => { + errors.push(msg); + break; + } + Err((_, msg)) => { + // Last.fm rejected the data itself; retrying would loop forever. + errors.push(format!("{msg} (dropped {} scrobble(s))", chunk.len())); + done.extend(chunk.iter().map(|e| (*e).clone())); + } + } } - lfm_call("track.scrobble", params, true, true)?; - sent += lfm.len(); - done.extend(lfm.iter().map(|e| (*e).clone())); } + + let lb: Vec<&Value> = pending.iter().filter(|e| svc(e, "listenbrainz")).collect(); if !lb.is_empty() && lb_on() { - let payload: Vec = lb.iter().map(|e| lb_payload(&song_of(e), e["ts"].as_i64())).collect(); - lb_submit(if payload.len() > 1 { "import" } else { "single" }, payload)?; - sent += lb.len(); - done.extend(lb.iter().map(|e| (*e).clone())); + 'lb: for chunk in lb.chunks(100) { + let payload: Vec = chunk.iter().map(|e| lb_payload(&song_of(e), e["ts"].as_i64())).collect(); + match lb_submit(if payload.len() > 1 { "import" } else { "single" }, payload.clone()) { + Ok(_) => { + sent += chunk.len(); + done.extend(chunk.iter().map(|e| (*e).clone())); + } + Err((400, _)) => { + // One bad listen spoils a batch: send them one by one and drop the bad ones. + for (e, p) in chunk.iter().zip(payload) { + match lb_submit("single", vec![p]) { + Ok(_) => { + sent += 1; + done.push((*e).clone()); + } + Err((400, msg)) => { + errors.push(format!("{msg} (dropped 1 listen)")); + done.push((*e).clone()); + } + Err((_, msg)) => { + errors.push(msg); + break 'lb; + } + } + } + } + Err((401, _)) => { + errors.push("ListenBrainz token is not valid. Paste a new one in Settings › Scrobbling; queued listens are kept.".into()); + break; + } + Err((_, msg)) => { + errors.push(msg); + break; + } + } + } } + let mut c = cache.lock().unwrap(); c.retain(|e| !done.contains(e)); Scrobbler::save(&c); + if sent == 0 && !errors.is_empty() { + return Err(errors.join("\n")); + } + if let Some(e) = errors.first() { + eprintln!("scrobble: {e}"); + } Ok(sent) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lb_payload_has_ids_and_info() { + let mut s = Song::new("https://www.youtube.com/watch?v=x"); + s.stream_title = "Shinedown - Stranger Inside".into(); + let p = lb_payload(&s, Some(1_700_000_000)); + assert_eq!(p["track_metadata"]["artist_name"], "Shinedown"); + assert_eq!(p["track_metadata"]["additional_info"]["music_service"], "youtube.com"); + assert_eq!(p["listened_at"], 1_700_000_000); + // Real queued song, if this PC has one. + if let Ok(t) = std::fs::read_to_string(crate::config::PATHS.data.join("scrobble_cache.json")) { + let v: Vec = serde_json::from_str(&t).unwrap_or_default(); + if let Some(e) = v.last() { + println!("{}", serde_json::to_string_pretty(&lb_payload(&song_from_json(&e["song"]), e["ts"].as_i64())).unwrap()); + println!("{:?}", track_params(&song_from_json(&e["song"]), Some(0))); + } + } + } +} diff --git a/src/tags.rs b/src/tags.rs index 20a4ae3..0a72656 100644 --- a/src/tags.rs +++ b/src/tags.rs @@ -44,7 +44,7 @@ impl Field { Field::Track => "track", Field::Disc => "disc", Field::Comment => "comment", - Field::MbTrackId => "MusicBrainz track id", + Field::MbTrackId => "MusicBrainz recording id", Field::MbAlbumId => "MusicBrainz album id", } } @@ -169,7 +169,7 @@ pub fn read_song(path: &str) -> Option { s.disc = tag.disk().unwrap_or(0) as i64; s.rg_track = gain(tag.get_string(ItemKey::ReplayGainTrackGain)); s.rg_album = gain(tag.get_string(ItemKey::ReplayGainAlbumGain)); - s.mb_trackid = tag.get_string(ItemKey::MusicBrainzTrackId).unwrap_or("").chars().take(64).collect(); + s.mb_trackid = tag.get_string(ItemKey::MusicBrainzRecordingId).unwrap_or("").chars().take(64).collect(); s.mb_albumid = tag.get_string(ItemKey::MusicBrainzReleaseId).unwrap_or("").chars().take(64).collect(); if s.year == 0 { if let Some(y) = tag.get_string(ItemKey::RecordingDate) { @@ -300,6 +300,41 @@ pub fn jpeg_bytes(img: &image::DynamicImage, quality: u8) -> Vec { } // ------------------------------------------------------------------ lyrics +/// MusicBrainz ids and ISRC for scrobbling (ListenBrainz `additional_info` names). Read fresh from the file. +pub fn scrobble_ids(path: &str) -> serde_json::Map { + use serde_json::json; + let mut out = serde_json::Map::new(); + let Some(tagged) = lofty::read_from_path(path).ok() else { return out }; + let Some(tag) = tagged.primary_tag().or_else(|| tagged.first_tag()) else { return out }; + let many = |k: ItemKey| -> Vec { + let mut v: Vec = vec![]; + for s in tag.get_strings(k) { + for p in s.split(['/', ';', ',', '\0']) { + let p = p.trim(); + if p.len() == 36 && !v.iter().any(|x| x == p) { + v.push(p.to_string()); + } + } + } + v + }; + for (key, name) in [(ItemKey::MusicBrainzRecordingId, "recording_mbid"), (ItemKey::MusicBrainzReleaseId, "release_mbid"), (ItemKey::MusicBrainzReleaseGroupId, "release_group_mbid"), (ItemKey::MusicBrainzTrackId, "track_mbid")] { + if let Some(id) = many(key).into_iter().next() { + out.insert(name.into(), json!(id)); + } + } + for (key, name) in [(ItemKey::MusicBrainzArtistId, "artist_mbids"), (ItemKey::MusicBrainzReleaseArtistId, "release_artist_mbids"), (ItemKey::MusicBrainzWorkId, "work_mbids")] { + let v = many(key); + if !v.is_empty() { + out.insert(name.into(), json!(v)); + } + } + if let Some(isrc) = tag.get_string(ItemKey::Isrc).map(str::trim).filter(|s| !s.is_empty()) { + out.insert("isrc".into(), json!(isrc)); + } + out +} + pub fn read_embedded_lyrics(path: &str) -> String { let Ok(tagged) = lofty::read_from_path(path) else { return String::new() }; for tag in tagged.tags() { @@ -353,7 +388,7 @@ fn apply(tag: &mut Tag, field: Field, val: &str) { Field::Comment => if empty { tag.remove_comment() } else { tag.set_comment(val.into()) }, Field::AlbumArtist => item(tag, ItemKey::AlbumArtist, val, empty), Field::Composer => item(tag, ItemKey::Composer, val, empty), - Field::MbTrackId => item(tag, ItemKey::MusicBrainzTrackId, val, empty), + Field::MbTrackId => item(tag, ItemKey::MusicBrainzRecordingId, val, empty), Field::MbAlbumId => item(tag, ItemKey::MusicBrainzReleaseId, val, empty), Field::Year => { if empty { diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs index 8b2fc3e..c59e0c0 100644 --- a/src/ui/dialogs.rs +++ b/src/ui/dialogs.rs @@ -148,6 +148,8 @@ pub struct SettingsState { rip_pat: String, lfm_waiting: bool, lfm_msg: String, + lb_checking: bool, + lb_msg: String, } pub enum Dialog { @@ -229,6 +231,8 @@ impl Dialog { rip_pat: s.get_str("cd/rip_pattern"), lfm_waiting: false, lfm_msg: String::new(), + lb_checking: false, + lb_msg: String::new(), })) } @@ -450,6 +454,7 @@ pub fn on_lastfm_connected(app: &mut App, r: Result<(String, String), String>) { settings().set("lastfm/user", name.clone()); settings().set("lastfm/enabled", true); app.toast(format!("Connected to Last.fm as {name}")); + app.scrobbler.flush(); if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { s.lfm_waiting = false; s.lfm_on = true; @@ -466,6 +471,28 @@ pub fn on_lastfm_connected(app: &mut App, r: Result<(String, String), String>) { } } +pub fn on_listenbrainz_connected(app: &mut App, r: Result<(String, String), String>) { + let msg = match r { + Ok((token, name)) => { + settings().set("listenbrainz/token", token.clone()); + settings().set("listenbrainz/user", name.clone()); + settings().set("listenbrainz/enabled", true); + if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { + s.lb_token = token; + s.lb_on = true; + } + app.scrobbler.flush(); + format!("Connected to ListenBrainz as {name}") + } + Err(e) => format!("ListenBrainz: {e}"), + }; + if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { + s.lb_checking = false; + s.lb_msg = msg.clone(); + } + app.toast(msg); +} + pub fn on_picked(app: &mut App, purpose: &str, paths: Vec) { let Some(p) = paths.first().cloned() else { return }; match (purpose, app.dialog.as_mut()) { @@ -1477,6 +1504,9 @@ fn kv(items: &[(&str, &str)]) -> Vec<(String, String)> { fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { let mut want_pick: Option<(&'static str, Pick)> = None; let mut login = false; + let mut lfm_logout = false; + let mut lb_connect = false; + let mut lb_disconnect = false; { let g = &mut app.g; let theme = g.theme.clone(); @@ -1612,6 +1642,9 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { if text_button(ui, g, Some("link"), if logged { "Log in again" } else { "Log in with Last.fm" }, true).clicked() { login = true; } + if logged && text_button(ui, g, None, "Log out", false).clicked() { + lfm_logout = true; + } }); checkbox(ui, g, &mut s.lfm_on, "Scrobble what I play and send “now playing”"); checkbox(ui, g, &mut s.lfm_own, "Use my own API key instead of Mulberry's (advanced)"); @@ -1625,13 +1658,41 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { ui.label(RichText::new("Get a free key at last.fm/api/account/create — any app name works, leave the callback empty.").color(theme.on_surface_variant).size(12.5)); } heading(ui, g, "ListenBrainz"); - checkbox(ui, g, &mut s.lb_on, "Submit listens to ListenBrainz"); - row(ui, theme.on_surface_variant, "User token", |ui| { - text_field(ui, g, &mut s.lb_token, 360.0); + let lb_user = settings().get_str("listenbrainz/user"); + let lb_saved = !settings().get_str("listenbrainz/token").is_empty(); + ui.horizontal(|ui| { + let status = if s.lb_checking { + "Checking your token…".to_string() + } else if !s.lb_msg.is_empty() { + s.lb_msg.clone() + } else if lb_saved && !lb_user.is_empty() { + format!("Connected as {lb_user}") + } else if lb_saved { + "Token saved (not checked yet)".to_string() + } else { + "Not connected".to_string() + }; + ui.label(RichText::new(status).color(theme.on_surface_variant)); + if lb_saved && text_button(ui, g, None, "Disconnect", false).clicked() { + lb_disconnect = true; + } }); - let pend = app.scrobbler.pending(); - if pend > 0 { - ui.label(RichText::new(format!("{pend} scrobble(s) waiting to be sent.")).color(theme.on_surface_variant)); + row(ui, theme.on_surface_variant, "User token", |ui| { + secret_field(ui, g, &mut s.lb_token, 300.0); + if text_button(ui, g, Some("link"), if lb_saved { "Check" } else { "Connect" }, true).clicked() { + lb_connect = true; + } + }); + ui.horizontal(|ui| { + ui.label(RichText::new("Copy your user token from listenbrainz.org/settings").color(theme.on_surface_variant).size(12.5)); + if text_button(ui, g, None, "Open", false).clicked() { + crate::util::open_url("https://listenbrainz.org/settings/"); + } + }); + checkbox(ui, g, &mut s.lb_on, "Submit listens and “now playing” to ListenBrainz"); + let (pl, pb) = (app.scrobbler.pending_for("lastfm"), app.scrobbler.pending_for("listenbrainz")); + if pl + pb > 0 { + ui.label(RichText::new(format!("Waiting to be sent: {pl} to Last.fm, {pb} to ListenBrainz.")).color(theme.on_surface_variant)); } } 4 => { @@ -1675,6 +1736,37 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { if let Some((purpose, kind)) = want_pick { pick(app, purpose, kind); } + if lfm_logout { + settings().set("lastfm/session", ""); + settings().set("lastfm/user", ""); + settings().set("lastfm/enabled", false); + s.lfm_on = false; + s.lfm_msg = "Logged out".into(); + app.scrobbler.purge("lastfm"); + } + if lb_disconnect { + settings().set("listenbrainz/token", ""); + settings().set("listenbrainz/user", ""); + settings().set("listenbrainz/enabled", false); + s.lb_token.clear(); + s.lb_on = false; + s.lb_msg = "Disconnected".into(); + app.scrobbler.purge("listenbrainz"); + } + if lb_connect { + let token = s.lb_token.trim().to_string(); + if token.is_empty() { + s.lb_msg = "Paste your user token first".into(); + } else { + s.lb_checking = true; + s.lb_msg.clear(); + let bus = app.bus.clone(); + std::thread::spawn(move || { + let r = crate::scrobble::lb_validate(&token).map(|name| (token, name)); + bus.send(crate::bus::Msg::ConnectListenBrainz(r)); + }); + } + } if login { settings().set("lastfm/use_own_key", s.lfm_own); settings().set("lastfm/api_key", s.lfm_key.trim().to_string()); @@ -1720,6 +1812,10 @@ fn apply_settings(app: &mut App, s: &SettingsState) { st.set("lastfm/api_key", s.lfm_key.trim().to_string()); st.set("lastfm/api_secret", s.lfm_secret.trim().to_string()); st.set("listenbrainz/enabled", s.lb_on); + if st.get_str("listenbrainz/token") != s.lb_token.trim() { + // A new token was typed without pressing Connect: forget the old user name until it is checked. + st.set("listenbrainz/user", ""); + } st.set("listenbrainz/token", s.lb_token.trim().to_string()); st.set("online/auto_lyrics", s.auto_lyr); st.set("online/auto_covers", s.auto_cov); diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index 222b5a7..db43f51 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -498,6 +498,23 @@ pub fn text_field(ui: &mut Ui, g: &Gfx, text: &mut String, width: f32) -> Respon .inner } +/// Like `text_field`, but hides the text (tokens, keys). +pub fn secret_field(ui: &mut Ui, g: &Gfx, text: &mut String, width: f32) -> Response { + let t = &g.theme; + egui::Frame::NONE + .fill(t.surface_container_highest) + .corner_radius(egui::CornerRadius { nw: 6, ne: 6, sw: 0, se: 0 }) + .inner_margin(egui::Margin::symmetric(8, 2)) + .show(ui, |ui| { + ui.visuals_mut().widgets.inactive.bg_fill = Color32::TRANSPARENT; + ui.visuals_mut().widgets.hovered.bg_fill = Color32::TRANSPARENT; + ui.visuals_mut().widgets.active.bg_fill = Color32::TRANSPARENT; + ui.visuals_mut().selection.bg_fill = t.primary; + ui.add(egui::TextEdit::singleline(text).password(true).frame(egui::Frame::NONE).desired_width(width - 16.0).margin(egui::Margin::symmetric(0, 6))) + }) + .inner +} + pub fn card(g: &Gfx) -> egui::Frame { egui::Frame::NONE.fill(g.theme.surface_container_low).corner_radius(cr(16.0)).inner_margin(egui::Margin::same(12)) }