Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

16.6 KB
Raw Blame
//! Spotify through its Web API, with the access token Discord keeps for your
//! Spotify connection (what Discord's own Listen Along uses): what's playing
//! (for your status), Listen Along, your playlists, and the controller in
//! Settings → Experimental, which drives the Spotify app on your PC (or any
//! of your devices) the way Spotify Connect does. Nothing plays in RustCord.
//!
//! The token is asked of Discord once and kept for 45 minutes (it lasts an
//! hour), so controlling Spotify adds almost nothing to Discord's traffic.

use crate::http::Http;
use crate::reqlog;
use anyhow::{anyhow, Result};
use reqwest::Method;
use serde_json::{json, Value};
use std::sync::Mutex;
use std::time::{Duration, Instant};

const API: &str = "https://api.spotify.com/v1";
/// A cached token is used this long (Spotify's last an hour).
const TOKEN_FOR: Duration = Duration::from_secs(45 * 60);

/// Your Spotify account ID and Discord's token for it, and when it came.
#[derive(Default)]
pub(crate) struct TokenCache(Mutex<Option<(String, String, Instant)>>);

/// Something to tell your Spotify to do.
#[derive(Clone, Debug, PartialEq)]
pub enum Command {
    Play,
    Pause,
    Next,
    Previous,
    /// Jump to this point of the track.
    Seek(u64),
    Shuffle(bool),
    /// "off", "context" (the playlist / album) or "track".
    Repeat(String),
    Volume(u8),
    /// Play a playlist (or album) by its `spotify:` URI.
    PlayContext(String),
    /// Move playback to this device (and keep it paused).
    Transfer(String),
}

/// What your Spotify is doing.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Player {
    pub playing: bool,
    pub track: String,
    pub artists: String,
    /// The album cover (the ~64 px one).
    pub art: Option<String>,
    pub progress_ms: u64,
    pub duration_ms: u64,
    pub shuffle: bool,
    pub repeat: String,
    pub volume: Option<u8>,
    /// The device playing ("DESKTOP-ABC", "iPhone").
    pub device: Option<String>,
    /// The track's page on open.spotify.com.
    pub link: Option<String>,
}

/// One of your devices Spotify knows about.
#[derive(Clone, Debug, PartialEq)]
pub struct Device {
    pub id: String,
    pub name: String,
    /// "Computer", "Smartphone", "Speaker"…
    pub kind: String,
    pub active: bool,
}

/// A playlist: name, `spotify:` URI, cover.
#[derive(Clone, Debug, PartialEq)]
pub struct Playlist {
    pub name: String,
    pub uri: String,
    pub image: Option<String>,
    pub link: String,
}

fn player_from(v: &Value) -> Option<Player> {
    let item = &v["item"];
    if item.is_null() {
        return None;
    }
    let artists = item["artists"].as_array().map(|a| a.iter().filter_map(|x| x["name"].as_str()).collect::<Vec<_>>().join(", ")).unwrap_or_default();
    // (Episodes have their show instead of artists.)
    let artists = if artists.is_empty() { item["show"]["name"].as_str().unwrap_or_default().to_string() } else { artists };
    let images = item["album"]["images"].as_array().or_else(|| item["images"].as_array());
    let art = images.and_then(|imgs| imgs.iter().filter_map(|i| i["url"].as_str().map(|u| (i["width"].as_u64().unwrap_or(0), u))).min_by_key(|(w, _)| w.abs_diff(64)).map(|(_, u)| u.to_string()));
    Some(Player {
        playing: v["is_playing"].as_bool().unwrap_or(false),
        track: item["name"].as_str().unwrap_or_default().to_string(),
        artists,
        art,
        progress_ms: v["progress_ms"].as_u64().unwrap_or(0),
        duration_ms: item["duration_ms"].as_u64().unwrap_or(0),
        shuffle: v["shuffle_state"].as_bool().unwrap_or(false),
        repeat: v["repeat_state"].as_str().unwrap_or("off").to_string(),
        // Devices that don't take volume changes (phones, some speakers) say so.
        volume: v["device"]["volume_percent"].as_u64().filter(|_| v["device"]["supports_volume"].as_bool() != Some(false)).map(|p| p.min(100) as u8),
        device: v["device"]["name"].as_str().map(String::from),
        link: item["external_urls"]["spotify"].as_str().map(String::from),
    })
}

