1use 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#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Friend {
28 pub user_id: String,
30 pub pseudo: String,
32 pub online: bool,
34 pub in_game: bool,
37 pub joinable: bool,
40 pub lobby_id: Option<String>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct FriendList {
49 pub friends: Vec<Friend>,
51 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#[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 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 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
187fn is_in_game(playing_game_id: Option<&str>, game_id: &str) -> bool {
189 playing_game_id == Some(game_id)
190}
191
192#[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}