Skip to main content

arcane_sdk/
friends.rs

1//! Friends: who this player has on Arcane, who is online, and who is in this
2//! game right now.
3//!
4//! One call, [`Friends::list`], and it is **synchronous on the calling thread**
5//! — a single local loopback round trip, on the order of a millisecond. Call it
6//! when a menu opens or on a timer of your own, never from the render loop.
7//!
8//! The SDK keeps no list of its own: the Arcane desktop app caches for 15
9//! seconds and reports [`FriendList::stale`] when the answer came from that
10//! cache while it was offline. [`Friends::send_request`] asks someone met in a
11//! lobby to be friends; accepting, chat and the overlay stay in the launcher.
12
13use std::time::Duration;
14
15use serde::{Deserialize, Serialize};
16
17use crate::desktop::{get_json, offline_only, post_json, DesktopCall, OFFLINE_ONLY_ENV};
18use crate::error::SdkError;
19use crate::p2p::validate_id;
20
21const CALL_TIMEOUT: Duration = Duration::from_secs(5);
22const FRIENDS_PATH: &str = "/v1/friends";
23const FRIEND_REQUESTS_PATH: &str = "/v1/friends/requests";
24
25/// One friend of the signed-in Arcane account, with their presence.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Friend {
28    /// The friend's Arcane account id — the value Arcane identifies them by.
29    pub user_id: String,
30    /// Their display name on Arcane.
31    pub pseudo: String,
32    /// Whether they are signed in to Arcane right now.
33    pub online: bool,
34    /// Whether they are playing **this** title right now — the title named by
35    /// `ARCANE_GAME_ID`.
36    pub in_game: bool,
37    /// Whether [`Friend::lobby_id`] has a free slot. Check it before joining
38    /// with [`crate::P2p::join`].
39    pub joinable: bool,
40    /// The lobby they are in, when it is a lobby of this title other than a
41    /// `code` lobby, full or not. `None` otherwise, including for a lobby of
42    /// another title.
43    pub lobby_id: Option<String>,
44}
45
46/// What the Arcane desktop app knows about this player's friends.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct FriendList {
49    /// The friends, in the order the desktop app returned them.
50    pub friends: Vec<Friend>,
51    /// Whether the desktop app answered from its cache because it is offline.
52    /// The list is still usable — presence may simply be a few minutes old.
53    pub stale: bool,
54}
55
56#[derive(Debug, Deserialize)]
57struct WireFriendList {
58    #[serde(default)]
59    friends: Vec<WireFriend>,
60    #[serde(default)]
61    stale: bool,
62}
63
64#[derive(Debug, Deserialize)]
65struct WireFriend {
66    user_id: String,
67    #[serde(default)]
68    pseudo: String,
69    #[serde(default)]
70    online: bool,
71    #[serde(default)]
72    playing_game_id: Option<String>,
73    #[serde(default)]
74    joinable: bool,
75    #[serde(default)]
76    lobby_id: Option<String>,
77}
78
79#[derive(Debug, Deserialize)]
80struct WireOk {}
81
82/// The friends accessor, borrowed from the client for one call.
83///
84/// Build it with [`crate::ArcaneClient::friends`]; it holds no state of its own,
85/// so keeping one around buys nothing.
86#[derive(Debug)]
87pub struct Friends<'a> {
88    game_id: &'a str,
89    user_id: Option<&'a str>,
90}
91
92impl<'a> Friends<'a> {
93    pub(crate) fn new(game_id: &'a str, user_id: Option<&'a str>) -> Self {
94        Self { game_id, user_id }
95    }
96
97    /// This player's friends, each with `online` and `in_game`.
98    ///
99    /// One synchronous loopback round trip. The Arcane desktop app caches the
100    /// list for 15 seconds and sets [`FriendList::stale`] when it served an
101    /// older copy while offline, so calling this on a menu or a timer of a few
102    /// seconds is fine — calling it per frame is not.
103    ///
104    /// # Errors
105    ///
106    /// `not_authenticated` when nobody is signed in, `network_required` under
107    /// `ARCANE_OFFLINE_ONLY` (raised before any call), `arcane_unavailable` when
108    /// the desktop app is not running, `feature_unavailable` when it predates
109    /// the route.
110    pub fn list(&self) -> Result<FriendList, SdkError> {
111        self.guard_offline("Listing friends")?;
112
113        let response: WireFriendList =
114            get_json(FRIENDS_PATH, CALL_TIMEOUT).map_err(DesktopCall::into_sdk_error)?;
115
116        Ok(map_list(response, self.game_id))
117    }
118
119    /// Ask another player to be friends on Arcane — typically someone met in
120    /// a lobby, whose id is [`crate::LobbyMember::user_id`].
121    ///
122    /// The request shows up in their launcher, where they accept or decline
123    /// it. One synchronous loopback round trip.
124    ///
125    /// # Errors
126    ///
127    /// `invalid_argument` for a malformed id or for this player's own id
128    /// (raised before any call), `user_not_found`, `already_friends` when you
129    /// are friends or a request is already pending either way, plus the codes
130    /// of [`Friends::list`].
131    pub fn send_request(&self, user_id: &str) -> Result<(), SdkError> {
132        validate_id("user_id", user_id)?;
133        if self
134            .user_id
135            .is_some_and(|own| own.eq_ignore_ascii_case(user_id))
136        {
137            return Err(SdkError::invalid_argument(
138                "A player cannot send a friend request to themselves.",
139            )
140            .with_hint("Compare the id against ArcaneClient::user_id before the call.")
141            .with_context("user_id", user_id));
142        }
143        self.guard_offline("Sending a friend request")?;
144
145        let body = serde_json::json!({ "user_id": user_id });
146        let _: WireOk = post_json(FRIEND_REQUESTS_PATH, Some(body), CALL_TIMEOUT)
147            .map_err(|call| call.into_sdk_error().with_context("user_id", user_id))?;
148        Ok(())
149    }
150
151    fn guard_offline(&self, action: &str) -> Result<(), SdkError> {
152        if !offline_only() {
153            return Ok(());
154        }
155        Err(SdkError::network_required(format!(
156            "{action} needs the Arcane desktop app, and the SDK is running in offline-only mode."
157        ))
158        .with_hint(format!(
159            "Unset {OFFLINE_ONLY_ENV} to let the SDK contact the Arcane desktop app."
160        ))
161        .with_context("env", OFFLINE_ONLY_ENV))
162    }
163}
164
165fn map_list(wire: WireFriendList, game_id: &str) -> FriendList {
166    FriendList {
167        friends: wire
168            .friends
169            .into_iter()
170            .map(|friend| {
171                let in_game = is_in_game(friend.playing_game_id.as_deref(), game_id);
172                let lobby_id = friend.lobby_id.filter(|id| in_game && !id.is_empty());
173                Friend {
174                    user_id: friend.user_id,
175                    pseudo: friend.pseudo,
176                    online: friend.online,
177                    in_game,
178                    joinable: friend.joinable && lobby_id.is_some(),
179                    lobby_id,
180                }
181            })
182            .collect(),
183        stale: wire.stale,
184    }
185}
186
187/// A friend is in this game when the title they are playing is this title.
188fn is_in_game(playing_game_id: Option<&str>, game_id: &str) -> bool {
189    playing_game_id == Some(game_id)
190}
191
192/// The C ABI rendering, in the field order the header and the docs promise —
193/// which `serde_json::json!` would not keep, as it sorts its keys.
194#[derive(Serialize)]
195struct JsonFriendList<'a> {
196    friends: Vec<JsonFriend<'a>>,
197    stale: bool,
198}
199
200#[derive(Serialize)]
201struct JsonFriend<'a> {
202    user_id: &'a str,
203    pseudo: &'a str,
204    online: bool,
205    in_game: bool,
206    joinable: bool,
207    lobby_id: Option<&'a str>,
208}
209
210pub(crate) fn to_json(list: &FriendList) -> String {
211    let rendered = JsonFriendList {
212        friends: list
213            .friends
214            .iter()
215            .map(|friend| JsonFriend {
216                user_id: &friend.user_id,
217                pseudo: &friend.pseudo,
218                online: friend.online,
219                in_game: friend.in_game,
220                joinable: friend.joinable,
221                lobby_id: friend.lobby_id.as_deref(),
222            })
223            .collect(),
224        stale: list.stale,
225    };
226    serde_json::to_string(&rendered)
227        .unwrap_or_else(|_| r#"{"friends":[],"stale":false}"#.to_string())
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    const WIRE: &str = r#"{
235        "friends": [
236            {"user_id":"user-a","pseudo":"Ada","online":true,"playing_game_id":"9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413"},
237            {"user_id":"user-b","pseudo":"Bo","online":true,"playing_game_id":"another-game"},
238            {"user_id":"user-c","pseudo":"Cy","online":false,"playing_game_id":null}
239        ],
240        "stale": false
241    }"#;
242
243    fn parse(raw: &str) -> WireFriendList {
244        serde_json::from_str(raw).expect("wire friend list")
245    }
246
247    #[test]
248    fn the_wire_shape_maps_onto_the_public_struct() {
249        let list = map_list(parse(WIRE), "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413");
250
251        assert_eq!(list.friends.len(), 3);
252        assert!(!list.stale);
253
254        assert_eq!(list.friends[0].user_id, "user-a");
255        assert_eq!(list.friends[0].pseudo, "Ada");
256        assert!(list.friends[0].online);
257        assert!(list.friends[0].in_game);
258
259        assert!(list.friends[1].online);
260        assert!(!list.friends[1].in_game, "another title is not this one");
261
262        assert!(!list.friends[2].online);
263        assert!(!list.friends[2].in_game);
264    }
265
266    #[test]
267    fn another_titles_id_marks_nobody_in_game() {
268        let list = map_list(parse(WIRE), "some-other-title");
269
270        assert!(list.friends.iter().all(|friend| !friend.in_game));
271        assert!(list.friends[0].online, "presence still comes through");
272    }
273
274    #[test]
275    fn stale_passes_through() {
276        let list = map_list(parse(r#"{"friends":[],"stale":true}"#), "game");
277
278        assert!(list.stale);
279        assert!(list.friends.is_empty());
280    }
281
282    #[test]
283    fn a_missing_body_field_reads_as_absent_rather_than_failing() {
284        let list = map_list(parse(r#"{"friends":[{"user_id":"user-a"}]}"#), "game");
285
286        assert!(!list.stale);
287        assert_eq!(list.friends[0].pseudo, "");
288        assert!(!list.friends[0].online);
289        assert!(!list.friends[0].in_game);
290    }
291
292    #[test]
293    fn only_the_same_title_counts_as_in_game() {
294        assert!(is_in_game(Some("game"), "game"));
295        assert!(!is_in_game(Some("another-game"), "game"));
296        assert!(!is_in_game(None, "game"));
297    }
298
299    #[test]
300    fn the_json_rendering_carries_every_field() {
301        let rendered = to_json(&map_list(
302            parse(WIRE),
303            "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
304        ));
305        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("json");
306
307        assert_eq!(parsed["stale"], false);
308        assert_eq!(parsed["friends"][0]["user_id"], "user-a");
309        assert_eq!(parsed["friends"][0]["pseudo"], "Ada");
310        assert_eq!(parsed["friends"][0]["online"], true);
311        assert_eq!(parsed["friends"][0]["in_game"], true);
312        assert_eq!(parsed["friends"][1]["in_game"], false);
313    }
314
315    #[test]
316    fn the_json_rendering_keeps_the_documented_field_order() {
317        let rendered = to_json(&map_list(
318            parse(WIRE),
319            "9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
320        ));
321
322        assert!(
323            rendered.starts_with(
324                r#"{"friends":[{"user_id":"user-a","pseudo":"Ada","online":true,"in_game":true,"joinable":false,"lobby_id":null}"#
325            ),
326            "field order drifted from the header and the docs: {rendered}"
327        );
328        assert!(rendered.ends_with(r#"],"stale":false}"#));
329    }
330
331    #[test]
332    fn a_pseudo_with_json_metacharacters_survives_the_rendering() {
333        let pseudo = "A\"B\\C\nD\u{0}E 日本語 🎮";
334        let list = FriendList {
335            friends: vec![Friend {
336                user_id: "user-a".into(),
337                pseudo: pseudo.into(),
338                online: true,
339                in_game: false,
340                joinable: false,
341                lobby_id: None,
342            }],
343            stale: false,
344        };
345
346        let parsed: serde_json::Value = serde_json::from_str(&to_json(&list)).expect("json");
347
348        assert_eq!(parsed["friends"][0]["pseudo"], pseudo);
349    }
350}