Skip to content

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

21.9 KB
Raw Blame
//! Discord Rich Presence over local IPC: what games use to show "Playing …"
//! with their art, details and elapsed time.
//!
//! RustCord serves Discord's `\\.\pipe\discord-ipc-N` pipe the way the desktop
//! app (and Vesktop's arRPC) does. A game connects, says hello with its
//! application ID, gets READY with your user, and sends SET_ACTIVITY; the
//! activity goes into your presence next to your status and custom status. The
//! first free pipe is used, so with the official app open, games keep talking
//! to it.
//!
//! Only Rich Presence is served. The rest of the RPC API (OAuth authorize,
//! guild and voice control) answers with an error: it would hand your account
//! to any program on the PC.

use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Biggest frame RustCord accepts (activities are a few hundred bytes).
const MAX_FRAME: usize = 64 * 1024;

#[derive(Debug, Clone)]
pub enum RpcEvent {
    /// A program set (Some) or cleared (None) its activity.
    Activity { socket: u64, client_id: String, activity: Option<Value> },
    /// It disconnected (its activity goes with it).
    Closed { socket: u64 },
}

/// The user READY reports to games (set once you're logged in).
pub type SharedUser = Arc<Mutex<Value>>;

#[cfg(windows)]
pub async fn serve<F>(user: SharedUser, on_event: F)
where
    F: Fn(RpcEvent) + Send + Sync + Clone + 'static,
{
    use tokio::net::windows::named_pipe::ServerOptions;
    let mut chosen = None;
    for n in 0..10 {
        let name = format!(r"\\.\pipe\discord-ipc-{n}");
        if let Ok(server) = ServerOptions::new().first_pipe_instance(true).create(&name) {
            chosen = Some((name, server));
            break;
        }
    }
    let Some((name, mut server)) = chosen else {
        log::warn!("rpc: every discord-ipc pipe is in use; Rich Presence is off");
        return;
    };
    log::info!("rpc: serving Rich Presence on {name}");
    let mut next = 1u64;
    loop {
        if let Err(e) = server.connect().await {
            log::warn!("rpc: accept failed: {e}");
        } else {
            let id = next;
            next += 1;
            let (user, on_event) = (user.clone(), on_event.clone());
            let conn = server;
            tokio::spawn(async move { handle(conn, id, user, on_event).await });
        }
        server = match ServerOptions::new().create(&name) {
            Ok(s) => s,
            Err(e) => {
                log::warn!("rpc: couldn't reopen {name}: {e}");
                return;
            }
        };
    }
}

/// Linux and macOS: Discord's `discord-ipc-N` Unix socket, in the runtime folder
/// where games look for it.
#[cfg(unix)]
pub async fn serve<F>(user: SharedUser, on_event: F)
where
    F: Fn(RpcEvent) + Send + Sync + Clone + 'static,
{
    use tokio::net::UnixListener;
    let dir = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"]
        .iter()
        .find_map(std::env::var_os)
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| "/tmp".into());
    let mut chosen = None;
    for n in 0..10 {
        let path = dir.join(format!("discord-ipc-{n}"));
        // A socket left behind by a client that quit without cleaning up:
        // nobody answers on it any more, so it can go.
        if path.exists() && std::os::unix::net::UnixStream::connect(&path).is_err() {
            let _ = std::fs::remove_file(&path);
        }
        if let Ok(listener) = UnixListener::bind(&path) {
            chosen = Some((path, listener));
            break;
        }
    }
    let Some((path, listener)) = chosen else {
        log::warn!("rpc: every discord-ipc socket is in use; Rich Presence is off");
        return;
    };
    // Only this user may connect. Without XDG_RUNTIME_DIR the socket sits in
    // a shared folder, and its mode would otherwise depend on the umask. Games
    // run as the same user, so nothing changes for them.
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) {
            log::warn!("rpc: could not make {} private: {e}", path.display());
        }
    }
    log::info!("rpc: serving Rich Presence on {}", path.display());
    let mut next = 1u64;
    loop {
        match listener.accept().await {
            Ok((conn, _)) => {
                let id = next;
                next += 1;
                let (user, on_event) = (user.clone(), on_event.clone());
                tokio::spawn(async move { handle(conn, id, user, on_event).await });
            }
            Err(e) => {
                log::warn!("rpc: accept failed: {e}");
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            }
        }
    }
}

