- scrobble.log in the data folder records queued, sent and failed scrobbles (stdout goes nowhere, so failures were invisible) - Queued scrobbles retry every 2 minutes; maybe_periodic was never called - One flush at a time, so a listen is never sent twice - The playing track's listen is queued on quit and sent on the next start - Listen time keeps counting while the window is hidden (Wayland stops frames) - Last.fm: says nothing is sent while logged out; waiting scrobbles can be discarded - Settings › Scrobbling: one card per service with its own send checkbox, text left and buttons right on one centre line; row labels left-aligned - iOS: send the listen as soon as it counts (not only at track change), retry every 2 minutes, log sends - Android: retry queued scrobbles every 2 minutes while playing Co-Authored-By: Claude Opus 5.5 <[email protected]>
600 lines
25 KiB
Rust
600 lines
25 KiB
Rust
//! Last.fm and ListenBrainz scrobbling with an offline cache.
|
||
|
||
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_st, http_post_form_st, http_post_json_st, lastfm_key};
|
||
use crate::song::Song;
|
||
use serde_json::{json, Value};
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use std::sync::{Arc, Mutex};
|
||
use std::time::Instant;
|
||
|
||
const LFM_API: &str = "https://ws.audioscrobbler.com/2.0/";
|
||
pub const CALLBACK_PORT: u16 = 47823;
|
||
|
||
/// Log of scrobble sends and errors (stdout/stderr go nowhere in the desktop app).
|
||
/// Rotated to scrobble.log.old past this size, so it never grows without bound.
|
||
const LOG_MAX_BYTES: u64 = 256 * 1024;
|
||
|
||
pub fn log(line: &str) {
|
||
use std::io::Write;
|
||
let path = PATHS.data.join("scrobble.log");
|
||
if std::fs::metadata(&path).map(|m| m.len() > LOG_MAX_BYTES).unwrap_or(false) {
|
||
let _ = std::fs::rename(&path, PATHS.data.join("scrobble.log.old"));
|
||
}
|
||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
|
||
let _ = writeln!(f, "{} {line}", chrono::Utc::now().format("%Y-%m-%d %H:%M:%SZ"));
|
||
}
|
||
}
|
||
|
||
/// Retry queued scrobbles this often after a failed send (also catches anything a crash left behind).
|
||
const RETRY_SECS: u64 = 120;
|
||
|
||
pub fn has_key() -> bool {
|
||
let (k, s) = lastfm_key();
|
||
!k.is_empty() && !s.is_empty()
|
||
}
|
||
|
||
fn sign(params: &mut Vec<(String, String)>) {
|
||
let (_, secret) = lastfm_key();
|
||
let mut sorted: Vec<&(String, String)> = params.iter().filter(|(k, _)| k != "format" && k != "callback").collect();
|
||
sorted.sort_by(|a, b| a.0.cmp(&b.0));
|
||
let s: String = sorted.iter().map(|(k, v)| format!("{k}{v}")).collect::<String>() + &secret;
|
||
let sig = format!("{:x}", md5::compute(s.as_bytes()));
|
||
params.push(("api_sig".into(), sig));
|
||
}
|
||
|
||
/// 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<Value, (i64, String)> {
|
||
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()));
|
||
if auth {
|
||
p.push(("sk".into(), settings().get_str("lastfm/session")));
|
||
}
|
||
sign(&mut p);
|
||
p.push(("format".into(), "json".into()));
|
||
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_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<Value, String> {
|
||
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<String, String> {
|
||
let res = lfm_call("auth.getToken", vec![], false, false)?;
|
||
res["token"].as_str().map(String::from).ok_or_else(|| "no token".into())
|
||
}
|
||
|
||
pub fn web_auth_url(port: u16) -> String {
|
||
let (key, _) = lastfm_key();
|
||
format!("https://www.last.fm/api/auth/?api_key={key}&cb={}", urlencoding::encode(&format!("http://127.0.0.1:{port}/lastfm")))
|
||
}
|
||
|
||
pub fn finish_auth(token: &str) -> Result<(String, String), String> {
|
||
let res = lfm_call("auth.getSession", vec![("token".into(), token.into())], false, false)?;
|
||
Ok((res["session"]["key"].as_str().unwrap_or("").into(), res["session"]["name"].as_str().unwrap_or("").into()))
|
||
}
|
||
|
||
/// One-shot local HTTP server that receives Last.fm's redirect (…/lastfm?token=XYZ).
|
||
pub fn start_login(bus: Bus) -> Result<(), String> {
|
||
let listener = std::net::TcpListener::bind(("127.0.0.1", CALLBACK_PORT)).map_err(|e| format!("Port {CALLBACK_PORT} is busy: {e}"))?;
|
||
let _ = listener.set_nonblocking(false);
|
||
crate::util::open_url(&web_auth_url(CALLBACK_PORT));
|
||
std::thread::spawn(move || {
|
||
use std::io::{Read, Write};
|
||
let deadline = Instant::now() + std::time::Duration::from_secs(300);
|
||
let _ = listener.set_nonblocking(true);
|
||
while Instant::now() < deadline {
|
||
match listener.accept() {
|
||
Ok((mut s, _)) => {
|
||
let mut buf = [0u8; 4096];
|
||
let n = s.read(&mut buf).unwrap_or(0);
|
||
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||
let token = req.split("token=").nth(1).map(|t| t.split(|c: char| c == ' ' || c == '&').next().unwrap_or("").to_string()).unwrap_or_default();
|
||
let page = "<!doctype html><meta charset=utf-8><title>Mulberry</title><body style='font-family:system-ui,sans-serif;background:#1d1b20;color:#e6e0e9;display:grid;place-items:center;height:100vh;margin:0'><div style='text-align:center'><div style='font-size:56px'>🫐</div><h2>Mulberry is connected to Last.fm</h2><p style='opacity:.7'>You can close this tab and go back to the app.</p></div></body>";
|
||
let status = if token.is_empty() { "404 Not Found" } else { "200 OK" };
|
||
let body = if token.is_empty() { "Not found" } else { page };
|
||
let _ = write!(s, "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
|
||
if !token.is_empty() {
|
||
bus.send(Msg::ConnectLastFm(finish_auth(&token)));
|
||
return;
|
||
}
|
||
}
|
||
Err(_) => std::thread::sleep(std::time::Duration::from_millis(150)),
|
||
}
|
||
}
|
||
bus.send(Msg::ConnectLastFm(Err("Timed out waiting for Last.fm".into())));
|
||
});
|
||
Ok(())
|
||
}
|
||
|
||
/// 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();
|
||
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<String, Value> {
|
||
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, Value>) -> 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<usize>) -> 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.is_stream() {
|
||
p.push((format!("albumArtist{sfx}"), s.albumartist.clone()));
|
||
}
|
||
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()));
|
||
}
|
||
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<i64>) -> Value {
|
||
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));
|
||
}
|
||
if s.duration() > 0.0 {
|
||
a.insert("duration_ms".into(), json!((s.duration() * 1000.0) as i64));
|
||
}
|
||
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() && !s.is_stream() {
|
||
meta["release_name"] = json!(s.album);
|
||
}
|
||
let mut p = json!({"track_metadata": meta});
|
||
if let Some(t) = ts {
|
||
p["listened_at"] = json!(t);
|
||
}
|
||
p
|
||
}
|
||
|
||
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<Value, (u16, String)> {
|
||
let token = format!("Token {}", settings().get_str("listenbrainz/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<Value>) -> Result<Value, (u16, String)> {
|
||
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<String, String> {
|
||
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 {
|
||
settings().get_bool("lastfm/enabled") && !settings().get_str("lastfm/session").is_empty() && has_key()
|
||
}
|
||
|
||
pub fn lb_on() -> bool {
|
||
settings().get_bool("listenbrainz/enabled") && !settings().get_str("listenbrainz/token").is_empty()
|
||
}
|
||
|
||
pub struct Scrobbler {
|
||
bus: Bus,
|
||
cache: Arc<Mutex<Vec<Value>>>,
|
||
announced: Option<(String, Instant)>,
|
||
last_flush: Instant,
|
||
/// One flush at a time, so two threads never send the same queued listen.
|
||
busy: Arc<AtomicBool>,
|
||
}
|
||
|
||
impl Scrobbler {
|
||
pub fn new(bus: Bus) -> Scrobbler {
|
||
let cache: Vec<Value> = std::fs::read_to_string(PATHS.data.join("scrobble_cache.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
|
||
let s = Scrobbler { bus, cache: Arc::new(Mutex::new(cache)), announced: None, last_flush: Instant::now(), busy: Default::default() };
|
||
s.flush_later(10);
|
||
s
|
||
}
|
||
|
||
fn save(cache: &[Value]) {
|
||
let _ = std::fs::write(PATHS.data.join("scrobble_cache.json"), serde_json::to_string(cache).unwrap_or_default());
|
||
}
|
||
|
||
pub fn pending(&self) -> usize {
|
||
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()));
|
||
if s.is_cd() && (s.title.is_empty() || s.title.starts_with("Track ")) && s.mb_trackid.is_empty() {
|
||
return;
|
||
}
|
||
let (bus, song) = (self.bus.clone(), s.clone());
|
||
if lfm_on() {
|
||
let (bus, song) = (bus.clone(), song.clone());
|
||
std::thread::spawn(move || {
|
||
if let Err(e) = lfm_call("track.updateNowPlaying", track_params(&song, None), true, true) {
|
||
log(&format!("lastfm now playing failed: {e}"));
|
||
bus.toast(e);
|
||
}
|
||
});
|
||
}
|
||
if lb_on() {
|
||
std::thread::spawn(move || {
|
||
if let Err((_, e)) = lb_submit("playing_now", vec![lb_payload(&song, None)]) {
|
||
log(&format!("listenbrainz now playing failed: {e}"));
|
||
bus.toast(e);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn state_playing(&mut self, s: &Song) {
|
||
let stale = match &self.announced {
|
||
Some((k, t)) => *k != s.key() || t.elapsed().as_secs() > 240,
|
||
None => true,
|
||
};
|
||
if stale {
|
||
self.track_started(s);
|
||
}
|
||
}
|
||
|
||
pub fn track_finished(&mut self, s: &Song, listened: f64, started: i64) {
|
||
let name = format!("{} - {}", s.display_artist(), s.display_title());
|
||
if !counts_as_listen(s.is_stream(), s.duration(), listened) || s.display_artist().is_empty() || s.display_title().is_empty() {
|
||
log(&format!("not a listen ({listened:.0} of {:.0} s): {name}", s.duration()));
|
||
return;
|
||
}
|
||
let mut entry = json!({"song": song_to_json(s), "ts": started, "stream_title": s.stream_title});
|
||
{
|
||
let mut c = self.cache.lock().unwrap();
|
||
if lfm_on() {
|
||
entry["svc"] = json!("lastfm");
|
||
c.push(entry.clone());
|
||
}
|
||
if lb_on() {
|
||
entry["svc"] = json!("listenbrainz");
|
||
c.push(entry.clone());
|
||
}
|
||
Self::save(&c);
|
||
}
|
||
log(&format!("queued (lastfm {}, listenbrainz {}): {name} at {started}", lfm_on(), lb_on()));
|
||
self.flush();
|
||
}
|
||
|
||
fn flush_later(&self, secs: u64) {
|
||
let s = Scrobbler { bus: self.bus.clone(), cache: self.cache.clone(), announced: None, last_flush: Instant::now(), busy: self.busy.clone() };
|
||
std::thread::spawn(move || {
|
||
std::thread::sleep(std::time::Duration::from_secs(secs));
|
||
s.flush();
|
||
});
|
||
}
|
||
|
||
pub fn maybe_periodic(&mut self) {
|
||
if self.last_flush.elapsed().as_secs() > RETRY_SECS {
|
||
self.last_flush = Instant::now();
|
||
self.flush();
|
||
}
|
||
}
|
||
|
||
pub fn flush(&self) {
|
||
if self.cache.lock().unwrap().is_empty() || self.busy.swap(true, Ordering::SeqCst) {
|
||
return;
|
||
}
|
||
let (cache, bus, busy) = (self.cache.clone(), self.bus.clone(), self.busy.clone());
|
||
std::thread::spawn(move || {
|
||
let r = flush_work(&cache);
|
||
busy.store(false, Ordering::SeqCst);
|
||
match r {
|
||
Ok(n) if n > 0 => bus.toast(format!("Scrobbled {n} track(s)")),
|
||
Ok(_) => {}
|
||
Err(e) => bus.toast(format!("Scrobbling deferred: {e}")),
|
||
}
|
||
});
|
||
}
|
||
|
||
pub fn love(&self, s: &Song, loved: bool) {
|
||
let bus = self.bus.clone();
|
||
if lfm_on() {
|
||
let (s, bus) = (s.clone(), bus.clone());
|
||
std::thread::spawn(move || {
|
||
let r = lfm_call(if loved { "track.love" } else { "track.unlove" }, vec![("artist".into(), s.display_artist()), ("track".into(), s.display_title())], true, true);
|
||
match r {
|
||
Ok(_) => bus.toast(if loved { "Loved on Last.fm" } else { "Unloved on Last.fm" }),
|
||
Err(e) => bus.toast(e),
|
||
}
|
||
});
|
||
}
|
||
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 || {
|
||
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<Mutex<Vec<Value>>>) -> Result<usize, String> {
|
||
let pending: Vec<Value> = cache.lock().unwrap().clone();
|
||
let svc = |e: &Value, n: &str| e["svc"] == n;
|
||
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<Value> = vec![];
|
||
let mut errors: Vec<String> = 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() {
|
||
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(_) => {
|
||
log(&format!("lastfm sent {}: {}", chunk.len(), titles(chunk)));
|
||
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()));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
let lb: Vec<&Value> = pending.iter().filter(|e| svc(e, "listenbrainz")).collect();
|
||
if !lb.is_empty() && lb_on() {
|
||
'lb: for chunk in lb.chunks(100) {
|
||
let payload: Vec<Value> = 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(_) => {
|
||
log(&format!("listenbrainz sent {}: {}", chunk.len(), titles(chunk)));
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if !lfm.is_empty() && !lfm_on() {
|
||
log(&format!("lastfm: {} scrobble(s) wait for a login", lfm.len()));
|
||
}
|
||
if !lb.is_empty() && !lb_on() {
|
||
log(&format!("listenbrainz: {} listen(s) wait, ListenBrainz is off or has no token", lb.len()));
|
||
}
|
||
for e in &errors {
|
||
log(&format!("error: {e}"));
|
||
}
|
||
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"));
|
||
}
|
||
Ok(sent)
|
||
}
|
||
|
||
/// Last.fm / ListenBrainz rule: half the track or 4 minutes, and tracks under 30 s never count.
|
||
fn counts_as_listen(stream: bool, dur: f64, listened: f64) -> bool {
|
||
if stream {
|
||
listened >= 30.0
|
||
} else {
|
||
dur >= 30.0 && listened >= (dur / 2.0).min(240.0)
|
||
}
|
||
}
|
||
|
||
fn titles(chunk: &[&Value]) -> String {
|
||
let t: Vec<String> = chunk.iter().take(5).map(|e| format!("{} at {}", e["song"]["title"].as_str().unwrap_or("?"), e["ts"])).collect();
|
||
t.join(", ") + if chunk.len() > 5 { ", …" } else { "" }
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn listen_rule() {
|
||
assert!(counts_as_listen(false, 300.0, 150.0));
|
||
assert!(!counts_as_listen(false, 300.0, 149.0));
|
||
assert!(counts_as_listen(false, 900.0, 240.0)); // 4 minutes is enough for long tracks
|
||
assert!(!counts_as_listen(false, 25.0, 25.0)); // under 30 s never counts
|
||
assert!(counts_as_listen(true, 0.0, 30.0));
|
||
}
|
||
|
||
#[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<Value> = 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)));
|
||
}
|
||
}
|
||
}
|
||
}
|