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";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Friend {
pub user_id: String,
pub pseudo: String,
pub online: bool,
pub in_game: bool,
pub joinable: bool,
pub lobby_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FriendList {
pub friends: Vec<Friend>,
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 {}
#[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 }
}
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))
}
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,
}
}
fn is_in_game(playing_game_id: Option<&str>, game_id: &str) -> bool {
playing_game_id == Some(game_id)
}
#[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);
}
}