arcane-sdk 0.15.0

Arcane Powered game SDK core (ownership tickets, DRM checks)
Documentation
//! Friends: who this player has on Arcane, who is online, and who is in this
//! game right now.
//!
//! One call, [`Friends::list`], and it is **synchronous on the calling thread**
//! — a single local loopback round trip, on the order of a millisecond. Call it
//! when a menu opens or on a timer of your own, never from the render loop.
//!
//! The SDK keeps no list of its own: the Arcane desktop app caches for 15
//! seconds and reports [`FriendList::stale`] when the answer came from that
//! cache while it was offline. [`Friends::send_request`] asks someone met in a
//! lobby to be friends; accepting, chat and the overlay stay in the launcher.

use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::desktop::{get_json, offline_only, post_json, DesktopCall, OFFLINE_ONLY_ENV};
use crate::error::SdkError;
use crate::p2p::validate_id;

const CALL_TIMEOUT: Duration = Duration::from_secs(5);
const FRIENDS_PATH: &str = "/v1/friends";
const FRIEND_REQUESTS_PATH: &str = "/v1/friends/requests";

/// One friend of the signed-in Arcane account, with their presence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Friend {
    /// The friend's Arcane account id — the value Arcane identifies them by.
    pub user_id: String,
    /// Their display name on Arcane.
    pub pseudo: String,
    /// Whether they are signed in to Arcane right now.
    pub online: bool,
    /// Whether they are playing **this** title right now — the title named by
    /// `ARCANE_GAME_ID`.
    pub in_game: bool,
    /// Whether [`Friend::lobby_id`] has a free slot. Check it before joining
    /// with [`crate::P2p::join`].
    pub joinable: bool,
    /// The lobby they are in, when it is a lobby of this title other than a
    /// `code` lobby, full or not. `None` otherwise, including for a lobby of
    /// another title.
    pub lobby_id: Option<String>,
}

/// What the Arcane desktop app knows about this player's friends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FriendList {
    /// The friends, in the order the desktop app returned them.
    pub friends: Vec<Friend>,
    /// Whether the desktop app answered from its cache because it is offline.
    /// The list is still usable — presence may simply be a few minutes old.
    pub stale: bool,
}

#[derive(Debug, Deserialize)]
struct WireFriendList {
    #[serde(default)]
    friends: Vec<WireFriend>,
    #[serde(default)]
    stale: bool,
}

#[derive(Debug, Deserialize)]
struct WireFriend {
    user_id: String,
    #[serde(default)]
    pseudo: String,
    #[serde(default)]
    online: bool,
    #[serde(default)]
    playing_game_id: Option<String>,
    #[serde(default)]
    joinable: bool,
    #[serde(default)]
    lobby_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct WireOk {}

/// The friends accessor, borrowed from the client for one call.
///
/// Build it with [`crate::ArcaneClient::friends`]; it holds no state of its own,
/// so keeping one around buys nothing.
#[derive(Debug)]
pub struct Friends<'a> {
    game_id: &'a str,
    user_id: Option<&'a str>,
}

impl<'a> Friends<'a> {
    pub(crate) fn new(game_id: &'a str, user_id: Option<&'a str>) -> Self {
        Self { game_id, user_id }
    }

    /// This player's friends, each with `online` and `in_game`.
    ///
    /// One synchronous loopback round trip. The Arcane desktop app caches the
    /// list for 15 seconds and sets [`FriendList::stale`] when it served an
    /// older copy while offline, so calling this on a menu or a timer of a few
    /// seconds is fine — calling it per frame is not.
    ///
    /// # Errors
    ///
    /// `not_authenticated` when nobody is signed in, `network_required` under
    /// `ARCANE_OFFLINE_ONLY` (raised before any call), `arcane_unavailable` when
    /// the desktop app is not running, `feature_unavailable` when it predates
    /// the route.
    pub fn list(&self) -> Result<FriendList, SdkError> {
        self.guard_offline("Listing friends")?;

        let response: WireFriendList =
            get_json(FRIENDS_PATH, CALL_TIMEOUT).map_err(DesktopCall::into_sdk_error)?;

        Ok(map_list(response, self.game_id))
    }