impl Command {
    /// Spotify's endpoint for it: method, path (under /v1/me/player), body.
    fn request(&self) -> (Method, String, Option<Value>) {
        match self {
            Command::Play => (Method::PUT, "/play".into(), None),
            Command::Pause => (Method::PUT, "/pause".into(), None),
            Command::Next => (Method::POST, "/next".into(), None),
            Command::Previous => (Method::POST, "/previous".into(), None),
            Command::Seek(ms) => (Method::PUT, format!("/seek?position_ms={ms}"), None),
            Command::Shuffle(on) => (Method::PUT, format!("/shuffle?state={on}"), None),
            Command::Repeat(mode) => {
                let mode = if matches!(mode.as_str(), "track" | "context") { mode.as_str() } else { "off" };
                (Method::PUT, format!("/repeat?state={mode}"), None)
            }
            Command::Volume(v) => (Method::PUT, format!("/volume?volume_percent={}", v.min(&100)), None),
            Command::PlayContext(uri) => (Method::PUT, "/play".into(), Some(json!({ "context_uri": uri }))),
            Command::Transfer(id) => (Method::PUT, String::new(), Some(json!({ "device_ids": [id], "play": false }))),
        }
    }
}

impl Http {
    /// Your Spotify account ID and Discord's token for it (cached).
    async fn spotify_token(&self) -> Result<(String, String)> {
        if let Some((id, token, at)) = self.spotify.0.lock().ok().and_then(|c| c.clone()) {
            if at.elapsed() < TOKEN_FOR {
                return Ok((id, token));
            }
        }
        let conns = self.request(Method::GET, "/users/@me/connections", None).await?;
        let spotify = conns
            .as_array()
            .and_then(|a| a.iter().find(|c| c["type"] == "spotify"))
            .ok_or_else(|| anyhow!("Connect Spotify to your account first (Settings → Connections)."))?;
        let id = spotify["id"].as_str().unwrap_or_default().to_string();
        let token = match self.request(Method::GET, &format!("/users/@me/connections/spotify/{id}/access-token"), None).await {
            Ok(v) => v["access_token"].as_str().map(String::from),
            Err(_) => None,
        }
        .or_else(|| spotify["access_token"].as_str().map(String::from))
        .ok_or_else(|| anyhow!("Discord didn't give a Spotify token. Reconnect Spotify in Settings → Connections."))?;
        if let Ok(mut c) = self.spotify.0.lock() {
            *c = Some((id.clone(), token.clone(), Instant::now()));
        }
        Ok((id, token))
    }

    fn forget_spotify_token(&self) {
        if let Ok(mut c) = self.spotify.0.lock() {
            *c = None;
        }
    }

    /// One Spotify Web API call: (status, JSON body if any). A 401 (the
    /// token ran out) is tried once more with a fresh token.
    async fn spotify_call(&self, method: Method, url: &str, body: Option<&Value>) -> Result<(u16, Option<Value>)> {
        for attempt in 0..2 {
            let (_, token) = self.spotify_token().await?;
            let mut req = self.plain_client().request(method.clone(), url).bearer_auth(token);
            req = match body {
                Some(b) => req.json(b),
                None if method != Method::GET => req.header("Content-Length", "0"),
                None => req,
            };
            let sent = Instant::now();
            let resp = match req.send().await {
                Ok(r) => r,
                Err(e) => {
                    reqlog::record_media(method.as_str(), url, sent, None, 0, Some("couldn't reach Spotify".into()));
                    return Err(anyhow!("couldn't reach Spotify ({})", e.without_url()));
                }
            };
            let status = resp.status().as_u16();
            if status == 401 && attempt == 0 {
                reqlog::record_media(method.as_str(), url, sent, Some(401), 0, Some("token ran out; getting a new one".into()));
                self.forget_spotify_token();
                continue;
            }
            let text = resp.text().await.unwrap_or_default();
            reqlog::record_media(method.as_str(), url, sent, Some(status), text.len() as u64, None);
            return Ok((status, serde_json::from_str(&text).ok()));
        }
        Err(anyhow!("Spotify didn't accept the token. Reconnect Spotify in Settings → Connections."))
    }

