steam-user 0.1.0

Steam User web client for Rust - HTTP-based Steam Community interactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
use std::{collections::HashMap, sync::OnceLock, time::Duration};

use scraper::{Html, Selector};
use serde_json::Value;

use crate::{
    client::SteamUser,
    endpoint::steam_endpoint,
    error::SteamUserError,
    types::apps::{AppDetail, CsgoAccountStats, OwnedApp},
};

/// Connect timeout for the ad-hoc clients in this module (static endpoints
/// that don't go through `SteamUser`'s shared client).
const ADHOC_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Total request timeout for the ad-hoc clients in this module.
const ADHOC_TIMEOUT: Duration = Duration::from_secs(60);

/// Build a one-off `reqwest::Client` with the project-standard timeouts.
fn build_adhoc_client() -> Result<reqwest::Client, SteamUserError> {
    reqwest::Client::builder().connect_timeout(ADHOC_CONNECT_TIMEOUT).timeout(ADHOC_TIMEOUT).build().map_err(SteamUserError::from)
}

static SEL_KV_LINE: OnceLock<Selector> = OnceLock::new();
fn sel_kv_line() -> &'static Selector {
    SEL_KV_LINE.get_or_init(|| Selector::parse(".generic_kv_table .generic_kv_line").expect("valid CSS selector"))
}

static SEL_KV_TABLE: OnceLock<Selector> = OnceLock::new();
fn sel_kv_table() -> &'static Selector {
    SEL_KV_TABLE.get_or_init(|| Selector::parse("table.generic_kv_table").expect("valid CSS selector"))
}

static SEL_TR: OnceLock<Selector> = OnceLock::new();
fn sel_tr() -> &'static Selector {
    SEL_TR.get_or_init(|| Selector::parse("tr").expect("valid CSS selector"))
}

static SEL_TH: OnceLock<Selector> = OnceLock::new();
fn sel_th() -> &'static Selector {
    SEL_TH.get_or_init(|| Selector::parse("th").expect("valid CSS selector"))
}

static SEL_TD: OnceLock<Selector> = OnceLock::new();
fn sel_td() -> &'static Selector {
    SEL_TD.get_or_init(|| Selector::parse("td").expect("valid CSS selector"))
}

static SEL_MATCH_ANCHOR: OnceLock<Selector> = OnceLock::new();
fn sel_match_anchor() -> &'static Selector {
    SEL_MATCH_ANCHOR.get_or_init(|| Selector::parse("a.match").expect("valid CSS selector"))
}

static SEL_MATCH_NAME: OnceLock<Selector> = OnceLock::new();
fn sel_match_name() -> &'static Selector {
    SEL_MATCH_NAME.get_or_init(|| Selector::parse(".match_name").expect("valid CSS selector"))
}

static SEL_MATCH_IMG: OnceLock<Selector> = OnceLock::new();
fn sel_match_img() -> &'static Selector {
    SEL_MATCH_IMG.get_or_init(|| Selector::parse(".match_img img").expect("valid CSS selector"))
}

static SEL_MATCH_PRICE: OnceLock<Selector> = OnceLock::new();
fn sel_match_price() -> &'static Selector {
    SEL_MATCH_PRICE.get_or_init(|| Selector::parse(".match_price").expect("valid CSS selector"))
}

static SEL_SEARCH_ROW: OnceLock<Selector> = OnceLock::new();
fn sel_search_row() -> &'static Selector {
    SEL_SEARCH_ROW.get_or_init(|| Selector::parse("a.search_result_row").expect("valid CSS selector"))
}

static SEL_SEARCH_NAME: OnceLock<Selector> = OnceLock::new();
fn sel_search_name() -> &'static Selector {
    SEL_SEARCH_NAME.get_or_init(|| Selector::parse(".search_name .title").expect("valid CSS selector"))
}

static SEL_SEARCH_CAPSULE_IMG: OnceLock<Selector> = OnceLock::new();
fn sel_search_capsule_img() -> &'static Selector {
    SEL_SEARCH_CAPSULE_IMG.get_or_init(|| Selector::parse(".search_capsule img").expect("valid CSS selector"))
}

static SEL_SEARCH_PRICE: OnceLock<Selector> = OnceLock::new();
fn sel_search_price() -> &'static Selector {
    SEL_SEARCH_PRICE.get_or_init(|| Selector::parse(".search_price").expect("valid CSS selector"))
}

static SEL_APP_CONFIG: OnceLock<Selector> = OnceLock::new();
fn sel_app_config() -> &'static Selector {
    SEL_APP_CONFIG.get_or_init(|| Selector::parse("#application_config").expect("valid CSS selector"))
}

