1use std::sync::OnceLock;
4
5use scraper::Selector;
6use serde::Deserialize;
7use steamid::SteamID;
8
9use crate::{
10 client::SteamUser,
11 endpoint::{steam_endpoint, Host},
12 error::SteamUserError,
13 utils::{
14 avatar::{extract_custom_url, get_avatar_hash_from_url, get_avatar_url_from_hash, AvatarSize},
15 debug::dump_html,
16 },
17};
18
19fn de_u32_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
32 use serde::de::Error;
33 #[derive(Deserialize)]
34 #[serde(untagged)]
35 enum N {
36 Int(u64),
37 Str(String),
38 }
39 match N::deserialize(d)? {
40 N::Int(n) => u32::try_from(n).map_err(D::Error::custom),
41 N::Str(s) => s.replace(',', "").parse().map_err(D::Error::custom),
42 }
43}
44
45fn de_opt_i32_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<i32>, D::Error> {
48 #[derive(Deserialize)]
49 #[serde(untagged)]
50 enum N {
51 Int(i64),
52 Str(String),
53 Null,
54 }
55 Ok(match Option::<N>::deserialize(d)? {
56 Some(N::Int(n)) => i32::try_from(n).ok(),
57 Some(N::Str(s)) => s.replace(',', "").parse().ok(),
58 Some(N::Null) | None => None,
59 })
60}
61
62fn de_opt_u64_int_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
64 #[derive(Deserialize)]
65 #[serde(untagged)]
66 enum N {
67 Int(u64),
68 Str(String),
69 Null,
70 }
71 Ok(match Option::<N>::deserialize(d)? {
72 Some(N::Int(n)) => Some(n),
73 Some(N::Str(s)) => s.replace(',', "").parse().ok(),
74 Some(N::Null) | None => None,
75 })
76}
77
78fn de_bool_int_or_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
83 #[derive(Deserialize)]
84 #[serde(untagged)]
85 enum B {
86 Bool(bool),
87 Int(i64),
88 Str(String),
89 Null,
90 }
91 Ok(match Option::<B>::deserialize(d)? {
92 Some(B::Bool(b)) => b,
93 Some(B::Int(n)) => n == 1,
94 Some(B::Str(s)) => s.eq_ignore_ascii_case("true") || s == "1",
95 Some(B::Null) | None => false,
96 })
97}
98
99#[derive(Deserialize)]
105struct CommunitySearchResponseRaw {
106 #[serde(default)]
107 success: i64,
108 #[serde(default)]
109 html: String,
110 #[serde(default = "default_search_filter")]
111 search_filter: String,
112 #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
113 search_page: Option<u64>,
114 #[serde(default, deserialize_with = "de_u32_int_or_string")]
115 search_result_count: u32,
116 #[serde(default)]
117 search_text: String,
118}
119
120fn default_search_filter() -> String {
121 "users".to_string()
122}
123
124#[derive(Deserialize, Default)]
126struct QuickInviteRaw {
127 #[serde(default)]
128 invite_token: Option<String>,
129 #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
130 invite_limit: Option<i32>,
131 #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
132 invite_duration: Option<i32>,
133 #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
134 time_created: Option<u64>,
135}
136
137#[derive(Deserialize)]
139struct QuickInviteCreateResponseRaw {
140 #[serde(default, deserialize_with = "de_bool_int_or_bool")]
141 success: bool,
142 #[serde(default)]
143 invite: Option<QuickInviteRaw>,
144 #[serde(default)]
146 error: Option<i64>,
147}
148
149#[derive(Deserialize)]
151struct QuickInviteListResponseRaw {
152 #[serde(default, deserialize_with = "de_bool_int_or_bool")]
153 success: bool,
154 #[serde(default)]
155 tokens: Vec<QuickInviteTokenRaw>,
156 #[serde(default)]
158 error: Option<i64>,
159}
160
161#[derive(Deserialize)]
163struct QuickInviteTokenRaw {
164 #[serde(default)]
165 invite_token: String,
166 #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
167 invite_limit: Option<i32>,
168 #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
169 invite_duration: Option<i32>,
170 #[serde(default, deserialize_with = "de_opt_u64_int_or_string")]
171 time_created: Option<u64>,
172}
173
174#[derive(Deserialize)]
176struct RedeemResponseRaw {
177 #[serde(default, deserialize_with = "de_opt_i32_int_or_string")]
178 success: Option<i32>,
179}
180
181#[derive(Deserialize, Default)]
183#[serde(default)]
184struct FriendsCountRaw {
185 #[serde(rename = "cFriends", deserialize_with = "de_u32_int_or_string")]
186 friends: u32,
187 #[serde(rename = "cFriendsPending", deserialize_with = "de_u32_int_or_string")]
188 friends_pending: u32,
189 #[serde(rename = "cFriendsBlocked", deserialize_with = "de_u32_int_or_string")]
190 friends_blocked: u32,
191 #[serde(rename = "cFollowing", deserialize_with = "de_u32_int_or_string")]
192 following: u32,
193 #[serde(rename = "cGroups", deserialize_with = "de_u32_int_or_string")]
194 groups: u32,
195 #[serde(rename = "cGroupsPending", deserialize_with = "de_u32_int_or_string")]
196 groups_pending: u32,
197}
198
199static SEL_INVITE_BLOCK_NAME: OnceLock<Selector> = OnceLock::new();
200fn sel_invite_block_name() -> &'static Selector {
201 SEL_INVITE_BLOCK_NAME.get_or_init(|| Selector::parse(".invite_block_name > a.linkTitle").expect("valid CSS selector"))
202}
203
204static SEL_FRIEND_PLAYER_LEVEL: OnceLock<Selector> = OnceLock::new();
205fn sel_friend_player_level() -> &'static Selector {
206 SEL_FRIEND_PLAYER_LEVEL.get_or_init(|| Selector::parse(".friendPlayerLevel .friendPlayerLevelNum").expect("valid CSS selector"))
207}
208
209static SEL_PERSONA_MINIPROFILE: OnceLock<Selector> = OnceLock::new();
210fn sel_persona_miniprofile() -> &'static Selector {
211 SEL_PERSONA_MINIPROFILE.get_or_init(|| Selector::parse(".persona[data-miniprofile]").expect("valid CSS selector"))
212}
213
214static SEL_SELECTABLE_OVERLAY: OnceLock<Selector> = OnceLock::new();
215fn sel_selectable_overlay() -> &'static Selector {
216 SEL_SELECTABLE_OVERLAY.get_or_init(|| Selector::parse("a.selectable_overlay").expect("valid CSS selector"))
217}
218
219static SEL_PLAYER_AVATAR_IMG: OnceLock<Selector> = OnceLock::new();
220fn sel_player_avatar_img() -> &'static Selector {
221 SEL_PLAYER_AVATAR_IMG.get_or_init(|| Selector::parse(".player_avatar img, .playerAvatar img").expect("valid CSS selector"))
222}
223
224static SEL_FRIEND_BLOCK_CONTENT: OnceLock<Selector> = OnceLock::new();
225fn sel_friend_block_content() -> &'static Selector {
226 SEL_FRIEND_BLOCK_CONTENT.get_or_init(|| Selector::parse(".friend_block_content, .friendBlockContent").expect("valid CSS selector"))
227}
228
229static SEL_PLAYER_NICKNAME_HINT: OnceLock<Selector> = OnceLock::new();
230fn sel_player_nickname_hint() -> &'static Selector {
231 SEL_PLAYER_NICKNAME_HINT.get_or_init(|| Selector::parse(".player_nickname_hint").expect("valid CSS selector"))
232}
233
234static SEL_FRIEND_GAME_LINK: OnceLock<Selector> = OnceLock::new();
235fn sel_friend_game_link() -> &'static Selector {
236 SEL_FRIEND_GAME_LINK.get_or_init(|| Selector::parse(".friend_game_link, .linkFriend_in-game").expect("valid CSS selector"))
237}
238
239static SEL_FRIEND_LAST_ONLINE: OnceLock<Selector> = OnceLock::new();
240fn sel_friend_last_online() -> &'static Selector {
241 SEL_FRIEND_LAST_ONLINE.get_or_init(|| Selector::parse(".friend_last_online_text").expect("valid CSS selector"))
242}
243
244static SEL_SEARCH_ROW: OnceLock<Selector> = OnceLock::new();
245fn sel_search_row() -> &'static Selector {
246 SEL_SEARCH_ROW.get_or_init(|| Selector::parse(".search_row").expect("valid CSS selector"))
247}
248
249static SEL_MEDIUM_HOLDER: OnceLock<Selector> = OnceLock::new();
250fn sel_medium_holder() -> &'static Selector {
251 SEL_MEDIUM_HOLDER.get_or_init(|| Selector::parse(".mediumHolder_default[data-miniprofile]").expect("valid CSS selector"))
252}
253
254static SEL_AVATAR_MEDIUM_IMG: OnceLock<Selector> = OnceLock::new();
255fn sel_avatar_medium_img() -> &'static Selector {
256 SEL_AVATAR_MEDIUM_IMG.get_or_init(|| Selector::parse(".avatarMedium a img").expect("valid CSS selector"))
257}
258
259static SEL_SEARCH_PERSONA_NAME: OnceLock<Selector> = OnceLock::new();
260fn sel_search_persona_name() -> &'static Selector {
261 SEL_SEARCH_PERSONA_NAME.get_or_init(|| Selector::parse("a.searchPersonaName").expect("valid CSS selector"))
262}
263
264static SEL_COMMUNITY_SEARCH_PAGING: OnceLock<Selector> = OnceLock::new();
265fn sel_community_search_paging() -> &'static Selector {
266 SEL_COMMUNITY_SEARCH_PAGING.get_or_init(|| Selector::parse(".community_searchresults_paging a").expect("valid CSS selector"))
267}
268
269impl SteamUser {
270 #[steam_endpoint(POST, host = Community, path = "/actions/AddFriendAjax", kind = Write)]
288 pub async fn add_friend(&self, user_id: SteamID) -> Result<(), SteamUserError> {
289 let steam_id = user_id.steam_id64().to_string();
290
291 let response: serde_json::Value = self.post_path("/actions/AddFriendAjax").form(&[("steamid", steam_id.as_str()), ("accept_invite", "0")]).send().await?.json().await?;
292
293 Self::check_json_success(&response, "Failed to add friend")?;
294
295 Ok(())
296 }
297
298 #[steam_endpoint(POST, host = Community, path = "/actions/RemoveFriendAjax", kind = Write)]
316 pub async fn remove_friend(&self, user_id: SteamID) -> Result<(), SteamUserError> {
317 let steam_id = user_id.steam_id64().to_string();
318
319 let response: serde_json::Value = self.post_path("/actions/RemoveFriendAjax").form(&[("steamid", steam_id.as_str())]).send().await?.json().await?;
320
321 Self::check_json_success(&response, "Failed to remove friend")?;
322
323 Ok(())
324 }
325
326 #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
344 pub async fn accept_friend_request(&self, user_id: SteamID) -> Result<(), SteamUserError> {
345 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();
346 let target_steam_id = user_id.steam_id64().to_string();
347
348 let url = format!("/profiles/{}/friends/action", my_steam_id);
349
350 let response: serde_json::Value = self.post_path(&url).form(&[("steamid", my_steam_id.as_str()), ("ajax", "1"), ("action", "accept"), ("steamids[]", target_steam_id.as_str())]).send().await?.json().await?;
351
352 Self::check_json_success(&response, "Failed to accept friend request")?;
353
354 Ok(())
355 }
356
357 #[steam_endpoint(POST, host = Community, path = "/actions/IgnoreFriendInviteAjax", kind = Write)]
363 pub async fn ignore_friend_request(&self, user_id: SteamID) -> Result<(), SteamUserError> {
364 let steam_id = user_id.steam_id64().to_string();
365
366 let response: serde_json::Value = self.post_path("/actions/IgnoreFriendInviteAjax").form(&[("steamid", steam_id.as_str())]).send().await?.json().await?;
367
368 Self::check_json_success(&response, "Failed to ignore friend request")?;
369
370 Ok(())
371 }
372
373 #[steam_endpoint(POST, host = Community, path = "/actions/BlockUserAjax", kind = Write)]
380 pub async fn set_communication_block(&self, user_id: SteamID, block: bool) -> Result<(), SteamUserError> {
381 let steam_id = user_id.steam_id64().to_string();
382 let block_val = if block { "1" } else { "0" };
383
384 let response: serde_json::Value = self.post_path("/actions/BlockUserAjax").form(&[("steamid", steam_id.as_str()), ("block", block_val)]).send().await?.json().await?;
385
386 Self::check_json_success(&response, &format!("Failed to {} user", if block { "block" } else { "unblock" }))?;
387
388 Ok(())
389 }
390
391 #[tracing::instrument(skip(self), fields(target_steam_id = user_id.steam_id64()))]
394 pub async fn block_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
395 self.set_communication_block(user_id, true).await
396 }
397
398 #[tracing::instrument(skip(self), fields(target_steam_id = user_id.steam_id64()))]
401 pub async fn unblock_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
402 self.set_communication_block(user_id, false).await
403 }
404
405 #[steam_endpoint(GET, host = Community, path = "/textfilter/ajaxgetfriendslist", kind = Read)]
410 async fn fetch_friends_list_raw(&self) -> Result<(i64, Vec<serde_json::Value>), SteamUserError> {
411 let response: serde_json::Value = self.get_path("/textfilter/ajaxgetfriendslist").send().await?.json().await?;
412
413 let success = response.get("success").and_then(|v| v.as_i64()).unwrap_or(0);
414
415 if success != 1 {
416 if success == 21 {
417 return Ok((21, Vec::new()));
418 }
419 return Err(SteamUserError::from_eresult(i32::try_from(success).unwrap_or(i32::MIN)));
420 }
421
422 let friends_list = response.get("friendslist").and_then(|v| v.get("friends")).and_then(|v| v.as_array()).ok_or_else(|| SteamUserError::MalformedResponse("Missing friends list".into()))?;
423
424 Ok((1, friends_list.clone()))
425 }
426
427 #[tracing::instrument(skip(self))]
438 pub async fn get_friends_list(&self) -> Result<std::collections::HashMap<SteamID, i32>, SteamUserError> {
439 let (_, friends_list) = self.fetch_friends_list_raw().await?;
440
441 let mut friends = std::collections::HashMap::with_capacity(friends_list.len());
442 for friend in &friends_list {
443 if let (Some(id), Some(rel)) = (friend.get("ulfriendid").and_then(|v| v.as_str()), friend.get("efriendrelationship").and_then(|v| v.as_i64())) {
444 if let Ok(steam_id) = id.parse::<u64>() {
445 if let Ok(rel_i32) = i32::try_from(rel) {
446 friends.insert(SteamID::from(steam_id), rel_i32);
447 }
448 }
449 }
450 }
451
452 Ok(friends)
453 }
454
455 #[tracing::instrument(skip(self))]
467 pub async fn get_friends_details(&self) -> Result<crate::types::FriendListPage, SteamUserError> {
468 let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
469 self.get_friends_details_of_user(steam_id).await
470 }
471
472 #[steam_endpoint(GET, host = Community, path = "/profiles/{user_id}/friends/", kind = Read)]
480 pub async fn get_friends_details_of_user(&self, user_id: SteamID) -> Result<crate::types::FriendListPage, SteamUserError> {
481 let body = self.get_path(format!("/profiles/{}/friends/", user_id.steam_id64())).send().await?.text().await?;
482 Ok(parse_friend_list(&body))
483 }
484
485 #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/followuser/", kind = Write)]
488 pub async fn follow_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
489 self.send_profile_follow_action(user_id, "follow").await
490 }
491
492 #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/unfollowuser/", kind = Write)]
494 pub async fn unfollow_user(&self, user_id: SteamID) -> Result<(), SteamUserError> {
495 self.send_profile_follow_action(user_id, "unfollow").await
496 }
497
498 #[steam_endpoint(GET, host = Community, path = "/search/SearchCommunityAjax", kind = Read)]
505 pub async fn search_users(&self, query: &str, page: u32) -> Result<crate::types::CommunitySearchResult, SteamUserError> {
506 let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();
507
508 let raw: CommunitySearchResponseRaw = self.get_path("/search/SearchCommunityAjax").query(&[("text", query), ("filter", "users"), ("steamid", steam_id.as_str()), ("accept_invite", "0"), ("page", &page.to_string())]).send().await?.json().await?;
509
510 if raw.success != 1 {
511 return Err(SteamUserError::SteamError("Search failed".to_string()));
512 }
513
514 let search_page = raw.search_page.and_then(|n| u32::try_from(n).ok()).unwrap_or(page);
515 let search_text = if raw.search_text.is_empty() { query.to_string() } else { raw.search_text };
516
517 let (players, prev_page, next_page) = parse_search_results(&raw.html, search_page);
518
519 Ok(crate::types::CommunitySearchResult {
520 players,
521 prev_page,
522 next_page,
523 search_filter: raw.search_filter,
524 search_page,
525 search_result_count: raw.search_result_count,
526 search_text,
527 })
528 }
529
530 #[tracing::instrument(skip(self))]
536 pub async fn create_instant_invite(&self) -> Result<String, SteamUserError> {
537 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
538 let short_url = format!("https://s.team/p/{}", steam_friend_code::create_short_steam_friend_code(my_steam_id.account_id));
539 let invite_data = self.get_quick_invite_data().await?;
540
541 if let Some(token) = invite_data.invite_token {
542 Ok(format!("{}/{}", short_url, token))
543 } else {
544 Err(SteamUserError::SteamError("Failed to generate invite token".to_string()))
545 }
546 }
547
548 #[steam_endpoint(POST, host = Community, path = "/invites/ajaxcreate", kind = Write)]
551 pub async fn get_quick_invite_data(&self) -> Result<crate::types::QuickInviteData, SteamUserError> {
552 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
553
554 let raw: QuickInviteCreateResponseRaw = self.post_path("/invites/ajaxcreate").form(&[("steamid_user", my_steam_id.steam_id64().to_string()), ("duration", "2592000".to_string())]).send().await?.json().await?;
555
556 if let (false, Some(code)) = (raw.success, raw.error) {
557 return Err(SteamUserError::SteamError(format!("/invites/ajaxcreate denied (EResult {code})")));
558 }
559
560 if let (true, Some(invite)) = (raw.success, raw.invite) {
561 Ok(crate::types::QuickInviteData {
562 success: true,
563 invite_token: invite.invite_token,
564 invite_limit: invite.invite_limit,
565 invite_duration: invite.invite_duration,
566 time_created: invite.time_created,
567 steam_id: Some(my_steam_id),
568 })
569 } else {
570 Ok(crate::types::QuickInviteData {
571 success: false,
572 invite_token: None,
573 invite_limit: None,
574 invite_duration: None,
575 time_created: None,
576 steam_id: Some(my_steam_id),
577 })
578 }
579 }
580
581 #[steam_endpoint(GET, host = Community, path = "/invites/ajaxgetall", kind = Read)]
583 pub async fn get_current_quick_invite_tokens(&self) -> Result<crate::types::QuickInviteTokensResponse, SteamUserError> {
584 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
585
586 let raw: QuickInviteListResponseRaw = self.get_path("/invites/ajaxgetall").send().await?.json().await?;
587
588 if let (false, Some(code)) = (raw.success, raw.error) {
589 return Err(SteamUserError::SteamError(format!("/invites/ajaxgetall denied (EResult {code})")));
590 }
591
592 let tokens = raw
593 .tokens
594 .into_iter()
595 .map(|t| crate::types::QuickInviteToken {
596 invite_token: t.invite_token,
597 invite_limit: t.invite_limit.unwrap_or(0),
598 invite_duration: t.invite_duration.unwrap_or(0),
599 time_created: t.time_created.unwrap_or(0),
600 steam_id: Some(my_steam_id),
601 })
602 .collect();
603
604 Ok(crate::types::QuickInviteTokensResponse { success: raw.success, tokens })
605 }
606
607 #[steam_endpoint(POST, host = Community, path = "/profiles/{user_id}/{action}user/", kind = Write)]
609 async fn send_profile_follow_action(&self, user_id: SteamID, action: &str) -> Result<(), SteamUserError> {
610 let target_steam_id = user_id.steam_id64().to_string();
611
612 let response: serde_json::Value = self.post_path(format!("/profiles/{}/{}user/", target_steam_id, action)).form(&([] as [(&str, &str); 0])).send().await?.json().await?;
613 Self::check_json_success(&response, &format!("Failed to {} user", action))?;
614 Ok(())
615 }
616
617 #[tracing::instrument(skip(self))]
629 pub async fn get_following_list(&self) -> Result<crate::types::FriendListPage, SteamUserError> {
630 let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
631 self.get_following_list_of_user(steam_id).await
632 }
633
634 #[steam_endpoint(GET, host = Community, path = "/profiles/{user_id}/following/", kind = Read)]
641 pub async fn get_following_list_of_user(&self, user_id: SteamID) -> Result<crate::types::FriendListPage, SteamUserError> {
642 let body = self.get_path(format!("/profiles/{}/following/", user_id.steam_id64())).send().await?.text().await?;
643 Ok(parse_friend_list(&body))
644 }
645
646 #[tracing::instrument(skip(self))]
658 pub async fn get_my_friends_id_list(&self) -> Result<Vec<SteamID>, SteamUserError> {
659 let (_, friends_list) = self.fetch_friends_list_raw().await?;
660
661 const FRIEND_RELATIONSHIP: i64 = 3;
663
664 let mut friends = Vec::new();
665 for friend in &friends_list {
666 let relationship = friend.get("efriendrelationship").and_then(|v| v.as_i64()).unwrap_or(0);
667
668 if relationship == FRIEND_RELATIONSHIP {
669 if let Some(id_str) = friend.get("ulfriendid").and_then(|v| v.as_str()) {
670 if let Ok(steam_id) = id_str.parse::<u64>() {
671 friends.push(SteamID::from(steam_id));
672 }
673 }
674 }
675 }
676
677 Ok(friends)
678 }
679
680 #[steam_endpoint(GET, host = Community, path = "/profiles/{steam_id}/friends/pending", kind = Read)]
688 pub async fn get_pending_friend_list(&self) -> Result<crate::types::PendingFriendList, SteamUserError> {
689 let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64();
690
691 let body = self.get_path(format!("/profiles/{}/friends/pending", steam_id)).send().await?.text().await?;
692
693 let sent_invites = parse_pending_friend_list(&body, "#search_results_sentinvites > div");
694 let received_invites = parse_pending_friend_list(&body, "#search_results > div");
695
696 Ok(crate::types::PendingFriendList { sent_invites, received_invites })
697 }
698
699 #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
705 pub async fn remove_friends(&self, steam_ids: &[SteamID]) -> Result<(), SteamUserError> {
706 if steam_ids.is_empty() {
707 return Ok(());
708 }
709
710 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();
711
712 let mut params = vec![("steamid", my_steam_id), ("ajax", "1".to_string()), ("action", "remove".to_string())];
713
714 for steam_id in steam_ids {
715 params.push(("steamids[]", steam_id.steam_id64().to_string()));
716 }
717
718 let response: serde_json::Value = self.post_path(format!("/profiles/{}/friends/action", params[0].1)).form(¶ms).send().await?.json().await?;
719
720 Self::check_json_success(&response, "Failed to remove friends")?;
721 Ok(())
722 }
723
724 #[steam_endpoint(POST, host = Community, path = "/profiles/{steam_id}/friends/action", kind = Write)]
730 pub async fn unfollow_users(&self, steam_ids: &[SteamID]) -> Result<(), SteamUserError> {
731 if steam_ids.is_empty() {
732 return Ok(());
733 }
734
735 let my_steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?.steam_id64().to_string();
736
737 let path = format!("/profiles/{}/friends/action", my_steam_id);
738
739 let mut params = vec![("steamid", my_steam_id.clone()), ("ajax", "1".to_string()), ("action", "unfollow".to_string())];
740
741 for steam_id in steam_ids {
742 params.push(("steamids[]", steam_id.steam_id64().to_string()));
743 }
744
745 let response: serde_json::Value = self.post_path(&path).form(¶ms).send().await?.json().await?;
746
747 Self::check_json_success(&response, "Failed to unfollow users")?;
748 Ok(())
749 }
750
751 #[tracing::instrument(skip(self))]
754 pub async fn unfollow_all_following(&self) -> Result<(), SteamUserError> {
755 let page = self.get_following_list().await?;
756 if page.friends.is_empty() {
757 return Ok(());
758 }
759
760 let steam_ids: Vec<SteamID> = page.friends.iter().map(|f| f.steam_id).collect();
761 self.unfollow_users(&steam_ids).await
762 }
763
764 #[tracing::instrument(skip(self), fields(target_steam_id = steam_id.steam_id64()))]
774 pub async fn cancel_friend_request(&self, steam_id: SteamID) -> Result<(), SteamUserError> {
775 self.remove_friend(steam_id).await
776 }
777
778 #[steam_endpoint(GET, host = Community, path = "/actions/PlayerList/", kind = Read)]
788 pub async fn get_friends_in_common(&self, steam_id: SteamID) -> Result<Vec<crate::types::FriendDetails>, SteamUserError> {
789 let account_id = steam_id.account_id.to_string();
790 let body = self.get_path("/actions/PlayerList/").query(&[("type", "friendsincommon"), ("target", &account_id)]).send().await?.text().await?;
791 Ok(parse_friend_list(&body).friends)
792 }
793
794 #[steam_endpoint(GET, host = Community, path = "/actions/PlayerList/", kind = Read)]
804 pub async fn get_friends_in_group(&self, group_id: SteamID) -> Result<Vec<crate::types::FriendDetails>, SteamUserError> {
805 let account_id = group_id.account_id.to_string();
806 let body = self.get_path("/actions/PlayerList/").query(&[("type", "friendsingroup"), ("target", &account_id)]).send().await?.text().await?;
807 Ok(parse_friend_list(&body).friends)
808 }
809
810 #[steam_endpoint(GET, host = Api, path = "/IPlayerService/GetFriendsGameplayInfo/v1", kind = Read)]
820 pub async fn get_friends_gameplay_info(&self, app_id: u32) -> Result<crate::types::gameplay::GameplayInfoResponse, SteamUserError> {
821 use prost::Message;
822 use steam_protos::messages::player::{CPlayerGetFriendsGameplayInfoRequest, CPlayerGetFriendsGameplayInfoResponse};
823
824 let request = CPlayerGetFriendsGameplayInfoRequest { appid: Some(app_id) };
825
826 let mut body = Vec::new();
827 request.encode(&mut body)?;
828
829 let access_token = self
836 .session
837 .mobile_access_token
838 .as_deref()
839 .or(self.session.access_token.as_deref())
840 .ok_or(SteamUserError::MissingCredential { field: "access_token" })?;
841
842 let encoded = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body);
843 let params = [("access_token", access_token), ("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &encoded)];
844
845 let response = self.get_path("/IPlayerService/GetFriendsGameplayInfo/v1").query(¶ms).send().await?;
846
847 if !response.status().is_success() {
848 let status = response.status().as_u16();
849 let url = response.url().to_string();
850 return Err(SteamUserError::HttpStatus { status, url });
851 }
852
853 let bytes = response.bytes().await?;
854 let response_proto = CPlayerGetFriendsGameplayInfoResponse::decode(bytes)?;
855
856 let convert_list = |list: Vec<steam_protos::messages::player::c_player_get_friends_gameplay_info_response::FriendsGameplayInfo>| {
857 list.into_iter()
858 .map(|item| crate::types::gameplay::FriendsGameplayInfo {
859 steam_id: SteamID::from(item.steamid.unwrap_or(0)),
860 minutes_played: item.minutes_played.unwrap_or(0),
861 minutes_played_forever: item.minutes_played_forever.unwrap_or(0),
862 })
863 .collect()
864 };
865
866 Ok(crate::types::gameplay::GameplayInfoResponse {
867 your_info: response_proto.your_info.map(|info| crate::types::gameplay::OwnGameplayInfo {
868 steam_id: SteamID::from(info.steamid.unwrap_or(0)),
869 minutes_played: info.minutes_played.unwrap_or(0),
870 minutes_played_forever: info.minutes_played_forever.unwrap_or(0),
871 in_wishlist: info.in_wishlist.unwrap_or(false),
872 owned: info.owned.unwrap_or(false),
873 }),
874 in_game: convert_list(response_proto.in_game),
875 played_recently: convert_list(response_proto.played_recently),
876 played_ever: convert_list(response_proto.played_ever),
877 owns: convert_list(response_proto.owns),
878 in_wishlist: convert_list(response_proto.in_wishlist),
879 })
880 }
881
882 #[steam_endpoint(GET, host = Community, path = "/tradeoffer/new/", kind = Read)]
893 pub async fn get_friend_since(&self, steam_id: SteamID) -> Result<Option<String>, SteamUserError> {
894 let account_id = steam_id.account_id.to_string();
895 let body = self.get_path("/tradeoffer/new/").query(&[("partner", &account_id)]).send().await?.text().await?;
896 Ok(parse_friend_since(&body))
897 }
898
899 #[steam_endpoint(GET, host = Community, path = "/invites/ajaxredeem", kind = Write)]
919 pub async fn accept_quick_invite_link(&self, invite_link: &str) -> Result<(), SteamUserError> {
920 let invite_token = invite_link.trim_end_matches('/').rsplit('/').next().ok_or_else(|| SteamUserError::MalformedResponse("Invalid invite link format".into()))?;
922
923 let parsed = url::Url::parse(invite_link).map_err(|e| SteamUserError::InvalidInput(format!("invalid invite_link: {e}")))?;
930 let host = match parsed.host_str() {
931 Some("s.team") => Host::ShortLink,
932 Some("steamcommunity.com") => Host::Community,
933 Some(other) => return Err(SteamUserError::InvalidInput(format!("invite_link host must be s.team or steamcommunity.com, got {other}"))),
934 None => return Err(SteamUserError::InvalidInput("invite_link has no host".into())),
935 };
936 let path_and_query: &str = &parsed[url::Position::BeforePath..];
937 let body = self.get_path_on(host, path_and_query).send().await?.text().await?;
938
939 let steamid_user = parse_profile_data_steamid(&body).ok_or_else(|| SteamUserError::MalformedResponse("Could not find steamid in invite page".into()))?;
941
942 let session_id = self.session.session_id.as_deref().ok_or(SteamUserError::NotLoggedIn)?;
944
945 let raw: RedeemResponseRaw = self
946 .get_path("/invites/ajaxredeem")
947 .query(&[("sessionid", session_id), ("steamid_user", steamid_user.as_str()), ("invite_token", invite_token)])
948 .send()
949 .await?
950 .json()
951 .await?;
952
953 let success = raw.success.unwrap_or(0);
954
955 if success != 1 {
956 return Err(SteamUserError::SteamError(format!("Failed to accept invite (code: {})", success)));
958 }
959
960 Ok(())
961 }
962
963 #[steam_endpoint(GET, host = Community, path = "/invites/ajaxredeem", kind = Write)]
977 pub async fn accept_quick_invite_data(&self, steamid_user: &str, invite_token: &str) -> Result<(), SteamUserError> {
978 let session_id = self.session.session_id.as_deref().ok_or(SteamUserError::NotLoggedIn)?;
979
980 let raw: RedeemResponseRaw = self
981 .get_path("/invites/ajaxredeem")
982 .query(&[("sessionid", session_id), ("steamid_user", steamid_user), ("invite_token", invite_token)])
983 .send()
984 .await?
985 .json()
986 .await?;
987
988 let success = raw.success.unwrap_or(0);
989
990 if success != 1 {
991 return Err(SteamUserError::SteamError(format!("Failed to accept invite (code: {})", success)));
995 }
996
997 Ok(())
998 }
999}
1000
1001fn parse_pending_friend_list(html: &str, selector: &str) -> Vec<crate::types::PendingFriend> {
1003 let document = scraper::Html::parse_document(html);
1004 let row_selector = match scraper::Selector::parse(selector) {
1005 Ok(s) => s,
1006 Err(e) => {
1007 tracing::warn!(selector, error = ?e, "parse_pending_friend_list: invalid CSS selector; returning empty");
1008 return Vec::new();
1009 }
1010 };
1011
1012 let mut results = Vec::new();
1013
1014 for element in document.select(&row_selector) {
1015 let steam_id_str = element.value().attr("data-steamid").unwrap_or("");
1016 let account_id_str = element.value().attr("data-accountid").unwrap_or("0");
1017
1018 let steam_id = match steam_id_str.parse::<u64>() {
1019 Ok(id) => SteamID::from(id),
1020 Err(e) => {
1021 tracing::warn!(data_steamid = steam_id_str, error = %e, "parse_pending_friend_list: malformed data-steamid; skipping row");
1022 continue;
1023 }
1024 };
1025 let account_id = account_id_str.parse::<u32>().unwrap_or(0);
1026
1027 if account_id == 0 {
1028 continue;
1029 }
1030
1031 let name = element.select(sel_invite_block_name()).next().map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();
1033
1034 let link = element.select(sel_invite_block_name()).next().and_then(|el| el.value().attr("href")).unwrap_or("").to_string();
1035
1036 let avatar_selector_str = format!(".playerAvatar a > img[data-miniprofile=\"{}\"]", account_id);
1038 let avatar = if let Ok(avatar_selector) = scraper::Selector::parse(&avatar_selector_str) { element.select(&avatar_selector).next().and_then(|el| el.value().attr("src")).unwrap_or("").to_string() } else { String::new() };
1039
1040 let level = element.select(sel_friend_player_level()).next().map(|el| el.text().collect::<String>().trim().parse::<u32>().unwrap_or(0)).unwrap_or(0);
1042
1043 results.push(crate::types::PendingFriend { name, link, avatar, steam_id, account_id, level });
1044 }
1045
1046 results
1047}
1048
1049fn parse_friend_since(html: &str) -> Option<String> {
1051 let document = scraper::Html::parse_document(html);
1052 let container_selector = scraper::Selector::parse(".trade_partner_header.responsive_trade_offersection").ok()?;
1053 let info_block_selector = scraper::Selector::parse(".trade_partner_info_block").ok()?;
1054 let info_text_selector = scraper::Selector::parse(".trade_partner_info_text").ok()?;
1055
1056 let container = document.select(&container_selector).next()?;
1057
1058 for info_block in container.select(&info_block_selector) {
1059 let full_text: String = info_block.text().collect();
1060
1061 if full_text.contains("You've been friends since") || full_text.contains("You've been friends for") {
1062 if let Some(info_text) = info_block.select(&info_text_selector).next() {
1063 let friend_since = info_text.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ");
1064
1065 if !friend_since.is_empty() {
1066 return Some(friend_since);
1067 }
1068 }
1069 }
1070 }
1071
1072 None
1073}
1074
1075fn parse_js_json_var(html: &str, var_name: &str) -> Option<serde_json::Value> {
1079 let marker = format!("{} = ", var_name);
1080 let start = html.find(&marker)?;
1081 let rest = &html[start + marker.len()..];
1082 let end = rest.find(";\n").or_else(|| rest.find(";\r")).or_else(|| rest.find(";\t")).or_else(|| rest.find(';'))?;
1083 serde_json::from_str(rest[..end].trim()).ok()
1084}
1085
1086fn parse_profile_data_steamid(html: &str) -> Option<String> {
1088 let val = parse_js_json_var(html, "g_rgProfileData")?;
1089 val.get("steamid").and_then(|v| v.as_str()).map(|s| s.to_string())
1090}
1091
1092fn parse_friend_page_info(html: &str, document: &scraper::Html) -> Option<crate::types::FriendPageInfo> {
1097 use crate::types::FriendPageInfo;
1098
1099 let mut info = FriendPageInfo::default();
1100 let mut found_anything = false;
1101
1102 if let Some(val) = parse_js_json_var(html, "g_rgProfileData") {
1103 if let Some(name) = val.get("personaname").and_then(|v| v.as_str()) {
1104 info.persona_name = name.to_string();
1105 }
1106 if let Some(url) = val.get("url").and_then(|v| v.as_str()) {
1107 info.profile_url = url.to_string();
1108 }
1109 if let Some(sid) = val.get("steamid").and_then(|v| v.as_str()) {
1110 if let Ok(id64) = sid.parse::<u64>() {
1111 info.steam_id = SteamID::from(id64);
1112 }
1113 }
1114 found_anything = true;
1115 }
1116
1117 if let Some(val) = parse_js_json_var(html, "g_rgCounts") {
1118 if let Ok(counts) = serde_json::from_value::<FriendsCountRaw>(val) {
1121 info.friends_count = counts.friends;
1122 info.friends_pending_count = counts.friends_pending;
1123 info.blocked_count = counts.friends_blocked;
1124 info.following_count = counts.following;
1125 info.groups_count = counts.groups;
1126 info.groups_pending_count = counts.groups_pending;
1127 found_anything = true;
1128 }
1129 }
1130
1131 if let Some(start) = html.find("g_cFriendsLimit = ") {
1133 let rest = &html[start + 18..];
1134 if let Some(end) = rest.find(';') {
1135 if let Ok(limit) = rest[..end].trim().parse::<u32>() {
1136 info.friends_limit = limit;
1137 found_anything = true;
1138 }
1139 }
1140 }
1141
1142 let wallet = crate::services::account::parse_wallet_balance(document);
1143 if wallet.main_balance.is_some() {
1144 info.wallet_balance = Some(wallet);
1145 found_anything = true;
1146 }
1147
1148 if found_anything {
1149 Some(info)
1150 } else {
1151 None
1152 }
1153}
1154
1155fn parse_friend_list(html: &str) -> crate::types::FriendListPage {
1156 let document = scraper::Html::parse_document(html);
1157 let mut results = Vec::new();
1158
1159 for element in document.select(sel_persona_miniprofile()) {
1160 let miniprofile = element.value().attr("data-miniprofile").and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
1161 if miniprofile == 0 {
1162 continue;
1163 }
1164
1165 let steam_id = SteamID::from_individual_account_id(miniprofile);
1166
1167 let profile_url = element.select(sel_selectable_overlay()).next().and_then(|el| el.value().attr("href")).unwrap_or("").to_string();
1169 if profile_url.is_empty() {
1170 continue;
1171 }
1172
1173 let avatar_src = element.select(sel_player_avatar_img()).next().and_then(|el| el.value().attr("src")).unwrap_or("");
1175 let avatar_hash = get_avatar_hash_from_url(avatar_src).unwrap_or_default();
1176 let avatar = get_avatar_url_from_hash(&avatar_hash, AvatarSize::Full).unwrap_or_else(|| avatar_src.to_string());
1177
1178 let mut username = String::new();
1180 let mut game = String::new();
1181 let mut last_online = String::new();
1182 let mut is_nickname = false;
1183
1184 if let Some(content) = element.select(sel_friend_block_content()).next() {
1185 is_nickname = content.select(sel_player_nickname_hint()).next().is_some();
1186
1187 if let Some(game_el) = content.select(sel_friend_game_link()).next() {
1188 game = game_el.text().collect::<String>().trim().replace("In-Game", "").trim().to_string();
1189 }
1190
1191 if let Some(last_el) = content.select(sel_friend_last_online()).next() {
1192 last_online = last_el.text().collect::<String>().trim().to_string();
1193 }
1194
1195 if let Some(first_text) = content.text().next() {
1197 username = first_text.trim().to_string();
1198 }
1199
1200 if username.is_empty() {
1201 let full_text = content.text().collect::<String>();
1202 username = full_text.trim().split('\n').next().unwrap_or("").trim().to_string();
1203 }
1204 }
1205
1206 if username == "[deleted]" {
1207 continue;
1208 }
1209
1210 let online_status = if element.value().classes().any(|c| c == "in-game") {
1211 "ingame"
1212 } else if element.value().classes().any(|c| c == "online") {
1213 "online"
1214 } else {
1215 "offline"
1216 }
1217 .to_string();
1218
1219 let custom_url = extract_custom_url(&profile_url);
1220
1221 results.push(crate::types::FriendDetails {
1222 username,
1223 steam_id,
1224 game,
1225 online_status,
1226 last_online,
1227 miniprofile: miniprofile as u64,
1228 is_nickname,
1229 avatar,
1230 avatar_hash,
1231 profile_url,
1232 custom_url,
1233 });
1234 }
1235
1236 if results.is_empty() && !html.trim().is_empty() && document.select(sel_persona_miniprofile()).next().is_none() {
1237 dump_html("friends_list_empty", html);
1238 }
1239
1240 let page_info = parse_friend_page_info(html, &document);
1241
1242 crate::types::FriendListPage { friends: results, page_info }
1243}
1244
1245fn parse_search_results(html: &str, current_page: u32) -> (Vec<crate::types::CommunitySearchPlayer>, Option<u32>, Option<u32>) {
1246 let document = scraper::Html::parse_document(html);
1247 let mut players = Vec::new();
1248
1249 for element in document.select(sel_search_row()) {
1250 let miniprofile = element.select(sel_medium_holder()).next().and_then(|el| el.value().attr("data-miniprofile")).and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
1251 if miniprofile == 0 {
1252 continue;
1253 }
1254
1255 let steam_id = SteamID::from_individual_account_id(miniprofile);
1256
1257 let avatar_src = element.select(sel_avatar_medium_img()).next().and_then(|el| el.value().attr("src")).unwrap_or("");
1258 let avatar_hash = get_avatar_hash_from_url(avatar_src).unwrap_or_default();
1259
1260 let search_persona_el = element.select(sel_search_persona_name()).next();
1261 let name = search_persona_el.map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();
1262 let profile_url = search_persona_el.and_then(|el| el.value().attr("href")).unwrap_or("").to_string();
1263 let custom_url = extract_custom_url(&profile_url);
1264
1265 players.push(crate::types::CommunitySearchPlayer { miniprofile: miniprofile as u64, steam_id, avatar_hash, name, profile_url, custom_url });
1266 }
1267
1268 let mut prev_page = None;
1269 let mut next_page = None;
1270
1271 for paging_el in document.select(sel_community_search_paging()) {
1272 let onclick = paging_el.value().attr("onclick").unwrap_or("");
1273 if onclick.contains("CommunitySearch.PrevPage()") {
1274 prev_page = Some(current_page.saturating_sub(1));
1275 } else if onclick.contains("CommunitySearch.NextPage()") {
1276 next_page = Some(current_page + 1);
1277 }
1278 }
1279
1280 if players.is_empty() && !html.trim().is_empty() && document.select(sel_search_row()).next().is_none() {
1281 dump_html("search_friends_empty", html);
1282 }
1283
1284 (players, prev_page, next_page)
1285}
1286
1287#[cfg(test)]
1288mod gameplay_info_tests {
1289 use crate::{SteamUser, SteamUserError};
1290
1291 #[tokio::test]
1299 async fn requires_access_token() {
1300 let user = SteamUser::new(&["steamLoginSecure=76561198000000000"]).expect("build user from cookie");
1301 let err = user.get_friends_gameplay_info(730).await.expect_err("call must require an access token");
1302 assert!(
1303 matches!(err, SteamUserError::MissingCredential { field: "access_token" }),
1304 "expected MissingCredential {{ field: \"access_token\" }}, got: {err:?}"
1305 );
1306 }
1307}
1308
1309#[cfg(test)]
1310mod quick_invite_decode_tests {
1311 use super::QuickInviteListResponseRaw;
1312
1313 #[test]
1318 fn error_envelope_with_string_success_decodes() {
1319 let raw: QuickInviteListResponseRaw = serde_json::from_str(r#"{"success":"false","error":15}"#).expect("error envelope must decode");
1320 assert!(!raw.success);
1321 assert_eq!(raw.error, Some(15));
1322 assert!(raw.tokens.is_empty());
1323 }
1324
1325 #[test]
1326 fn happy_path_still_decodes() {
1327 let raw: QuickInviteListResponseRaw = serde_json::from_str(r#"{"success":1,"tokens":[{"invite_token":"abc","invite_limit":"5","invite_duration":null,"time_created":1700000000}]}"#).expect("token list must decode");
1328 assert!(raw.success);
1329 assert_eq!(raw.error, None);
1330 assert_eq!(raw.tokens.len(), 1);
1331 assert_eq!(raw.tokens[0].invite_token, "abc");
1332 assert_eq!(raw.tokens[0].invite_limit, Some(5));
1333 }
1334}