    /// Listen Along, the way Discord does it: play `track` from `position_ms`
    /// on your active Spotify device.
    pub async fn spotify_play(&self, track: &str, position_ms: u64) -> Result<()> {
        let body = json!({ "uris": [format!("spotify:track:{track}")], "position_ms": position_ms });
        let (status, _) = self.spotify_call(Method::PUT, &format!("{API}/me/player/play"), Some(&body)).await?;
        match status {
            200..=299 => Ok(()),
            404 => Err(anyhow!("Open Spotify on one of your devices first, then try again.")),
            403 => Err(anyhow!("Listen Along needs Spotify Premium.")),
            s => Err(anyhow!("Spotify returned {s}")),
        }
    }

    /// The token for showing what you listen to: `None` when Spotify isn't connected or
    /// its connection has "Display Spotify as your status" switched off.
    pub async fn spotify_status_token(&self) -> Result<Option<String>> {
        let conns = self.request(Method::GET, "/users/@me/connections", None).await?;
        let Some(spotify) = conns.as_array().and_then(|a| a.iter().find(|c| c["type"] == "spotify")) else { return Ok(None) };
        if spotify["show_activity"].as_bool() == Some(false) || spotify["revoked"].as_bool() == Some(true) {
            return Ok(None);
        }
        Ok(self.spotify_token().await.ok().map(|(_, token)| token))
    }

    /// What your Spotify is playing right now (Spotify's Web API "currently playing"
    /// object), `None` when nothing is. `Err` carries the HTTP status as text ("401": the
    /// token has expired).
    pub async fn spotify_playing(&self, token: &str) -> Result<Option<Value>> {
        let url = format!("{API}/me/player/currently-playing");
        let sent = Instant::now();
        let resp = self.plain_client().get(&url).bearer_auth(token).send().await.map_err(|e| anyhow!("couldn't reach Spotify ({})", e.without_url()))?;
        let status = resp.status().as_u16();
        reqlog::record_media("GET", &url, sent, Some(status), 0, None);
        match status {
            200 => Ok(resp.json::<Value>().await.ok()),
            202 | 204 => Ok(None),
            401 => {
                self.forget_spotify_token();
                Err(anyhow!("401"))
            }
            s => Err(anyhow!("{s}")),
        }
    }

    /// The playlists on your Spotify profile, as (name, link): what
    /// `/spotify playlist` offers. Public ones only (the ones your profile
    /// shows), so nothing private gets pasted into a chat.
    pub async fn spotify_playlists(&self) -> Result<Vec<(String, String)>> {
        let (id, _) = self.spotify_token().await?;
        let (status, v) = self.spotify_call(Method::GET, &format!("{API}/users/{id}/playlists?limit=50"), None).await?;
        if !(200..300).contains(&status) {
            return Err(anyhow!("Spotify returned {status}"));
        }
        Ok(playlists_from(&v.unwrap_or_default()).into_iter().filter(|p| p.1).map(|(p, _)| (p.name, p.link)).collect())
    }

    // ---- the controller ----

    /// What your Spotify is doing now (`None`: nothing is playing anywhere),
    /// and your devices when nothing is (to offer "play on this PC").
    pub async fn spotify_player(&self) -> Result<(Option<Player>, Vec<Device>)> {
        let (status, v) = self.spotify_call(Method::GET, &format!("{API}/me/player?additional_types=episode"), None).await?;
        let player = match status {
            200 => v.as_ref().and_then(player_from),
            204 => None,
            // Without permission to read the player: what's playing, at least.
            403 => {
                let (status, v) = self.spotify_call(Method::GET, &format!("{API}/me/player/currently-playing"), None).await?;
                if status == 200 { v.as_ref().and_then(player_from) } else { None }
            }
            429 => return Err(anyhow!("Spotify asked RustCord to slow down; trying again shortly.")),
            s => return Err(anyhow!("Spotify returned {s}")),
        };
        let devices = if player.is_none() { self.spotify_devices().await.unwrap_or_default() } else { Vec::new() };
        Ok((player, devices))
    }