impl SteamUser {
    /// Retrieves the list of apps owned by the currently authenticated user.
    ///
    /// Fetches the list from `https://steamcommunity.com/actions/GetOwnedApps/`.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<OwnedApp>` containing details about each app owned by the
    /// user.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let apps = user.get_owned_apps().await?;
    /// println!("You own {} apps.", apps.len());
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Community, path = "/actions/GetOwnedApps/", kind = Read)]
    pub async fn get_owned_apps(&self) -> Result<Vec<OwnedApp>, SteamUserError> {
        let response: Value = self.get_path("/actions/GetOwnedApps/").send().await?.json().await?;

        let apps = response.as_array().ok_or_else(|| SteamUserError::MalformedResponse("Expected an array of apps".into()))?;

        let mut owned_apps = Vec::new();
        for app in apps {
            if let Ok(owned_app) = serde_json::from_value::<OwnedApp>(app.clone()) {
                owned_apps.push(owned_app);
            }
        }

        Ok(owned_apps)
    }

    /// Retrieves details for one or more Steam applications.
    ///
    /// Fetches data from the Steam Store API at `https://store.steampowered.com/api/appdetails`.
    ///
    /// # Arguments
    ///
    /// * `app_ids` - A slice of Steam App IDs to fetch details for.
    ///
    /// # Returns
    ///
    /// Returns a `HashMap<u32, AppDetail>` where the key is the App ID and the
    /// value is the [`AppDetail`].
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let details = user.get_app_detail(&[730, 440]).await?;
    /// if let Some(csgo) = details.get(&730) {
    ///     println!("App name: {}", csgo.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Store, path = "/api/appdetails", kind = Read)]
    pub async fn get_app_detail(&self, app_ids: &[u32]) -> Result<HashMap<u32, AppDetail>, SteamUserError> {
        if app_ids.is_empty() {
            return Ok(HashMap::new());
        }

        let ids = app_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>().join(",");

        let response: Value = self.get_path("/api/appdetails").query(&[("appids", ids.as_str()), ("hl", "en")]).send().await?.json().await?;

        let mut details = HashMap::new();
        if let Some(obj) = response.as_object() {
            for (key, val) in obj {
                if let Ok(app_id) = key.parse::<u32>() {
                    if val["success"].as_bool().unwrap_or(false) {
                        if let Ok(detail) = serde_json::from_value::<AppDetail>(val["data"].clone()) {
                            details.insert(app_id, detail);
                        }
                    }
                }
            }
        }

        Ok(details)
    }

    /// Fetches CS:GO account statistics from the Steam GDPR page.
    ///
    /// Scrapes the GDPR activity page for CS:GO (App ID 730) at `https://steamcommunity.com/my/gcpd/730/?tab=accountmain`.
    /// This includes data like last logout, first played, and profile rank.
    ///
    /// # Returns
    ///
    /// Returns a [`CsgoAccountStats`] struct containing various account
    /// statistics.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let stats = user.fetch_csgo_account_stats().await?;
    /// if let Some(rank) = stats.profile_rank {
    ///     println!("CS:GO Profile Rank: {}", rank);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Community, path = "/my/gcpd/730/", kind = Read)]
    pub async fn fetch_csgo_account_stats(&self) -> Result<CsgoAccountStats, SteamUserError> {
        let html = self.my_profile_get("gcpd/730/?tab=accountmain").await?;
        let document = Html::parse_document(&html);

        let mut stats = CsgoAccountStats {
            last_logout_csgo: None,
            last_launch_steam_client: None,
            start_play_csgo: None,
            first_played_cs_franchise: None,
            last_known_ip: None,
            earned_service_medal: None,
            profile_rank: None,
            xp_to_next_rank: None,
            anti_addiction_online_time: None,
        };

        // Parse key-value lines
        for element in document.select(sel_kv_line()) {
            let text = element.text().collect::<String>().trim().to_string();
            let mut parts = text.splitn(2, ": ");
            if let (Some(raw_key), Some(raw_value)) = (parts.next(), parts.next()) {
                let key = raw_key.trim();
                let value = raw_value.trim().to_string();

                match key {
                    "Logged out of CS:GO" => stats.last_logout_csgo = Some(value),
                    "Launched CS:GO using Steam Client" | "Launched CSGO using Steam Client" => stats.last_launch_steam_client = Some(value),
                    "Started playing CS:GO" | "Started playing CSGO" => stats.start_play_csgo = Some(value),
                    "First Counter-Strike franchise game" => stats.first_played_cs_franchise = Some(value),
                    "Last known IP address" => stats.last_known_ip = Some(value),
                    "Earned a Service Medal" => stats.earned_service_medal = Some(value),
                    "CS:GO Profile Rank" | "CSGO Profile Rank" => stats.profile_rank = value.parse().ok(),
                    "Experience points earned towards next rank" => stats.xp_to_next_rank = value.parse().ok(),
                    "Anti-addiction online time" => stats.anti_addiction_online_time = Some(value),
                    _ => {}
                }
            }
        }

        // Parse activity table (some data might be in rows instead of single lines)
        for table in document.select(sel_kv_table()) {
            let mut rows = table.select(sel_tr());
            if let Some(header_row) = rows.next() {
                let headers: Vec<String> = header_row.select(sel_th()).map(|h| h.text().collect::<String>().trim().to_lowercase()).collect();

                if headers.contains(&"recorded activity".to_string()) && headers.contains(&"activity time".to_string()) {
                    for tr in rows {
                        let cells: Vec<String> = tr.select(sel_td()).map(|c| c.text().collect::<String>().trim().to_string()).collect();
                        if cells.len() >= 2 {
                            let key = &cells[0];
                            let value = cells[1].clone();
                            match key.as_str() {
                                "Logged out of CS:GO" => stats.last_logout_csgo = Some(value),
                                "Launched CS:GO using Steam Client" => stats.last_launch_steam_client = Some(value),
                                "Started playing CS:GO" => stats.start_play_csgo = Some(value),
                                "First Counter-Strike franchise game" => stats.first_played_cs_franchise = Some(value),
                                _ => {}
                            }
                        }
                    }
                }
            }
        }

        Ok(stats)
    }

    /// Fetches Steam batched loyalty reward items for given app ID(s).
    ///
    /// Uses the `ILoyaltyRewardsService/BatchedQueryRewardItems` Protobuf API.
    /// Loyalty rewards include items like profile backgrounds, emojis, and
    /// animated avatars.
    ///
    /// # Arguments
    ///
    /// * `app_ids` - A slice of Steam App IDs to query reward items for.
    ///
    /// # Returns
    ///
    /// Returns a `Vec` of Protobuf responses containing reward item details for
    /// each app.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let rewards = user.fetch_batched_loyalty_reward_items(&[730]).await?;
    /// println!("Found rewards for {} apps.", rewards.len());
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Api, path = "/ILoyaltyRewardsService/BatchedQueryRewardItems/v1", kind = Read)]
    pub async fn fetch_batched_loyalty_reward_items(&self, app_ids: &[u32]) -> Result<Vec<steam_protos::messages::CLoyaltyRewardsBatchedQueryRewardItemsResponseResponse>, SteamUserError> {
        use prost::Message;
        use steam_protos::messages::{CLoyaltyRewardsBatchedQueryRewardItemsRequest, CLoyaltyRewardsBatchedQueryRewardItemsResponse, CLoyaltyRewardsQueryRewardItemsRequest};

        if app_ids.is_empty() {
            return Ok(Vec::new());
        }

        let request = CLoyaltyRewardsBatchedQueryRewardItemsRequest {
            requests: app_ids
                .iter()
                .map(|&app_id| CLoyaltyRewardsQueryRewardItemsRequest {
                    appids: vec![app_id],
                    time_available: None,
                    community_item_classes: Vec::new(),
                    language: Some("english".to_string()),
                    count: Some(10),
                    cursor: None,
                    sort: Some(1),
                    sort_descending: Some(true),
                    reward_types: Vec::new(),
                    excluded_community_item_classes: Vec::new(),
                    definitionids: Vec::new(),
                    filters: Vec::new(),
                    filter_match_all_category_tags: Vec::new(),
                    filter_match_any_category_tags: Vec::new(),
                    contains_definitionids: Vec::new(),
                    include_direct_purchase_disabled: None,
                    excluded_content_descriptors: vec![3, 4],
                    excluded_appids: Vec::new(),
                    excluded_store_tagids: Vec::new(),
                    store_tagids: Vec::new(),
                    search_term: None,
                })
                .collect(),
        };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        let params = [("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body))];

        let response = self.get_path("/ILoyaltyRewardsService/BatchedQueryRewardItems/v1").query(&params).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let bytes = response.bytes().await?;
        let response_proto = CLoyaltyRewardsBatchedQueryRewardItemsResponse::decode(bytes)?;

        Ok(response_proto.responses)
    }

    /// Retrieves detailed information about all games the user owns.
    ///
    /// Scrapes the games page at `https://steamcommunity.com/my/games/?tab=all`
    /// and parses the `rgGames` JavaScript variable.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<OwnedAppDetail>` containing detailed info about each
    /// owned game.
    #[steam_endpoint(GET, host = Community, path = "/my/games/", kind = Read)]
    pub async fn get_owned_apps_detail(&self) -> Result<Vec<crate::types::apps::OwnedAppDetail>, SteamUserError> {
        let html = self.my_profile_get("games/?tab=all").await?;

        // Find rgGames variable in the HTML
        let start_marker = "var rgGames = ";
        let end_marker = "var rgChangingGames = []";

        let start = html.find(start_marker).ok_or_else(|| SteamUserError::MalformedResponse("rgGames not found".into()))?;

        let rest = &html[start + start_marker.len()..];
        let end = rest.find(end_marker).ok_or_else(|| SteamUserError::MalformedResponse("rgChangingGames not found".into()))?;

        let json_str = rest[..end].trim().trim_end_matches(';').trim();

        let apps: Vec<crate::types::apps::OwnedAppDetail> = serde_json::from_str(json_str).map_err(|e| SteamUserError::MalformedResponse(format!("Failed to parse rgGames: {}", e)))?;

        Ok(apps)
    }

    /// Retrieves dynamic store user data including owned apps, wishlist, and
    /// ignored apps.
    ///
    /// Fetches data from `https://store.steampowered.com/dynamicstore/userdata/`.
    ///
    /// # Returns
    ///
    /// Returns a `DynamicStoreUserData` containing lists of owned apps,
    /// packages, wishlist, etc.
    #[steam_endpoint(GET, host = Store, path = "/dynamicstore/userdata/", kind = Read)]
    pub async fn get_dynamic_store_user_data(&self) -> Result<crate::types::apps::DynamicStoreUserData, SteamUserError> {
        let response = self.get_path("/dynamicstore/userdata/").send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let data: crate::types::apps::DynamicStoreUserData = response.json().await?;
        Ok(data)
    }

    /// Retrieves an array of Steam AppIDs that the current user owns.
    ///
    /// This is a convenience wrapper around `get_dynamic_store_user_data()`.
    // delegates to `get_dynamic_store_user_data` — no #[steam_endpoint]
    ///
    /// # Returns
    ///
    /// Returns a `Vec<u32>` containing owned Steam AppIDs.
    #[tracing::instrument(skip(self))]
    pub async fn get_owned_apps_id(&self) -> Result<Vec<u32>, SteamUserError> {
        let data = self.get_dynamic_store_user_data().await?;
        Ok(data.owned_apps)
    }

    /// Fetches up-to-date status and version information for a Steam app.
    ///
    /// Uses the public API at `https://api.steampowered.com/ISteamApps/UpToDateCheck/v1/`.
    /// This is a static method that doesn't require authentication.
    ///
    /// # Arguments
    ///
    /// * `app_id` - The Steam App ID to check.
    ///
    /// # Returns
    ///
    /// Returns a `SteamAppVersionInfo` containing update status information.
    #[steam_endpoint(GET, host = Api, path = "/ISteamApps/UpToDateCheck/v1/", kind = Read)]
    pub async fn get_steam_app_version_info(app_id: u32) -> Result<crate::types::apps::SteamAppVersionInfo, SteamUserError> {
        let client = build_adhoc_client()?;
        let response = client.get("https://api.steampowered.com/ISteamApps/UpToDateCheck/v1/").query(&[("format", "json"), ("appid", &app_id.to_string()), ("version", "0")]).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let info: crate::types::apps::SteamAppVersionInfo = response.json().await?;
        Ok(info)
    }

    /// Fetches a list of suggested Steam apps based on a search term.
    ///
    /// Uses the Steam store search suggestions at `https://store.steampowered.com/search/suggest`.
    /// This is a static method that doesn't require authentication.
    ///
    /// # Arguments
    ///
    /// * `term` - The search keyword to suggest apps for.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<AppListItem>` containing suggested apps.
    #[steam_endpoint(GET, host = Store, path = "/search/suggest", kind = Read)]
    pub async fn suggest_app_list(term: &str) -> Result<Vec<crate::types::apps::AppListItem>, SteamUserError> {
        let client = build_adhoc_client()?;
        let response = client.get("https://store.steampowered.com/search/suggest").query(&[("term", term), ("f", "games"), ("cc", "VN"), ("realm", "1"), ("l", "english"), ("use_store_query", "1")]).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let html = response.text().await?;
        let document = Html::parse_document(&html);

        let mut items = Vec::new();
        for element in document.select(sel_match_anchor()) {
            let appid = element.value().attr("data-ds-appid").and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);

            let name = element.select(sel_match_name()).next().map(|e| e.text().collect::<String>().trim().to_string()).unwrap_or_default();

            let img = element.select(sel_match_img()).next().and_then(|e| e.value().attr("src")).unwrap_or("").to_string();

            let price = element.select(sel_match_price()).next().map(|e| e.text().collect::<String>().trim().to_string()).unwrap_or_default();

            if appid > 0 {
                items.push(crate::types::apps::AppListItem { appid, name, img, price });
            }
        }

        Ok(items)
    }

    /// Fetches a list of Steam apps from the store search results.
    ///
    /// Uses the Steam store search at `https://store.steampowered.com/search/results/`.
    /// This is a static method that doesn't require authentication.
    ///
    /// # Arguments
    ///
    /// * `term` - The search keyword to query.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<AppListItem>` containing matched apps.
    #[steam_endpoint(GET, host = Store, path = "/search/results/", kind = Read)]
    pub async fn query_app_list(term: &str) -> Result<Vec<crate::types::apps::AppListItem>, SteamUserError> {
        let client = build_adhoc_client()?;
        let response = client.get("https://store.steampowered.com/search/results/").query(&[("query", ""), ("start", "0"), ("count", "50"), ("dynamic_data", ""), ("sort_by", "_ASC"), ("term", term), ("infinite", "1")]).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        #[derive(serde::Deserialize)]
        struct SearchResponse {
            results_html: Option<String>,
        }

        let data: SearchResponse = response.json().await?;
        let results_html = data.results_html.unwrap_or_default();

        let document = Html::parse_document(&results_html);

        let mut items = Vec::new();
        for element in document.select(sel_search_row()) {
            let appid = element.value().attr("data-ds-appid").and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);

            let name = element.select(sel_search_name()).next().map(|e| e.text().collect::<String>().trim().to_string()).unwrap_or_default();

            let img = element.select(sel_search_capsule_img()).next().and_then(|e| e.value().attr("src")).unwrap_or("").to_string();

            let price = element.select(sel_search_price()).next().map(|e| e.text().collect::<String>().trim().to_string()).unwrap_or_default();

            if appid > 0 {
                items.push(crate::types::apps::AppListItem { appid, name, img, price });
            }
        }

        Ok(items)
    }

    /// Retrieves the full list of Steam applications.
    ///
    /// Uses the public API at `https://api.steampowered.com/ISteamApps/GetAppList/v0002/`.
    /// This is a static method that doesn't require authentication.
    ///
    /// # Returns
    ///
    /// Returns a `SimpleSteamAppList` containing all Steam applications.
    #[steam_endpoint(GET, host = Api, path = "/ISteamApps/GetAppList/v0002/", kind = Read)]
    pub async fn get_app_list() -> Result<crate::types::apps::SimpleSteamAppList, SteamUserError> {
        let client = build_adhoc_client()?;
        let response = client.get("https://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json").send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let list: crate::types::apps::SimpleSteamAppList = response.json().await?;
        Ok(list)
    }

    /// Fetches CS2 matchmaking stats (cooldown, summary, per-map, last played).
    ///
    /// Scrapes `https://steamcommunity.com/my/gcpd/730/?tab=matchmaking`.
    ///
    /// # Returns
    ///
    /// Returns a [`MatchmakingStats`] with all four tables parsed from the
    /// page.
    #[steam_endpoint(GET, host = Community, path = "/my/gcpd/730/", kind = Read)]
    pub async fn fetch_matchmaking_stats(&self) -> Result<crate::types::apps::MatchmakingStats, SteamUserError> {
        let html = self.my_profile_get("gcpd/730/?tab=matchmaking").await?;
        Ok(parse_matchmaking_html(&html))
    }
}

