Adds a "My server" sidebar item (⌘5) for Navidrome and other Subsonic-compatible servers: albums, artists, playlists, starred songs and search, with album, artist and playlist pages. Server songs share the player and queue with Yandex tracks and scrobble back to the server. - New subsonic-api crate: token auth, envelope and error parsing, and a stream plan that keeps files the player decodes and asks the server to transcode the rest to MP3. - ym_api::Track gains a Subsonic source; the player fetches, reports and scrobbles by source. Server errors never sign out of Yandex, and the Yandex client never fetches server audio or covers. - Server credentials live in the keychain; connect and disconnect from the page or Settings. - Server tracks have no likes; lyrics come from LRCLIB.
171 lines
5.8 KiB
Rust
171 lines
5.8 KiB
Rust
//! LRCLIB (lrclib.net), the open lyrics database, for tracks Yandex has no lyrics for.
|
|
|
|
use std::time::Duration;
|
|
|
|
use serde::Deserialize;
|
|
|
|
use crate::edit::{Lyrics, LyricsSource};
|
|
use crate::models::Track;
|
|
use crate::{Error, Result};
|
|
|
|
const BASE: &str = "https://lrclib.net/api";
|
|
/// LRCLIB asks clients to name themselves.
|
|
const USER_AGENT: &str = concat!("musyx/", env!("CARGO_PKG_VERSION"));
|
|
const TIMEOUT: Duration = Duration::from_secs(10);
|
|
/// How far a match's length may stray from the track's; LRCLIB's own `get` uses ±2 s.
|
|
const SLACK: f64 = 2.0;
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct Record {
|
|
#[serde(default)]
|
|
duration: Option<f64>,
|
|
#[serde(default)]
|
|
instrumental: bool,
|
|
plain_lyrics: Option<String>,
|
|
synced_lyrics: Option<String>,
|
|
}
|
|
|
|
impl Record {
|
|
fn has_lyrics(&self) -> bool {
|
|
!self.instrumental && (filled(&self.synced_lyrics).is_some() || filled(&self.plain_lyrics).is_some())
|
|
}
|
|
|
|
/// Synced when there are timings, else plain text.
|
|
fn into_lyrics(self) -> Option<Lyrics> {
|
|
if self.instrumental {
|
|
return None;
|
|
}
|
|
let lyrics = match (filled(&self.synced_lyrics), filled(&self.plain_lyrics)) {
|
|
(Some(lrc), _) => Lyrics::from_lrc(lrc, vec![]),
|
|
(None, Some(text)) => Lyrics::from_text(text, vec![]),
|
|
(None, None) => return None,
|
|
};
|
|
Some(Lyrics { source: LyricsSource::Lrclib, ..lyrics })
|
|
}
|
|
}
|
|
|
|
fn filled(s: &Option<String>) -> Option<&str> {
|
|
s.as_deref().filter(|s| !s.trim().is_empty())
|
|
}
|
|
|
|
/// Looks the track up by its exact signature first, then by a looser search
|
|
/// filtered on length so a live cut or a remix doesn't borrow the studio timings.
|
|
pub(crate) async fn lyrics(http: &reqwest::Client, track: &Track) -> Result<Option<Lyrics>> {
|
|
let Some(artist) = track.artists.first().map(|a| a.name.as_str()) else { return Ok(None) };
|
|
let secs = track.duration.as_secs_f64();
|
|
|
|
if let Some(album) = track.album_title()
|
|
&& secs > 0.0
|
|
{
|
|
let duration = secs.round().to_string();
|
|
let query = [
|
|
("track_name", track.title.as_str()),
|
|
("artist_name", artist),
|
|
("album_name", album),
|
|
("duration", duration.as_str()),
|
|
];
|
|
if let Some(record) = get::<Record>(http, "get", &query).await?
|
|
&& let Some(lyrics) = record.into_lyrics()
|
|
{
|
|
return Ok(Some(lyrics));
|
|
}
|
|
}
|
|
|
|
let query = [("track_name", track.title.as_str()), ("artist_name", artist)];
|
|
let found = get::<Vec<Record>>(http, "search", &query).await?.unwrap_or_default();
|
|
Ok(pick(found, secs).and_then(Record::into_lyrics))
|
|
}
|
|
|
|
/// The closest-length match that has words, preferring synced ones.
|
|
fn pick(found: Vec<Record>, secs: f64) -> Option<Record> {
|
|
let off = |r: &Record| match r.duration {
|
|
Some(d) if secs > 0.0 => (d - secs).abs(),
|
|
_ => 0.0,
|
|
};
|
|
found
|
|
.into_iter()
|
|
.filter(|r| r.has_lyrics() && (secs <= 0.0 || r.duration.is_none_or(|d| (d - secs).abs() <= SLACK)))
|
|
.min_by(|a, b| {
|
|
filled(&b.synced_lyrics)
|
|
.is_some()
|
|
.cmp(&filled(&a.synced_lyrics).is_some())
|
|
.then(off(a).total_cmp(&off(b)))
|
|
})
|
|
}
|
|
|
|
/// `None` on 404, which LRCLIB answers when it has no such track.
|
|
async fn get<T: serde::de::DeserializeOwned>(
|
|
http: &reqwest::Client,
|
|
endpoint: &str,
|
|
query: &[(&str, &str)],
|
|
) -> Result<Option<T>> {
|
|
let network = |e: reqwest::Error| Error::Network(format!("lrclib: {e}"));
|
|
let response = http
|
|
.get(format!("{BASE}/{endpoint}"))
|
|
.query(query)
|
|
.header(reqwest::header::USER_AGENT, USER_AGENT)
|
|
.timeout(TIMEOUT)
|
|
.send()
|
|
.await
|
|
.map_err(network)?;
|
|
let status = response.status();
|
|
if status == reqwest::StatusCode::NOT_FOUND {
|
|
return Ok(None);
|
|
}
|
|
if !status.is_success() {
|
|
return Err(if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
|
|
Error::Network(format!("lrclib: {status}"))
|
|
} else {
|
|
Error::Api(format!("lrclib: {status}"))
|
|
});
|
|
}
|
|
let body = response.bytes().await.map_err(network)?;
|
|
serde_json::from_slice(&body).map(Some).map_err(|e| Error::Api(format!("lrclib: {e}")))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn records(json: &str) -> Vec<Record> {
|
|
serde_json::from_str(json).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn prefers_synced_then_closest_length() {
|
|
let found = records(
|
|
r#"[
|
|
{"duration":200,"instrumental":false,"plainLyrics":"far","syncedLyrics":"[00:01.00]far"},
|
|
{"duration":181,"instrumental":false,"plainLyrics":"plain","syncedLyrics":null},
|
|
{"duration":182,"instrumental":false,"plainLyrics":"x","syncedLyrics":"[00:01.00]near"},
|
|
{"duration":180,"instrumental":false,"plainLyrics":"y","syncedLyrics":"[00:01.00]exact"}
|
|
]"#,
|
|
);
|
|
let l = pick(found, 180.0).unwrap().into_lyrics().unwrap();
|
|
assert!(l.synced);
|
|
assert_eq!(l.lines[0].text, "exact");
|
|
assert_eq!(l.source, LyricsSource::Lrclib);
|
|
}
|
|
|
|
#[test]
|
|
fn skips_instrumentals_and_wrong_lengths() {
|
|
let found = records(
|
|
r#"[
|
|
{"duration":180,"instrumental":true,"plainLyrics":null,"syncedLyrics":null},
|
|
{"duration":240,"instrumental":false,"plainLyrics":"live","syncedLyrics":null}
|
|
]"#,
|
|
);
|
|
assert!(pick(found, 180.0).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn falls_back_to_plain_text() {
|
|
let r = records(r#"[{"duration":180,"instrumental":false,"plainLyrics":"a\nb","syncedLyrics":" "}]"#);
|
|
let l = pick(r, 180.0).unwrap().into_lyrics().unwrap();
|
|
assert!(!l.synced);
|
|
assert_eq!(l.lines.len(), 2);
|
|
}
|
|
}
|
|
|