    /// Ask another player to be friends on Arcane — typically someone met in
    /// a lobby, whose id is [`crate::LobbyMember::user_id`].
    ///
    /// The request shows up in their launcher, where they accept or decline
    /// it. One synchronous loopback round trip.
    ///
    /// # Errors
    ///
    /// `invalid_argument` for a malformed id or for this player's own id
    /// (raised before any call), `user_not_found`, `already_friends` when you
    /// are friends or a request is already pending either way, plus the codes
    /// of [`Friends::list`].
    pub fn send_request(&self, user_id: &str) -> Result<(), SdkError> {
        validate_id("user_id", user_id)?;
        if self
            .user_id
            .is_some_and(|own| own.eq_ignore_ascii_case(user_id))
        {
            return Err(SdkError::invalid_argument(
                "A player cannot send a friend request to themselves.",
            )
            .with_hint("Compare the id against ArcaneClient::user_id before the call.")
            .with_context("user_id", user_id));
        }
        self.guard_offline("Sending a friend request")?;

        let body = serde_json::json!({ "user_id": user_id });
        let _: WireOk = post_json(FRIEND_REQUESTS_PATH, Some(body), CALL_TIMEOUT)
            .map_err(|call| call.into_sdk_error().with_context("user_id", user_id))?;
        Ok(())
    }

    fn guard_offline(&self, action: &str) -> Result<(), SdkError> {
        if !offline_only() {
            return Ok(());
        }
        Err(SdkError::network_required(format!(
            "{action} needs the Arcane desktop app, and the SDK is running in offline-only mode."
        ))
        .with_hint(format!(
            "Unset {OFFLINE_ONLY_ENV} to let the SDK contact the Arcane desktop app."
        ))
        .with_context("env", OFFLINE_ONLY_ENV))
    }
}

fn map_list(wire: WireFriendList, game_id: &str) -> FriendList {
    FriendList {
        friends: wire
            .friends
            .into_iter()
            .map(|friend| {
                let in_game = is_in_game(friend.playing_game_id.as_deref(), game_id);
                let lobby_id = friend.lobby_id.filter(|id| in_game && !id.is_empty());
                Friend {
                    user_id: friend.user_id,
                    pseudo: friend.pseudo,
                    online: friend.online,
                    in_game,
                    joinable: friend.joinable && lobby_id.is_some(),
                    lobby_id,
                }
            })
            .collect(),
        stale: wire.stale,
    }
}

/// A friend is in this game when the title they are playing is this title.
fn is_in_game(playing_game_id: Option<&str>, game_id: &str) -> bool {
    playing_game_id == Some(game_id)
}

/// The C ABI rendering, in the field order the header and the docs promise —
/// which `serde_json::json!` would not keep, as it sorts its keys.
#[derive(Serialize)]
struct JsonFriendList<'a> {
    friends: Vec<JsonFriend<'a>>,
    stale: bool,
}

#[derive(Serialize)]
struct JsonFriend<'a> {
    user_id: &'a str,
    pseudo: &'a str,
    online: bool,
    in_game: bool,
    joinable: bool,
    lobby_id: Option<&'a str>,
}