/// Parses the CS2 GCPD matchmaking HTML page into a [`MatchmakingStats`]
/// struct.
///
/// Accepts raw HTML (as fetched from `gcpd/730/?tab=matchmaking` or saved
/// locally).
pub fn parse_matchmaking_html(html: &str) -> crate::types::apps::MatchmakingStats {
    let document = Html::parse_document(html);

    let mut matchmaking_cooldown = None;
    let mut matchmaking_summary = Vec::new();
    let mut matchmaking_per_map = Vec::new();
    let mut last_played_modes = None;

    for table in document.select(sel_kv_table()) {
        let mut rows = table.select(sel_tr());
        if let Some(header_row) = rows.next() {
            let headers: Vec<String> = header_row.select(sel_th()).map(|h| h.text().collect::<String>().trim().to_lowercase()).collect();

            if headers == ["competitive cooldown expiration", "competitive cooldown level", "acknowledged"] {
                // Table 1: matchmaking_cooldown — Expiration | Level | Acknowledged
                let mut list = Vec::new();
                for tr in rows {
                    let cells: Vec<String> = tr.select(sel_td()).map(|c| c.text().collect::<String>().trim().to_string()).collect();
                    if cells.len() >= 3 {
                        list.push(crate::types::apps::CooldownInfo {
                            competitive_cooldown_expiration: cells.first().map(|s| {
                                if s.eq_ignore_ascii_case("never") || s.is_empty() {
                                    crate::types::apps::CooldownExpiration::Never
                                } else {
                                    let clean = s.replace("GMT", "");
                                    chrono::NaiveDateTime::parse_from_str(clean.trim(), "%Y-%m-%d %H:%M:%S").map(|dt| crate::types::apps::CooldownExpiration::At(dt.and_utc())).unwrap_or(crate::types::apps::CooldownExpiration::Never)
                                }
                            }),
                            competitive_cooldown_level: cells.get(1).and_then(|s| s.parse().ok()),
                            acknowledged: cells.get(2).is_some_and(|s| s.eq_ignore_ascii_case("yes")),
                        });
                    }
                }
                if !list.is_empty() {
                    matchmaking_cooldown = Some(list);
                }
            } else if headers == ["matchmaking mode", "map", "wins", "ties", "losses", "skill group", "last match", "region"] {
                // Table 3: matchmaking_per_map — Mode | Map | Wins | Ties | Losses | Skill
                // Group | Last Match | Region
                for tr in rows {
                    let cells: Vec<String> = tr.select(sel_td()).map(|c| c.text().collect::<String>().trim().to_string()).collect();
                    if cells.len() >= 2 {
                        matchmaking_per_map.push(crate::types::apps::MatchmakingPerMap {
                            matchmaking_mode: cells.first().cloned(),
                            map: cells.get(1).cloned(),
                            wins: cells.get(2).and_then(|s| s.parse().ok()),
                            ties: cells.get(3).and_then(|s| s.parse().ok()),
                            losses: cells.get(4).and_then(|s| s.parse().ok()),
                            skill_group: cells.get(5).cloned(),
                            last_match: cells.get(6).cloned(),
                            region: cells.get(7).and_then(|s| s.parse().ok()),
                        });
                    }
                }
            } else if headers == ["matchmaking mode", "wins", "ties", "losses", "skill group", "last match", "region"] {
                // Table 2: matchmaking_summary — Mode | Wins | Ties | Losses | Skill Group |
                // Last Match | Region
                for tr in rows {
                    let cells: Vec<String> = tr.select(sel_td()).map(|c| c.text().collect::<String>().trim().to_string()).collect();
                    if cells.len() >= 2 {
                        matchmaking_summary.push(crate::types::apps::MatchmakingSummary {
                            matchmaking_mode: cells.first().cloned(),
                            wins: cells.get(1).and_then(|s| s.parse().ok()),
                            ties: cells.get(2).and_then(|s| s.parse().ok()),
                            losses: cells.get(3).and_then(|s| s.parse().ok()),
                            skill_group: cells.get(4).cloned(),
                            last_match: cells.get(5).cloned(),
                            region: cells.get(6).and_then(|s| s.parse().ok()),
                        });
                    }
                }
            } else if headers == ["matchmaking mode", "last match"] {
                // Table 4: last_played_modes — Mode | Last Match
                let mut list = Vec::new();
                for tr in rows {
                    let cells: Vec<String> = tr.select(sel_td()).map(|c| c.text().collect::<String>().trim().to_string()).collect();
                    if cells.len() >= 2 {
                        list.push(crate::types::apps::LastPlayedMode { matchmaking_mode: cells.first().cloned(), last_match: cells.get(1).cloned() });
                    }
                }
                if !list.is_empty() {
                    last_played_modes = Some(list);
                }
            }
        }
    }

    crate::types::apps::MatchmakingStats { matchmaking_cooldown, matchmaking_summary, matchmaking_per_map, last_played_modes }
}

