10.2 KiB · text History 0463cca
//! Last.fm (<https://www.last.fm/api/scrobbling>). Every call is signed:
//! the parameters sorted by name, each name and value concatenated, the
//! shared secret appended, MD5 in hex (`format` is left out). Scrobbles and
//! now-playing need a session key, which `scropple login` gets with the
//! desktop flow (<https://www.last.fm/api/desktopauth>): a request token,
//! approved by the user in the browser, traded for a session key. Scropple
//! never sees the password.
//!
//! The API key and secret belong to an application registered at
//! <https://www.last.fm/api/account/create>: from the config, or built in
//! from `SCROPPLE_LASTFM_API_KEY` / `SCROPPLE_LASTFM_API_SECRET` at compile
//! time.

use anyhow::{Context, bail};
use md5::{Digest, Md5};
use serde_json::Value;
use std::collections::BTreeMap;

use super::{Play, SendError, classify, http_client};

pub const ROOT: &str = "https://ws.audioscrobbler.com/2.0/";
pub const AUTH_URL: &str = "https://www.last.fm/api/auth/";

/// The application credentials built into this binary, if any.
pub const BUILTIN_API_KEY: Option<&str> = option_env!("SCROPPLE_LASTFM_API_KEY");
pub const BUILTIN_API_SECRET: Option<&str> = option_env!("SCROPPLE_LASTFM_API_SECRET");

pub struct Lastfm {
    pub name: String,
    root: String,
    api_key: String,
    api_secret: String,
    session_key: String,
    client: reqwest::Client,
}

impl Lastfm {
    pub fn new(name: &str, root: &str, api_key: &str, api_secret: &str, session_key: &str) -> Self {
        Self {
            name: name.to_string(),
            root: root.to_string(),
            api_key: api_key.to_string(),
            api_secret: api_secret.to_string(),
            session_key: session_key.to_string(),
            client: http_client(),
        }
    }

    pub fn has_session(&self) -> bool {
        !self.session_key.is_empty()
    }

    pub async fn now_playing(&self, p: &Play) -> Result<(), SendError> {
        let mut params = BTreeMap::new();
        params.insert("method".into(), "track.updateNowPlaying".into());
        params.insert("artist".into(), p.artist.clone());
        params.insert("track".into(), p.track.clone());
        put_optional(&mut params, "", p);
        self.write(params).await.map(|_| ())
    }

    /// Up to 50 plays (Last.fm's limit per call, and the queue's batch).
    pub async fn scrobble(&self, plays: &[Play]) -> Result<(), SendError> {
        if plays.is_empty() {
            return Ok(());
        }
        let resp = self.write(scrobble_params(plays)).await?;
        // Last.fm accepts the call but may ignore some plays (too old, a
        // filtered artist...): nothing to retry, so just say so.
        let attr = &resp["scrobbles"]["@attr"];
        let ignored = number(&attr["ignored"]);
        if ignored > 0 {
            tracing::info!(
                backend = %self.name,
                accepted = number(&attr["accepted"]),
                ignored,
                "Last.fm ignored some plays"
            );
        }
        Ok(())
    }

    /// A signed POST with the session key.
    async fn write(&self, mut params: BTreeMap<String, String>) -> Result<Value, SendError> {
        params.insert("api_key".into(), self.api_key.clone());
        params.insert("sk".into(), self.session_key.clone());
        let form = signed(params, &self.api_secret);
        let resp = self
            .client
            .post(&self.root)
            .form(&form)
            .send()
            .await
            .map_err(|e| SendError::Retry(e.to_string()))?;
        let status = resp.status().as_u16();
        let body: Value = resp.json().await.unwrap_or(Value::Null);
        if let Some(code) = body["error"].as_u64() {
            let message = body["message"].as_str().unwrap_or("").to_string();
            return Err(classify_error(code, &message));
        }
        classify(status, || format!("HTTP {status} from Last.fm"))?;
        Ok(body)
    }

    // ── signing in ────────────────────────────────────────────────────

    /// Step 1: a request token, and the page where the user approves it.
    pub async fn request_token(&self) -> anyhow::Result<(String, String)> {
        let resp = self.read("auth.getToken", BTreeMap::new()).await?;
        let token = resp["token"]
            .as_str()
            .context("Last.fm sent no token")?
            .to_string();
        let url = format!("{AUTH_URL}?api_key={}&token={token}", self.api_key);
        Ok((token, url))
    }

    /// Step 2, once approved: the session key and the user's name.
    pub async fn session(&self, token: &str) -> anyhow::Result<(String, String)> {
        let mut params = BTreeMap::new();
        params.insert("token".into(), token.to_string());
        let resp = self.read("auth.getSession", params).await?;
        let session = &resp["session"];
        Ok((
            session["key"]
                .as_str()
                .context("Last.fm sent no session key")?
                .to_string(),
            session["name"].as_str().unwrap_or("?").to_string(),
        ))
    }