pub(crate) fn to_json(list: &FriendList) -> String {
    let rendered = JsonFriendList {
        friends: list
            .friends
            .iter()
            .map(|friend| JsonFriend {
                user_id: &friend.user_id,
                pseudo: &friend.pseudo,
                online: friend.online,
                in_game: friend.in_game,
                joinable: friend.joinable,
                lobby_id: friend.lobby_id.as_deref(),
            })
            .collect(),
        stale: list.stale,
    };
    serde_json::to_string(&rendered)
        .unwrap_or_else(|_| r#"{"friends":[],"stale":false}"#.to_string())
}

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

    const WIRE: &str = r#"{
        "friends": [
            {"user_id":"user-a","pseudo":"Ada","online":true,"playing_game_id":"9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413"},
            {"user_id":"user-b","pseudo":"Bo","online":true,"playing_game_id":"another-game"},
            {"user_id":"user-c","pseudo":"Cy","online":false,"playing_game_id":null}
        ],
        "stale": false
    }"#;

    fn parse(raw: &str) -> WireFriendList {
        serde_json::from_str(raw).expect("wire friend list")
    }

    #[test]
    fn the_wire_shape_maps_onto_the_public_struct() {
        let list = map_list(parse(WIRE), "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413");

        assert_eq!(list.friends.len(), 3);
        assert!(!list.stale);

        assert_eq!(list.friends[0].user_id, "user-a");
        assert_eq!(list.friends[0].pseudo, "Ada");
        assert!(list.friends[0].online);
        assert!(list.friends[0].in_game);

        assert!(list.friends[1].online);
        assert!(!list.friends[1].in_game, "another title is not this one");

        assert!(!list.friends[2].online);
        assert!(!list.friends[2].in_game);
    }

    #[test]
    fn another_titles_id_marks_nobody_in_game() {
        let list = map_list(parse(WIRE), "some-other-title");

        assert!(list.friends.iter().all(|friend| !friend.in_game));
        assert!(list.friends[0].online, "presence still comes through");
    }

    #[test]
    fn stale_passes_through() {
        let list = map_list(parse(r#"{"friends":[],"stale":true}"#), "game");

        assert!(list.stale);
        assert!(list.friends.is_empty());
    }

    #[test]
    fn a_missing_body_field_reads_as_absent_rather_than_failing() {
        let list = map_list(parse(r#"{"friends":[{"user_id":"user-a"}]}"#), "game");

        assert!(!list.stale);
        assert_eq!(list.friends[0].pseudo, "");
        assert!(!list.friends[0].online);
        assert!(!list.friends[0].in_game);
    }

    #[test]
    fn only_the_same_title_counts_as_in_game() {
        assert!(is_in_game(Some("game"), "game"));
        assert!(!is_in_game(Some("another-game"), "game"));
        assert!(!is_in_game(None, "game"));
    }

    #[test]
    fn the_json_rendering_carries_every_field() {
        let rendered = to_json(&map_list(
            parse(WIRE),
            "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
        ));
        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("json");

        assert_eq!(parsed["stale"], false);
        assert_eq!(parsed["friends"][0]["user_id"], "user-a");
        assert_eq!(parsed["friends"][0]["pseudo"], "Ada");
        assert_eq!(parsed["friends"][0]["online"], true);
        assert_eq!(parsed["friends"][0]["in_game"], true);
        assert_eq!(parsed["friends"][1]["in_game"], false);
    }

    #[test]
    fn the_json_rendering_keeps_the_documented_field_order() {
        let rendered = to_json(&map_list(
            parse(WIRE),
            "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
        ));

        assert!(
            rendered.starts_with(
                r#"{"friends":[{"user_id":"user-a","pseudo":"Ada","online":true,"in_game":true,"joinable":false,"lobby_id":null}"#
            ),
            "field order drifted from the header and the docs: {rendered}"
        );
        assert!(rendered.ends_with(r#"],"stale":false}"#));
    }

    #[test]
    fn a_pseudo_with_json_metacharacters_survives_the_rendering() {
        let pseudo = "A\"B\\C\nD\u{0}E 日本語 🎮";
        let list = FriendList {
            friends: vec![Friend {
                user_id: "user-a".into(),
                pseudo: pseudo.into(),
                online: true,
                in_game: false,
                joinable: false,
                lobby_id: None,
            }],
            stale: false,
        };

        let parsed: serde_json::Value = serde_json::from_str(&to_json(&list)).expect("json");

        assert_eq!(parsed["friends"][0]["pseudo"], pseudo);
    }
}