impl SteamUser {
    /// Fetches eligible event apps from the Steam Points Shop.
    ///
    /// Scrapes `https://store.steampowered.com/points/shop/c/events` and parses
    /// the loyalty store data to find event apps.
    /// This is a static method that doesn't require authentication.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<EligibleEventApp>` containing eligible event apps.
    #[steam_endpoint(GET, host = Store, path = "/points/shop/c/events", kind = Read)]
    pub async fn get_eligible_event_apps() -> Result<Vec<crate::types::apps::EligibleEventApp>, SteamUserError> {
        let client = build_adhoc_client()?;
        let response = client.get("https://store.steampowered.com/points/shop/c/events").send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let html = response.text().await?;
        let document = Html::parse_document(&html);

        let loyalty_str = document.select(sel_app_config()).next().and_then(|e| e.value().attr("data-loyaltystore")).ok_or_else(|| SteamUserError::MalformedResponse("data-loyaltystore not found".into()))?;

        #[derive(serde::Deserialize)]
        struct LoyaltyStore {
            eligible_apps: Option<EligibleApps>,
        }
        #[derive(serde::Deserialize)]
        struct EligibleApps {
            apps: Vec<crate::types::apps::EligibleEventApp>,
        }

        let loyalty_obj: LoyaltyStore = serde_json::from_str(loyalty_str).map_err(|e| SteamUserError::MalformedResponse(format!("Failed to parse loyalty store: {}", e)))?;

        let apps = loyalty_obj.eligible_apps.map(|ea| ea.apps.into_iter().filter(|a| a.event_app).collect()).unwrap_or_default();

        Ok(apps)
    }