    /// A signed GET without a session (the auth methods).
    async fn read(
        &self,
        method: &str,
        mut params: BTreeMap<String, String>,
    ) -> anyhow::Result<Value> {
        params.insert("method".into(), method.into());
        params.insert("api_key".into(), self.api_key.clone());
        let query = signed(params, &self.api_secret);
        let resp: Value = self
            .client
            .get(&self.root)
            .query(&query)
            .send()
            .await?
            .json()
            .await
            .context("Last.fm's answer wasn't JSON")?;
        if let Some(code) = resp["error"].as_u64() {
            bail!(
                "Last.fm error {code}: {}",
                resp["message"].as_str().unwrap_or("no message")
            );
        }
        Ok(resp)
    }
}

fn number(v: &Value) -> u64 {
    v.as_u64()
        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        .unwrap_or(0)
}

/// `album`, `albumArtist`, `duration`, each with `suffix` (`[i]` in a batch).
fn put_optional(params: &mut BTreeMap<String, String>, suffix: &str, p: &Play) {
    if let Some(a) = &p.album {
        params.insert(format!("album{suffix}"), a.clone());
    }
    if let Some(a) = &p.album_artist {
        params.insert(format!("albumArtist{suffix}"), a.clone());
    }
    if let Some(d) = p.duration_sec {
        params.insert(format!("duration{suffix}"), d.to_string());
    }
}

pub fn scrobble_params(plays: &[Play]) -> BTreeMap<String, String> {
    let mut params = BTreeMap::new();
    params.insert("method".into(), "track.scrobble".into());
    for (i, p) in plays.iter().enumerate() {
        let s = format!("[{i}]");
        params.insert(format!("artist{s}"), p.artist.clone());
        params.insert(format!("track{s}"), p.track.clone());
        params.insert(
            format!("timestamp{s}"),
            p.timestamp
                .unwrap_or_else(crate::daemon::epoch_now)
                .to_string(),
        );
        put_optional(&mut params, &s, p);
    }
    params
}

/// The signature of `params` (everything but `format` and `callback`).
pub fn signature(params: &BTreeMap<String, String>, secret: &str) -> String {
    let mut base = String::new();
    for (k, v) in params {
        if k != "format" && k != "callback" {
            base.push_str(k);
            base.push_str(v);
        }
    }
    base.push_str(secret);
    format!("{:x}", Md5::digest(base.as_bytes()))
}

/// `params` with `api_sig` and `format=json` added.
fn signed(mut params: BTreeMap<String, String>, secret: &str) -> BTreeMap<String, String> {
    let sig = signature(&params, secret);
    params.insert("api_sig".into(), sig);
    params.insert("format".into(), "json".into());
    params
}

/// What a Last.fm error code means for the plays sent
/// (<https://www.last.fm/api/errorcodes>). Trouble with the session,
/// the key or the service is worth waiting out; a complaint about the
/// plays themselves isn't.
pub fn classify_error(code: u64, message: &str) -> SendError {
    let describe = format!("Last.fm error {code}: {message}");
    match code {
        // 4 authentication failed, 8 operation failed, 9 invalid session
        // key, 10 invalid API key, 11 service offline, 13 invalid signature,
        // 16 temporarily unavailable, 26 suspended API key, 29 rate limited.
        4 | 8 | 9 | 10 | 11 | 13 | 16 | 26 | 29 => SendError::Retry(describe),
        _ => SendError::Rejected(describe),
    }
}

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

    fn play(track: &str, at: i64) -> Play {
        Play {
            artist: "Pink Floyd".into(),
            track: track.into(),
            album: Some("The Dark Side of the Moon".into()),
            album_artist: None,
            duration_sec: Some(413),
            timestamp: Some(at),
        }
    }

    #[test]
    fn signs_sorted_params_with_the_secret() {
        let mut p = BTreeMap::new();
        p.insert("method".to_string(), "auth.getToken".to_string());
        p.insert("api_key".to_string(), "KEY".to_string());
        p.insert("format".to_string(), "json".to_string());
        // md5("api_keyKEYmethodauth.getTokenSECRET"), format left out.
        assert_eq!(signature(&p, "SECRET"), "66ee63a18da3c919f987b342697d913c");
    }

    #[test]
    fn batches_are_indexed() {
        let p = scrobble_params(&[play("Time", 100), play("Money", 200)]);
        assert_eq!(p["method"], "track.scrobble");
        assert_eq!(p["artist[0]"], "Pink Floyd");
        assert_eq!(p["track[0]"], "Time");
        assert_eq!(p["timestamp[0]"], "100");
        assert_eq!(p["album[0]"], "The Dark Side of the Moon");
        assert_eq!(p["duration[0]"], "413");
        assert_eq!(p["track[1]"], "Money");
        assert_eq!(p["timestamp[1]"], "200");
        assert!(!p.contains_key("albumArtist[0]"));
    }

    #[test]
    fn error_codes() {
        for code in [4, 9, 11, 16, 29] {
            assert!(
                matches!(classify_error(code, ""), SendError::Retry(_)),
                "{code}"
            );
        }
        for code in [6, 7] {
            assert!(
                matches!(classify_error(code, ""), SendError::Rejected(_)),
                "{code}"
            );
        }
    }
}