async fn read_frame<S: tokio::io::AsyncRead + Unpin>(s: &mut S) -> std::io::Result<(u32, Value)> {
    use tokio::io::AsyncReadExt;
    let mut head = [0u8; 8];
    s.read_exact(&mut head).await?;
    let op = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
    let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
    if len > MAX_FRAME {
        return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "frame too big"));
    }
    let mut body = vec![0u8; len];
    s.read_exact(&mut body).await?;
    Ok((op, serde_json::from_slice(&body).unwrap_or(Value::Null)))
}

async fn write_frame<S: tokio::io::AsyncWrite + Unpin>(s: &mut S, op: u32, payload: &Value) -> std::io::Result<()> {
    use tokio::io::AsyncWriteExt;
    let body = payload.to_string().into_bytes();
    let mut frame = Vec::with_capacity(8 + body.len());
    frame.extend_from_slice(&op.to_le_bytes());
    frame.extend_from_slice(&(body.len() as u32).to_le_bytes());
    frame.extend_from_slice(&body);
    s.write_all(&frame).await?;
    s.flush().await
}

/// One program's connection: handshake, then commands until it goes away.
async fn handle<S, F>(mut s: S, socket: u64, user: SharedUser, on_event: F)
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
    F: Fn(RpcEvent),
{
    let mut client_id: Option<String> = None;
    while let Ok((op, payload)) = read_frame(&mut s).await {
        let reply = match op {
            // Handshake: {"v": 1, "client_id": "…"}
            0 => {
                let id = payload["client_id"].as_str().filter(|c| !c.is_empty() && c.chars().all(|ch| ch.is_ascii_digit())).map(String::from);
                let Some(id) = id else {
                    let _ = write_frame(&mut s, 2, &json!({ "code": 4000, "message": "Invalid Client ID" })).await;
                    break;
                };
                log::info!("rpc: program connected (application {id})");
                client_id = Some(id);
                let u = user.lock().map(|u| u.clone()).unwrap_or(Value::Null);
                Some((1, ready(u)))
            }
            1 => {
                let Some(cid) = client_id.clone() else { break };
                let cmd = payload["cmd"].as_str().unwrap_or("").to_string();
                let nonce = payload["nonce"].clone();
                Some((1, command(&cmd, &payload, nonce, socket, &cid, &on_event)))
            }
            2 => break,
            // Ping → pong with the same body.
            3 => Some((4, payload)),
            _ => None,
        };
        if let Some((op, body)) = reply {
            if write_frame(&mut s, op, &body).await.is_err() {
                break;
            }
        }
    }
    if client_id.is_some() {
        on_event(RpcEvent::Closed { socket });
    }
}

fn ready(user: Value) -> Value {
    json!({
        "cmd": "DISPATCH",
        "evt": "READY",
        "data": {
            "v": 1,
            "config": { "cdn_host": "cdn.discordapp.com", "api_endpoint": "//discord.com/api", "environment": "production" },
            "user": user,
        },
        "nonce": Value::Null,
    })
}

/// Answer one command (SET_ACTIVITY does the work; SUBSCRIBE is acknowledged).
fn command(cmd: &str, payload: &Value, nonce: Value, socket: u64, client_id: &str, on_event: &impl Fn(RpcEvent)) -> Value {
    match cmd {
        "SET_ACTIVITY" => {
            let activity = payload["args"]["activity"].clone();
            let activity = (activity.is_object()).then_some(activity);
            on_event(RpcEvent::Activity { socket, client_id: client_id.to_string(), activity: activity.clone() });
            let mut data = activity.unwrap_or(Value::Null);
            if data.is_object() {
                data["application_id"] = json!(client_id);
                data["type"] = json!(activity_type(&data));
            }
            json!({ "cmd": "SET_ACTIVITY", "data": data, "evt": Value::Null, "nonce": nonce })
        }
        "SUBSCRIBE" | "UNSUBSCRIBE" => json!({ "cmd": cmd, "data": { "evt": payload["evt"] }, "evt": Value::Null, "nonce": nonce }),
        _ => json!({ "cmd": cmd, "evt": "ERROR", "data": { "code": 1000, "message": "RustCord only supports Rich Presence" }, "nonce": nonce }),
    }
}

/// Activity types a game may set: Playing, Listening, Watching, Competing.
fn activity_type(a: &Value) -> u64 {
    match a["type"].as_u64() {
        Some(t @ (0 | 2 | 3 | 5)) => t,
        _ => 0,
    }
}

/// The two asset fields that name a picture (the rest are texts and links).
const IMAGE_KEYS: [&str; 2] = ["large_image", "small_image"];