    /// Fetches Steam app information using the Community GetApps API.
    ///
    /// Uses the protobuf endpoint at `https://api.steampowered.com/ICommunityService/GetApps/v1`.
    ///
    /// # Arguments
    ///
    /// * `app_ids` - A slice of Steam App IDs to fetch.
    ///
    /// # Returns
    ///
    /// Returns the protobuf response containing app information.
    #[steam_endpoint(POST, host = Api, path = "/ICommunityService/GetApps/v1", kind = Read)]
    pub async fn get_community_apps(&self, app_ids: &[u32]) -> Result<steam_protos::messages::community::CCommunityGetAppsResponse, SteamUserError> {
        use prost::Message;
        use steam_protos::messages::community::CCommunityGetAppsRequest;

        if app_ids.is_empty() {
            return Ok(steam_protos::messages::community::CCommunityGetAppsResponse { apps: Vec::new() });
        }

        let request = CCommunityGetAppsRequest { appids: app_ids.to_vec(), language: Some(0) };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        let params = [("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body))];

        let response = self.get_path("/ICommunityService/GetApps/v1").query(&params).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let bytes = response.bytes().await?;
        let response_proto = steam_protos::messages::community::CCommunityGetAppsResponse::decode(bytes)?;

        Ok(response_proto)
    }

    /// Retrieves Steam Store items for given app IDs.
    ///
    /// Uses the protobuf endpoint at `https://api.steampowered.com/IStoreBrowseService/GetItems/v1`.
    ///
    /// # Arguments
    ///
    /// * `app_ids` - A slice of Steam App IDs to fetch store items for.
    ///
    /// # Returns
    ///
    /// Returns the protobuf response containing store item information.
    #[steam_endpoint(POST, host = Api, path = "/IStoreBrowseService/GetItems/v1", kind = Read)]
    pub async fn get_steam_store_items(&self, app_ids: &[u32]) -> Result<steam_protos::messages::store::CStoreBrowseGetItemsResponse, SteamUserError> {
        use prost::Message;
        use steam_protos::messages::store::{
            c_store_browse_get_items_request::{StoreBrowseContext, StoreBrowseItemDataRequest, StoreItemId},
            CStoreBrowseGetItemsRequest,
        };

        if app_ids.is_empty() {
            return Ok(steam_protos::messages::store::CStoreBrowseGetItemsResponse { store_items: Vec::new() });
        }

        let request = CStoreBrowseGetItemsRequest {
            ids: app_ids.iter().map(|&appid| StoreItemId { appid: Some(appid), packageid: None, bundleid: None, tagid: None, creatorid: None, hubcategoryid: None }).collect(),
            context: Some(StoreBrowseContext {
                language: Some("english".to_string()),
                elanguage: None,
                country_code: Some("VN".to_string()),
                steam_realm: Some(1),
            }),
            data_request: Some(StoreBrowseItemDataRequest {
                include_assets: Some(true),
                include_release: None,
                include_platforms: None,
                include_all_purchase_options: None,
                include_screenshots: None,
                include_trailers: None,
                include_ratings: None,
                include_tag_count: None,
                include_reviews: None,
                include_basic_info: None,
                include_supported_languages: None,
                include_full_description: None,
                include_included_items: None,
                included_item_data_request: None,
                include_assets_without_overrides: None,
                apply_user_filters: None,
                include_links: None,
            }),
        };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        let params = [("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body))];

        let response = self.get_path("/IStoreBrowseService/GetItems/v1").query(&params).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let bytes = response.bytes().await?;
        let response_proto = steam_protos::messages::store::CStoreBrowseGetItemsResponse::decode(bytes)?;

        Ok(response_proto)
    }

    /// Checks which friends own a specific package (useful for gifting
    /// validation).
    ///
    /// Uses the `ICheckoutService/GetFriendOwnershipForGifting/v1` endpoint.
    ///
    /// # Arguments
    ///
    /// * `access_token` - The OAuth access token to use.
    /// * `package_id` - The Steam Package ID to check (e.g. 54029 for CS:GO
    ///   Prime).
    ///
    /// # Returns
    ///
    /// Returns a `FriendOwnershipResponse` containing ownership info for
    /// friends.
    #[steam_endpoint(POST, host = Api, path = "/ICheckoutService/GetFriendOwnershipForGifting/v1", kind = Read)]
    pub async fn get_friend_ownership_for_gifting(&self, access_token: &str, package_id: u32) -> Result<crate::types::apps::FriendOwnershipResponse, SteamUserError> {
        use prost::Message;

        #[derive(Clone, PartialEq, ::prost::Message)]
        pub struct OwnershipItemIdProto {
            #[prost(uint32, optional, tag = "1")]
            pub appid: Option<u32>,
            #[prost(uint32, optional, tag = "2")]
            pub packageid: Option<u32>,
            #[prost(uint32, optional, tag = "3")]
            pub bundleid: Option<u32>,
            #[prost(uint32, optional, tag = "4")]
            pub tagid: Option<u32>,
            #[prost(uint32, optional, tag = "5")]
            pub creatorid: Option<u32>,
            #[prost(uint32, optional, tag = "6")]
            pub hubcategoryid: Option<u32>,
        }

        #[derive(Clone, PartialEq, ::prost::Message)]
        pub struct CCheckoutGetFriendOwnershipForGiftingRequest {
            #[prost(message, repeated, tag = "1")]
            pub item_ids: ::prost::alloc::vec::Vec<OwnershipItemIdProto>,
        }

        #[derive(Clone, PartialEq, ::prost::Message)]
        pub struct FriendOwnershipProto {
            #[prost(uint32, repeated, tag = "1")]
            pub partial_owns_appids: ::prost::alloc::vec::Vec<u32>,
            #[prost(uint32, repeated, tag = "2")]
            pub partial_wishes_for: ::prost::alloc::vec::Vec<u32>,
            #[prost(uint32, tag = "3")]
            pub accountid: u32,
            #[prost(bool, tag = "4")]
            pub already_owns: bool,
            #[prost(bool, tag = "5")]
            pub wishes_for: bool,
        }

        #[derive(Clone, PartialEq, ::prost::Message)]
        pub struct FriendOwnershipInfoProto {
            #[prost(message, repeated, tag = "1")]
            pub friend_ownership: ::prost::alloc::vec::Vec<FriendOwnershipProto>,
            #[prost(message, optional, tag = "2")]
            pub item_id: Option<OwnershipItemIdProto>,
        }

        #[derive(Clone, PartialEq, ::prost::Message)]
        pub struct CCheckoutGetFriendOwnershipForGiftingResponse {
            #[prost(message, repeated, tag = "1")]
            pub ownership_info: ::prost::alloc::vec::Vec<FriendOwnershipInfoProto>,
        }

        let item_id = OwnershipItemIdProto { packageid: Some(package_id), appid: None, bundleid: None, tagid: None, creatorid: None, hubcategoryid: None };

        let request = CCheckoutGetFriendOwnershipForGiftingRequest { item_ids: vec![item_id] };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        let params = [("access_token", access_token), ("spoof_steamid", ""), ("origin", "https://store.steampowered.com"), ("input_protobuf_encoded", &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &body))];

        let response = self.get_path("/ICheckoutService/GetFriendOwnershipForGifting/v1").query(&params).send().await?;

        if !response.status().is_success() {
            return Err(SteamUserError::HttpStatus {
                status: response.status().as_u16(),
                url: response.url().to_string(),
            });
        }

        let bytes = response.bytes().await?;
        let response_proto = CCheckoutGetFriendOwnershipForGiftingResponse::decode(bytes)?;

        let ownership_info = response_proto
            .ownership_info
            .into_iter()
            .map(|info| crate::types::apps::FriendOwnershipInfo {
                friend_ownership: info
                    .friend_ownership
                    .into_iter()
                    .map(|fo| crate::types::apps::FriendOwnership {
                        partial_owns_appids: fo.partial_owns_appids,
                        partial_wishes_for: fo.partial_wishes_for,
                        accountid: fo.accountid,
                        already_owns: fo.already_owns,
                        wishes_for: fo.wishes_for,
                    })
                    .collect(),
                item_id: info.item_id.map(|id| crate::types::apps::OwnershipItemId {
                    appid: id.appid,
                    packageid: id.packageid,
                    bundleid: id.bundleid,
                    tagid: id.tagid,
                    creatorid: id.creatorid,
                    hubcategoryid: id.hubcategoryid,
                }),
            })
            .collect();

        Ok(crate::types::apps::FriendOwnershipResponse { ownership_info })
    }
}