    pub async fn spotify_devices(&self) -> Result<Vec<Device>> {
        let (_, v) = self.spotify_call(Method::GET, &format!("{API}/me/player/devices"), None).await?;
        Ok(v.and_then(|v| v["devices"].as_array().cloned())
            .unwrap_or_default()
            .iter()
            .filter_map(|d| {
                Some(Device {
                    id: d["id"].as_str()?.to_string(),
                    name: d["name"].as_str().unwrap_or_default().to_string(),
                    kind: d["type"].as_str().unwrap_or_default().to_string(),
                    active: d["is_active"].as_bool().unwrap_or(false),
                })
            })
            .collect())
    }

    /// Do `cmd` on your Spotify.
    pub async fn spotify_command(&self, cmd: &Command) -> Result<()> {
        let (method, path, body) = cmd.request();
        let (status, _) = self.spotify_call(method, &format!("{API}/me/player{path}"), body.as_ref()).await?;
        match status {
            200..=299 => Ok(()),
            404 => Err(anyhow!("Spotify isn't open on any of your devices. Open the Spotify app on your PC, then try again.")),
            403 => Err(anyhow!("Spotify only lets Premium accounts be controlled from other apps.")),
            429 => Err(anyhow!("Spotify asked RustCord to slow down. Try again in a moment.")),
            s => Err(anyhow!("Spotify returned {s}")),
        }
    }

    /// Your playlists, private ones included when Discord's token may read
    /// them (else the public ones on your profile).
    pub async fn spotify_my_playlists(&self) -> Result<Vec<Playlist>> {
        let (status, v) = self.spotify_call(Method::GET, &format!("{API}/me/playlists?limit=50"), None).await?;
        let v = if (200..300).contains(&status) {
            v.unwrap_or_default()
        } else {
            let (id, _) = self.spotify_token().await?;
            let (status, v) = self.spotify_call(Method::GET, &format!("{API}/users/{id}/playlists?limit=50"), None).await?;
            if !(200..300).contains(&status) {
                return Err(anyhow!("Spotify returned {status}"));
            }
            v.unwrap_or_default()
        };
        Ok(playlists_from(&v).into_iter().map(|(p, _)| p).collect())
    }
}

/// Playlists in a Spotify list answer, each with whether it is public.
fn playlists_from(v: &Value) -> Vec<(Playlist, bool)> {
    v["items"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|p| {
            let name = p["name"].as_str().filter(|n| !n.trim().is_empty())?.to_string();
            let id = p["id"].as_str()?;
            let uri = p["uri"].as_str().map(String::from).unwrap_or_else(|| format!("spotify:playlist:{id}"));
            let link = p["external_urls"]["spotify"].as_str().map(String::from).unwrap_or_else(|| format!("https://open.spotify.com/playlist/{id}"));
            let image = p["images"].as_array().and_then(|i| i.last()).and_then(|i| i["url"].as_str()).map(String::from);
            Some((Playlist { name, uri, image, link }, p["public"].as_bool() != Some(false)))
        })
        .collect()
}

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

    #[test]
    fn reads_spotifys_player_answer() {
        let v = json!({
            "is_playing": true, "progress_ms": 61000, "shuffle_state": true, "repeat_state": "context",
            "device": { "name": "DESKTOP", "volume_percent": 55 },
            "item": { "name": "Song", "duration_ms": 200000, "artists": [{ "name": "A" }, { "name": "B" }],
                      "album": { "images": [{ "url": "big", "width": 640 }, { "url": "small", "width": 64 }] },
                      "external_urls": { "spotify": "https://open.spotify.com/track/x" } }
        });
        let p = player_from(&v).unwrap();
        assert_eq!((p.track.as_str(), p.artists.as_str(), p.art.as_deref()), ("Song", "A, B", Some("small")));
        assert!(p.playing && p.shuffle && p.repeat == "context" && p.volume == Some(55));
        assert!(player_from(&json!({ "is_playing": false, "item": null })).is_none());
    }

    #[test]
    fn commands_map_to_spotifys_endpoints() {
        assert_eq!(Command::Seek(1500).request().1, "/seek?position_ms=1500");
        assert_eq!(Command::Repeat("nonsense".into()).request().1, "/repeat?state=off");
        assert_eq!(Command::Volume(250).request().1, "/volume?volume_percent=100");
        assert_eq!(Command::Transfer("d".into()).request().1, "");
    }
}