/// Turn an RPC activity into a gateway one: the application's name and ID,
/// timestamps in milliseconds, buttons as labels + `metadata.button_urls`,
/// and its pictures the way the gateway wants them. A game names a picture
/// by the *key* it was uploaded under ("map_forest") or by an image URL;
/// presences carry the asset's ID or an `mp:` external-asset path. `assets`
/// maps both: key → ID (this application's) and URL → `mp:…`. A picture
/// that is in neither is left out, as Discord's client does.
pub fn to_gateway(client_id: &str, name: &str, a: &Value, assets: &HashMap<String, String>) -> Value {
    let mut out = json!({ "application_id": client_id, "name": name, "type": activity_type(a) });
    for k in ["details", "state", "party", "secrets", "instance", "details_url", "state_url", "status_display_type"] {
        if !a[k].is_null() {
            out[k] = a[k].clone();
        }
    }
    if a["instance"].as_bool() == Some(true) {
        out["flags"] = json!(1);
    }
    let ms = |v: &Value| {
        v.as_f64().map(|t| {
            // Seconds (as most games send) or milliseconds.
            let t = if t < 1e12 { t * 1000.0 } else { t };
            json!(t.round() as i64)
        })
    };
    let mut ts = serde_json::Map::new();
    for k in ["start", "end"] {
        if let Some(v) = ms(&a["timestamps"][k]) {
            ts.insert(k.into(), v);
        }
    }
    if !ts.is_empty() {
        out["timestamps"] = Value::Object(ts);
    }
    if let Some(src) = a["assets"].as_object() {
        let mut dst = serde_json::Map::new();
        for (k, v) in src {
            if !IMAGE_KEYS.contains(&k.as_str()) {
                // Hover texts, and the links the pictures open.
                if matches!(k.as_str(), "large_text" | "small_text" | "large_url" | "small_url") && v.is_string() {
                    dst.insert(k.clone(), v.clone());
                }
                continue;
            }
            let Some(key) = v.as_str().filter(|s| !s.is_empty()) else { continue };
            // Already what the gateway takes: an asset ID or a media-proxy path.
            let ready = key.starts_with("mp:") || key.chars().all(|c| c.is_ascii_digit());
            match (ready, assets.get(key)) {
                (true, _) => drop(dst.insert(k.clone(), json!(key))),
                (false, Some(resolved)) => drop(dst.insert(k.clone(), json!(resolved))),
                (false, None) => {}
            }
        }
        if !dst.is_empty() {
            out["assets"] = Value::Object(dst);
        }
    }
    if let Some(buttons) = a["buttons"].as_array().filter(|b| !b.is_empty()) {
        let labels: Vec<Value> = buttons.iter().filter_map(|b| b["label"].as_str()).take(2).map(|s| json!(s)).collect();
        let urls: Vec<Value> = buttons.iter().filter_map(|b| b["url"].as_str()).take(2).map(|s| json!(s)).collect();
        if !labels.is_empty() && labels.len() == urls.len() {
            out["buttons"] = Value::Array(labels);
            out["metadata"] = json!({ "button_urls": urls });
        }
    }
    out
}

/// Image URLs an activity uses (they need converting to external assets).
pub fn image_urls(a: &Value) -> Vec<String> {
    IMAGE_KEYS.iter().filter_map(|k| a["assets"][k].as_str()).filter(|s| s.starts_with("http")).map(String::from).collect()
}

/// Does the activity name a picture by its key (to look up among the
/// application's uploaded assets)?
pub fn names_asset_keys(a: &Value) -> bool {
    IMAGE_KEYS
        .iter()
        .filter_map(|k| a["assets"][k].as_str())
        .any(|s| !s.is_empty() && !s.starts_with("http") && !s.starts_with("mp:") && !s.chars().all(|c| c.is_ascii_digit()))
}

/// An application's uploaded pictures (`GET /oauth2/applications/{id}/assets`)
/// as key → asset ID.
pub fn asset_ids(list: &Value) -> HashMap<String, String> {
    list.as_array().into_iter().flatten().filter_map(|a| Some((a["name"].as_str()?.to_string(), a["id"].as_str()?.to_string()))).collect()
}

