7.9 KiB · text History 0463cca
//! Where scrobbles go. Three kinds, as on scropple-android:
//!
//! - [`scropple`]: the Scropple HTTP contract (final_track, ircd's
//!   ScrobbleServ), bearer token;
//! - [`listenbrainz`]: ListenBrainz, or any server speaking its API, with a
//!   user token;
//! - [`lastfm`]: Last.fm, with a session key from `scropple login`.
//!
//! Each takes a [`Play`] for now-playing and a batch of them for scrobbles,
//! and answers with a [`SendError`] saying whether the plays are worth
//! sending again.

pub mod lastfm;
pub mod listenbrainz;
pub mod scropple;

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::time::Duration;

use crate::config::{BackendConfig, Kind};
use crate::engine::Track;

pub use lastfm::Lastfm;
pub use listenbrainz::ListenBrainz;
pub use scropple::HttpBackend;

/// One play, as the Scropple API takes it (and as the queue stores it).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Play {
    pub artist: String,
    pub track: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub album: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub album_artist: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_sec: Option<u64>,
    /// When the play started, Unix seconds (absent for now-playing).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<i64>,
}

impl Play {
    pub fn from_track(t: &Track, started: Option<i64>) -> Self {
        Self {
            artist: t.artist.clone(),
            track: t.title.clone(),
            album: t.album.clone(),
            album_artist: t.album_artist.clone(),
            duration_sec: (t.duration_ms > 0).then(|| t.duration_ms.div_ceil(1000)),
            timestamp: started.filter(|&s| s > 0),
        }
    }
}

#[derive(Debug)]
pub enum SendError {
    /// Worth trying again later: the network, a 5xx, 408/429, or a 401/403
    /// (a token being fixed shouldn't cost the plays waiting for it).
    Retry(String),
    /// The server refused the plays themselves (a 4xx such as 422): drop them.
    Rejected(String),
}

impl std::fmt::Display for SendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SendError::Retry(m) => write!(f, "will retry: {m}"),
            SendError::Rejected(m) => write!(f, "rejected: {m}"),
        }
    }
}

/// What a status means for the plays sent.
pub fn classify(status: u16, describe: impl FnOnce() -> String) -> Result<(), SendError> {
    match status {
        200..=299 => Ok(()),
        401 | 403 | 408 | 429 | 500..=599 => Err(SendError::Retry(describe())),
        _ => Err(SendError::Rejected(describe())),
    }
}

pub(crate) fn http_client() -> reqwest::Client {
    reqwest::Client::builder()
        .user_agent(concat!("scropple-linux/", env!("CARGO_PKG_VERSION")))
        .timeout(Duration::from_secs(20))
        .build()
        .expect("an HTTP client")
}

/// A configured backend.
pub enum Backend {
    Scropple(HttpBackend),
    ListenBrainz(ListenBrainz),
    Lastfm(Lastfm),
}

impl Backend {
    /// Builds one from its config, reading its token. An empty token isn't an
    /// error here: the backend holds its plays until one is there (see
    /// [`Backend::scrobble`]), so signing in later loses nothing.
    pub fn from_config(c: &BackendConfig) -> Result<Self> {
        let token = c.token()?;
        Ok(match c.kind {
            Kind::Scropple => {
                let Some(url) = &c.url else {
                    bail!("backend {:?}: a scropple backend needs a url", c.name)
                };
                Backend::Scropple(HttpBackend::new(&c.name, url, &token))
            }
            Kind::Listenbrainz => Backend::ListenBrainz(ListenBrainz::new(
                &c.name,
                c.url.as_deref().unwrap_or(listenbrainz::ROOT),
                &token,
            )),
            Kind::Lastfm => {
                let (api_key, api_secret) = c.lastfm_credentials()?;
                Backend::Lastfm(Lastfm::new(
                    &c.name,
                    c.url.as_deref().unwrap_or(lastfm::ROOT),
                    &api_key,
                    &api_secret,
                    &token,
                ))
            }
        })
    }

    pub fn name(&self) -> &str {
        match self {
            Backend::Scropple(b) => &b.name,
            Backend::ListenBrainz(b) => &b.name,
            Backend::Lastfm(b) => &b.name,
        }
    }

    fn signed_in(&self) -> bool {
        match self {
            Backend::Scropple(b) => b.has_token(),
            Backend::ListenBrainz(b) => b.has_token(),
            Backend::Lastfm(b) => b.has_session(),
        }
    }

    fn not_signed_in(&self) -> SendError {
        SendError::Retry(format!(
            "not signed in: run `scropple login {}`, then restart scropple",
            self.name()
        ))
    }

    pub async fn now_playing(&self, play: &Play) -> Result<(), SendError> {
        if !self.signed_in() {
            return Err(self.not_signed_in());
        }
        match self {
            Backend::Scropple(b) => b.now_playing(play).await,
            Backend::ListenBrainz(b) => b.now_playing(play).await,
            Backend::Lastfm(b) => b.now_playing(play).await,
        }
    }

    /// Sends up to [`crate::queue::BATCH`] plays (50: Last.fm's limit too).
    pub async fn scrobble(&self, plays: &[Play]) -> Result<(), SendError> {
        if !self.signed_in() {
            return Err(self.not_signed_in());
        }
        match self {
            Backend::Scropple(b) => b.scrobble(plays).await,
            Backend::ListenBrainz(b) => b.scrobble(plays).await,
            Backend::Lastfm(b) => b.scrobble(plays).await,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plays_serialize_as_the_api_takes_them() {
        let t = Track {
            artist: "Pink Floyd".into(),
            title: "Time".into(),
            album: Some("The Dark Side of the Moon".into()),
            album_artist: None,
            duration_ms: 412_500,
            player: "spotify".into(),
        };
        let json = serde_json::to_value(Play::from_track(&t, Some(1_763_494_445))).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "artist": "Pink Floyd",
                "track": "Time",
                "album": "The Dark Side of the Moon",
                "durationSec": 413,
                "timestamp": 1_763_494_445
            })
        );

        let now = serde_json::to_value(Play::from_track(
            &Track {
                duration_ms: 0,
                album: None,
                ..t
            },
            None,
        ))
        .unwrap();
        assert_eq!(
            now,
            serde_json::json!({"artist": "Pink Floyd", "track": "Time"})
        );
    }

    #[test]
    fn statuses() {
        assert!(classify(200, String::new).is_ok());
        assert!(classify(204, String::new).is_ok());
        for s in [401, 403, 408, 429, 500, 503] {
            assert!(
                matches!(classify(s, String::new), Err(SendError::Retry(_))),
                "{s}"
            );
        }
        for s in [400, 404, 422] {
            assert!(
                matches!(classify(s, String::new), Err(SendError::Rejected(_))),
                "{s}"
            );
        }
    }

    #[tokio::test]
    async fn without_a_token_plays_wait() {
        let b = Backend::ListenBrainz(ListenBrainz::new("lb", "http://127.0.0.1:9", ""));
        let play = Play {
            artist: "a".into(),
            track: "t".into(),
            album: None,
            album_artist: None,
            duration_sec: None,
            timestamp: Some(1),
        };
        match b.scrobble(&[play]).await {
            Err(SendError::Retry(m)) => assert!(m.contains("scropple login lb"), "{m}"),
            other => panic!("{other:?}"),
        }
    }
}