/// "Listening to Spotify", as Discord's own client builds it from Spotify's "currently
/// playing" object: the track, its artists, the album art, when it started and ends.
/// `None` when nothing is playing (or it isn't a track: podcasts aren't shown).
pub fn spotify_activity(playing: &Value, user: u64, now_ms: u64) -> Option<Value> {
    if playing["is_playing"].as_bool() != Some(true) || playing["currently_playing_type"].as_str().is_some_and(|t| t != "track") {
        return None;
    }
    let item = &playing["item"];
    let id = item["id"].as_str()?;
    let name = item["name"].as_str()?;
    let duration = item["duration_ms"].as_u64()?;
    let start = now_ms.saturating_sub(playing["progress_ms"].as_u64().unwrap_or(0));
    let artists: Vec<&str> = item["artists"].as_array().into_iter().flatten().filter_map(|a| a["name"].as_str()).collect();
    let artist_ids: Vec<&str> = item["artists"].as_array().into_iter().flatten().filter_map(|a| a["id"].as_str()).collect();
    let mut assets = json!({});
    if let Some(album) = item["album"]["name"].as_str() {
        assets["large_text"] = json!(album);
    }
    // Album art: Discord names it by Spotify's image id.
    if let Some(art) = item["album"]["images"][0]["url"].as_str().and_then(|u| u.rsplit('/').next()).filter(|a| !a.is_empty()) {
        assets["large_image"] = json!(format!("spotify:{art}"));
    }
    let mut activity = json!({
        "type": 2,
        "name": "Spotify",
        "details": name,
        "assets": assets,
        "timestamps": { "start": start, "end": start + duration },
        "party": { "id": format!("spotify:{user}") },
        "sync_id": id,
        // Sync + Play: the "Listen Along" and "Play on Spotify" buttons.
        "flags": 48,
        "metadata": { "context_uri": playing["context"]["uri"], "album_id": item["album"]["id"], "artist_ids": artist_ids },
    });
    if !artists.is_empty() {
        activity["state"] = json!(artists.join("; "));
    }
    Some(activity)
}

/// Is `b` the same listening as `a` (same track, started within three seconds)? Polls
/// jitter by a second or so; a seek or a new track is a change.
pub fn spotify_same(a: Option<&Value>, b: Option<&Value>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => {
            a["sync_id"] == b["sync_id"]
                && a["timestamps"]["start"].as_u64().zip(b["timestamps"]["start"].as_u64()).is_some_and(|(x, y)| x.abs_diff(y) < 3000)
        }
        _ => false,
    }
}

/// Your presence with the games' activities added (none while invisible).
pub fn compose(base: &Value, extra: &[Value]) -> Value {
    let mut p = base.clone();
    if p["status"].as_str() == Some("invisible") || extra.is_empty() {
        return p;
    }
    if let Some(list) = p["activities"].as_array_mut() {
        list.extend(extra.iter().cloned());
    } else {
        p["activities"] = Value::Array(extra.to_vec());
    }
    p
}

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

    #[test]
    fn spotify_tracks_become_listening_activities() {
        let playing = json!({
            "is_playing": true, "currently_playing_type": "track", "progress_ms": 30_000,
            "context": { "uri": "spotify:playlist:abc" },
            "item": {
                "id": "track1", "name": "Song", "duration_ms": 200_000,
                "artists": [{ "name": "One", "id": "a1" }, { "name": "Two", "id": "a2" }],
                "album": { "id": "al1", "name": "Album", "images": [{ "url": "https://i.scdn.co/image/ab67616d0000b273deadbeef" }] }
            }
        });
        let a = spotify_activity(&playing, 42, 1_000_000).unwrap();
        assert_eq!(a["type"], 2);
        assert_eq!(a["name"], "Spotify");
        assert_eq!(a["details"], "Song");
        assert_eq!(a["state"], "One; Two");
        assert_eq!(a["assets"]["large_image"], "spotify:ab67616d0000b273deadbeef");
        assert_eq!(a["assets"]["large_text"], "Album");
        assert_eq!(a["timestamps"]["start"], 970_000);
        assert_eq!(a["timestamps"]["end"], 1_170_000);
        assert_eq!(a["party"]["id"], "spotify:42");
        assert_eq!(a["sync_id"], "track1");
        // Paused, or a podcast: nothing to show.
        let mut paused = playing.clone();
        paused["is_playing"] = json!(false);
        assert!(spotify_activity(&paused, 42, 1_000_000).is_none());
        let mut episode = playing.clone();
        episode["currently_playing_type"] = json!("episode");
        assert!(spotify_activity(&episode, 42, 1_000_000).is_none());
        // A second look a moment later is the same listening; a seek or a new track is not.
        let later = spotify_activity(&playing, 42, 1_001_200).unwrap();
        assert!(spotify_same(Some(&a), Some(&later)));
        let sought = spotify_activity(&playing, 42, 1_060_000).unwrap();
        assert!(!spotify_same(Some(&a), Some(&sought)));
        assert!(!spotify_same(Some(&a), None));
        assert!(spotify_same(None, None));
    }

    #[test]
    fn activities_convert_like_discords_client() {
        let a = json!({
            "details": "Ranked", "state": "In queue", "type": 7,
            "timestamps": { "start": 1_700_000_000u64 },
            "assets": { "large_image": "map_icon", "small_image": "https://example.com/a.png", "large_text": "Map", "large_url": "https://example.com/map" },
            "buttons": [{ "label": "Watch", "url": "https://example.com/w" }],
            "instance": true,
        });
        assert!(names_asset_keys(&a));
        let mut assets = asset_ids(&json!([{ "id": "555", "type": 1, "name": "map_icon" }, { "id": "556", "type": 1, "name": "other" }]));
        assets.insert("https://example.com/a.png".to_string(), "mp:external/abc".to_string());
        let g = to_gateway("123", "Some Game", &a, &assets);
        assert_eq!(g["name"], "Some Game");
        assert_eq!(g["application_id"], "123");
        assert_eq!(g["type"], 0, "unknown types fall back to Playing");
        assert_eq!(g["timestamps"]["start"], 1_700_000_000_000i64);
        // The key becomes the asset's ID; the link stays a link.
        assert_eq!(g["assets"]["large_image"], "555");
        assert_eq!(g["assets"]["large_text"], "Map");
        assert_eq!(g["assets"]["large_url"], "https://example.com/map");
        // A key the application never uploaded is left out; IDs pass through.
        let bare = to_gateway("123", "Some Game", &json!({ "assets": { "large_image": "nope", "small_image": "987654321" } }), &assets);
        assert!(bare["assets"]["large_image"].is_null());
        assert_eq!(bare["assets"]["small_image"], "987654321");
        assert_eq!(g["assets"]["small_image"], "mp:external/abc");
        assert_eq!(g["buttons"], json!(["Watch"]));
        assert_eq!(g["metadata"]["button_urls"], json!(["https://example.com/w"]));
        assert_eq!(g["flags"], 1);
        assert_eq!(image_urls(&a), vec!["https://example.com/a.png".to_string()]);
    }

    #[test]
    fn presence_keeps_custom_status_and_hides_games_when_invisible() {
        let base = json!({ "status": "online", "since": 0, "activities": [{ "type": 4, "name": "Custom Status" }], "afk": false });
        let game = json!({ "type": 0, "name": "Game" });
        let p = compose(&base, &[game.clone()]);
        assert_eq!(p["activities"].as_array().unwrap().len(), 2);
        let inv = json!({ "status": "invisible", "since": 0, "activities": [], "afk": false });
        assert_eq!(compose(&inv, &[game])["activities"].as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn handshake_then_set_activity_round_trip() {
        let (mut client, server) = tokio::io::duplex(4096);
        let user: SharedUser = Arc::new(Mutex::new(json!({ "id": "1", "username": "me" })));
        let seen = Arc::new(Mutex::new(Vec::new()));
        let s2 = seen.clone();
        let task = tokio::spawn(handle(server, 7, user, move |e| s2.lock().unwrap().push(e)));
        write_frame(&mut client, 0, &json!({ "v": 1, "client_id": "42" })).await.unwrap();
        let (op, ready) = read_frame(&mut client).await.unwrap();
        assert_eq!(op, 1);
        assert_eq!(ready["evt"], "READY");
        assert_eq!(ready["data"]["user"]["username"], "me");
        write_frame(&mut client, 1, &json!({ "cmd": "SET_ACTIVITY", "args": { "pid": 1, "activity": { "state": "hi" } }, "nonce": "n1" })).await.unwrap();
        let (_, reply) = read_frame(&mut client).await.unwrap();
        assert_eq!(reply["nonce"], "n1");
        assert_eq!(reply["data"]["application_id"], "42");
        write_frame(&mut client, 1, &json!({ "cmd": "AUTHORIZE", "args": {}, "nonce": "n2" })).await.unwrap();
        let (_, err) = read_frame(&mut client).await.unwrap();
        assert_eq!(err["evt"], "ERROR");
        drop(client);
        task.await.unwrap();
        let seen = seen.lock().unwrap();
        assert!(matches!(&seen[0], RpcEvent::Activity { socket: 7, client_id, activity: Some(_) } if client_id == "42"));
        assert!(matches!(seen.last(), Some(RpcEvent::Closed { socket: 7 })));
    }
}