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
//! Account management services.

use std::sync::OnceLock;

use regex::Regex;
use scraper::{Html, Selector};

use crate::{
    client::SteamUser,
    endpoint::steam_endpoint,
    error::SteamUserError,
    types::{AccountDetails, PurchaseHistoryItem, RedeemWalletCodeResponse, TransactionId, WalletBalance},
    utils::get_avatar_hash_from_url,
};

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

static SEL_TOOLTIP: OnceLock<Selector> = OnceLock::new();
fn sel_tooltip() -> &'static Selector {
    SEL_TOOLTIP.get_or_init(|| Selector::parse("span.tooltip").expect("valid CSS selector"))
}

static SEL_HELP_SPEND: OnceLock<Selector> = OnceLock::new();
fn sel_help_spend() -> &'static Selector {
    SEL_HELP_SPEND.get_or_init(|| Selector::parse(".help_event_limiteduser .help_event_limiteduser_spend").expect("valid CSS selector"))
}

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

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

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

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

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

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

static SEL_WHT_BASE_PRICE: OnceLock<Selector> = OnceLock::new();
fn sel_wht_base_price() -> &'static Selector {
    SEL_WHT_BASE_PRICE.get_or_init(|| Selector::parse(".wht_base_price, .wht_base_price_discounted").expect("valid CSS selector"))
}

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

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

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

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

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

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

static RE_CURRENCY_END: OnceLock<Regex> = OnceLock::new();
fn re_currency_end() -> &'static Regex {
    RE_CURRENCY_END.get_or_init(|| Regex::new(r"([^\d.,\s].*)$").expect("valid regex"))
}

static RE_CURRENCY_START: OnceLock<Regex> = OnceLock::new();
fn re_currency_start() -> &'static Regex {
    RE_CURRENCY_START.get_or_init(|| Regex::new(r"^([^\d.,\s]+)").expect("valid regex"))
}

static RE_PENDING: OnceLock<Regex> = OnceLock::new();
fn re_pending() -> &'static Regex {
    RE_PENDING.get_or_init(|| Regex::new(r"Pending:\s*([\d.,]+[^\s]*)").expect("valid regex"))
}

static RE_TRANSID: OnceLock<Regex> = OnceLock::new();
fn re_transid() -> &'static Regex {
    RE_TRANSID.get_or_init(|| Regex::new(r"transid=(\d+)").expect("valid regex"))
}

/// Parse wallet balance fields out of any Steam Store HTML document.
///
/// Looks for `#header_wallet_balance` (present on every logged-in Store page),
/// extracts the display text as `main_balance`, detects the currency symbol,
/// and reads any pending balance from the tooltip child span.
pub(crate) fn parse_wallet_balance(document: &Html) -> WalletBalance {
    let mut main_balance = None;
    let mut currency = None;
    let mut pending = None;

    if let Some(el) = document.select(sel_balance()).next() {
        // Collect only direct text nodes — ignores the nested tooltip <span>
        let text: String = el.children().filter_map(|n| n.value().as_text().map(|t| t.to_string())).collect::<String>().trim().to_string();

        if !text.is_empty() {
            // Currency symbol: non-digit/non-separator chars at start or end
            if let Some(caps) = re_currency_end().captures(&text) {
                currency = Some(caps[1].trim().to_string());
            } else if let Some(caps) = re_currency_start().captures(&text) {
                currency = Some(caps[1].trim().to_string());
            }

            main_balance = Some(text);
        }

        // Pending balance lives inside the tooltip child span
        if let Some(tip) = el.select(sel_tooltip()).next() {
            let tip_text = tip.text().collect::<String>();
            if let Some(caps) = re_pending().captures(&tip_text) {
                pending = Some(caps[1].to_string());
            }
        }
    }

    WalletBalance { main_balance, pending, currency }
}

impl SteamUser {
    /// Retrieves the Steam Wallet balance(s) and account currency.
    ///
    /// Scrapes the Steam Community home page to extract the main wallet balance
    /// and any pending balances.
    ///
    /// # Returns
    ///
    /// Returns a [`WalletBalance`] struct containing:
    /// - `main_balance`: The current available balance (e.g., "$10.00").
    /// - `pending`: Any pending balance awaiting verification.
    /// - `currency`: The currency symbol or code extracted from the balance
    ///   string.
    ///
    /// # Errors
    ///
    /// Returns [`SteamUserError::Other("Not logged in")`] if the session is not
    /// authenticated.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let wallet = user.get_steam_wallet_balance().await?;
    /// if let Some(balance) = wallet.main_balance {
    ///     println!("Current balance: {}", balance);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    // delegates to `get_account_details` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_steam_wallet_balance(&self) -> Result<WalletBalance, SteamUserError> {
        let details = self.get_account_details().await?;
        details.wallet_balance.ok_or_else(|| SteamUserError::Other("Wallet balance not found".into()))
    }

    /// Retrieves the total amount spent on Steam for the current account.
    ///
    /// Scrapes the Steam Help page to determine the lifetime spending on the
    /// account. This is often used to check if an account is "limited"
    /// (spent less than $5.00).
    ///
    /// # Returns
    ///
    /// Returns a `String` representing the total amount spent (e.g.,
    /// "$150.42").
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let spent = user.get_amount_spent_on_steam().await?;
    /// println!("Lifetime spend: {}", spent);
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Help, path = "/en/", kind = Read)]
    pub async fn get_amount_spent_on_steam(&self) -> Result<String, SteamUserError> {
        let response = self.get_path("/en/").send().await?.text().await?;

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

        if let Some(el) = document.select(sel_help_spend()).next() {
            let text = el.text().collect::<String>().trim().to_string();
            // Clean space equivalent
            let text = text.split_whitespace().collect::<Vec<_>>().join(" ");

            if text.starts_with("Amount Spent on Steam:") {
                return Ok(text.replace("Amount Spent on Steam:", "").trim().to_string());
            }
        }

        Err(SteamUserError::Other("Amount spent information not found on help page".into()))
    }

    /// Unlocks Steam Parental Controls using the provided PIN.
    ///
    /// Sends a POST request to `https://steamcommunity.com/parental/ajaxunlock`.
    ///
    /// # Arguments
    ///
    /// * `pin` - A 4-digit PIN code as a string.
    ///
    /// # Errors
    ///
    /// - Returns [`SteamUserError::Other("Incorrect PIN")`] if the PIN is
    ///   wrong.
    /// - Returns [`SteamUserError::Other("Too many invalid PIN attempts")`] if
    ///   locked out.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// match user.parental_unlock("1234").await {
    ///     Ok(_) => println!("Unlocked!"),
    ///     Err(e) => eprintln!("Failed to unlock: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/parental/ajaxunlock", kind = Auth)]
    pub async fn parental_unlock(&self, pin: &str) -> Result<(), SteamUserError> {
        let response: serde_json::Value = self.post_path("/parental/ajaxunlock").form(&[("pin", pin)]).send().await?.json().await?;

        let result = Self::check_json_success(&response, "Failed to unlock parental controls");

        match result {
            Ok(_) => Ok(()),
            Err(SteamUserError::EResult { code, .. }) => match code {
                15 => Err(SteamUserError::Other("Incorrect PIN".into())),
                25 => Err(SteamUserError::Other("Too many invalid PIN attempts".into())),
                _ => Err(SteamUserError::from_eresult(code)),
            },
            Err(e) => Err(e),
        }
    }

    /// Retrieves the Steam purchase history for the current account.
    ///
    /// Scrapes the account purchase history page at `https://store.steampowered.com/account/history/`.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<PurchaseHistoryItem>` containing all visible purchase
    /// history entries.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the page cannot be parsed.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let history = user.get_purchase_history().await?;
    /// for item in history {
    ///     println!("{}: {} - {}", item.date, item.transaction_type, item.total);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Store, path = "/account/history/", kind = Read)]
    pub async fn get_purchase_history(&self) -> Result<Vec<PurchaseHistoryItem>, SteamUserError> {
        let response = self.get_path("/account/history/").send().await?.text().await?;

        Self::parse_purchase_history_html(&response)
    }

    /// Pure parsing function for the purchase history page HTML.
    ///
    /// Extracted for easier testing and offline parsing.
    pub fn parse_purchase_history_html(html: &str) -> Result<Vec<PurchaseHistoryItem>, SteamUserError> {
        let document = Html::parse_document(html);

        // Check for login redirect
        if let Some(title) = document.select(sel_title()).next() {
            if title.text().collect::<String>() == "Sign In" {
                return Err(SteamUserError::Other("Not logged in".into()));
            }
        }

        let mut history = Vec::new();

        for row in document.select(sel_wallet_row()) {
            let date_str = row.select(sel_wht_date()).next().map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();

            // Try different date formats Steam uses. Steam reports day
            // granularity; promote to midnight UTC so the stored value is
            // timezone-unambiguous. Falls back to the chrono default
            // (1970-01-01) when no format matches.
            let date_naive = chrono::NaiveDate::parse_from_str(&date_str, "%d %b, %Y").or_else(|_| chrono::NaiveDate::parse_from_str(&date_str, "%e %b, %Y")).or_else(|_| chrono::NaiveDate::parse_from_str(&date_str, "%b %d, %Y")).or_else(|_| chrono::NaiveDate::parse_from_str(&date_str, "%b %e, %Y")).unwrap_or_default();
            let date = date_naive.and_hms_opt(0, 0, 0).map(|naive| chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(naive, chrono::Utc)).unwrap_or_default();

            let transaction_type = row.select(sel_wht_type()).next().map(|el| el.text().find(|t| !t.trim().is_empty()).unwrap_or_default().trim().to_string()).unwrap_or_default();

            // Items can have multiple items separated
            let items: Vec<String> = row.select(sel_wht_items()).next().map(|el| el.text().collect::<String>().lines().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default();

            let total = row.select(sel_wht_total()).next().map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();

            let payment_method = row.select(sel_wth_payment()).next().map(|el| el.text().collect::<String>().trim().to_string()).filter(|s| !s.is_empty());

            let wallet_balance = row.select(sel_wht_wallet()).next().map(|el| el.text().collect::<String>().trim().to_string()).filter(|s| !s.is_empty());

            let base_price = row.select(sel_wht_base_price()).next().map(|el| el.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")).filter(|s| !s.is_empty());
            let tax = row.select(sel_wht_tax()).next().map(|el| el.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")).filter(|s| !s.is_empty());
            let shipping = row.select(sel_wht_shipping()).next().map(|el| el.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")).filter(|s| !s.is_empty());
            let wallet_change = row.select(sel_wht_wallet_change()).next().map(|el| el.text().collect::<String>().trim().to_string()).filter(|s| !s.is_empty() && s != "Change");

            // Try to extract transaction ID from data attributes or links
            let mut transaction_id = row.value().attr("data-transid").or_else(|| row.value().attr("data-transactionid")).map(|s| s.to_string());

            // Sometimes transid is in the onclick handler URL
            if transaction_id.is_none() {
                if let Some(onclick) = row.value().attr("onclick") {
                    if let Some(caps) = re_transid().captures(onclick) {
                        transaction_id = Some(caps[1].to_string());
                    }
                }
            }

            let transaction_id = transaction_id.map(TransactionId);

            // Only add if we have at least date and type
            if !transaction_type.is_empty() {
                history.push(PurchaseHistoryItem {
                    date,
                    transaction_type,
                    items,
                    total,
                    base_price,
                    tax,
                    shipping,
                    wallet_change,
                    payment_method,
                    wallet_balance,
                    transaction_id,
                });
            }
        }

        Ok(history)
    }

    /// Redeems a Steam wallet code to add funds to the account.
    ///
    /// Posts to `https://store.steampowered.com/account/ajaxredeemwalletcode/`.
    ///
    /// # Arguments
    ///
    /// * `wallet_code` - The Steam wallet code to redeem (e.g.,
    ///   "XXXXX-XXXXX-XXXXX").
    ///
    /// # Returns
    ///
    /// Returns a [`RedeemWalletCodeResponse`] containing the result of the
    /// redemption.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails. Common error codes in the
    /// response:
    /// - `success: 1` - Code redeemed successfully
    /// - `success: 2` with `detail: 14` - Invalid code
    /// - `success: 2` with `detail: 15` - Already redeemed
    /// - `success: 2` with `detail: 53` - Rate limited
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let result = user.redeem_wallet_code("XXXXX-XXXXX-XXXXX").await?;
    /// if result.success == 1 {
    ///     println!(
    ///         "Redeemed! New balance: {:?}",
    ///         result.formatted_new_wallet_balance
    ///     );
    /// } else {
    ///     println!("Failed with detail: {:?}", result.detail);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Store, path = "/account/ajaxredeemwalletcode/", kind = Write)]
    pub async fn redeem_wallet_code(&self, wallet_code: &str) -> Result<RedeemWalletCodeResponse, SteamUserError> {
        let response: RedeemWalletCodeResponse = self.post_path("/account/ajaxredeemwalletcode/").form(&[("wallet_code", wallet_code)]).send().await?.json().await?;

        Ok(response)
    }

    /// Fetches and parses the Steam authorized-devices page.
    ///
    /// Scrapes `https://store.steampowered.com/account/authorizeddevices` and
    /// extracts every JSON data blob embedded by Steam into the page:
    ///
    /// | Field | Source attribute |
    /// |---|---|
    /// | `active_devices` | `data-active_devices` |
    /// | `revoked_devices` | `data-revoked_devices` |
    /// | `two_factor_status` | `data-two_factor_status` |
    /// | `user_info` | `data-userinfo` |
    /// | `hw_info` | `data-hwinfo` |
    /// | `page_config` | `data-config` |
    /// | `store_user_config` | `data-store_user_config` (includes WebAPI JWT) |
    /// | `notifications` | `data-steam_notifications` |
    /// | `broadcast_user` | `data-broadcastuser` |
    /// | `account_name` | `data-accountName` |
    /// | `email` | `data-email` |
    /// | `phone_hint` | `data-phone_hint` |
    /// | `latest_android_app_version` | `data-latest_android_app_version` |
    /// | `requesting_token_id` | `data-requesting_token_id` |
    ///
    /// # Errors
    ///
    /// Returns [`SteamUserError::Other("Not logged in")`] if the session is
    /// unauthenticated (Steam redirects to the Sign In page).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let page = user.get_account_details().await?;
    /// println!("Account: {:?}", page.account_name);
    /// println!("Country: {:?}", page.country);
    /// println!("Security: {:?}", page.account_security());
    /// println!("Active sessions: {}", page.active_devices.len());
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Store, path = "/account/authorizeddevices", kind = Read)]
    pub async fn get_account_details(&self) -> Result<AccountDetails, SteamUserError> {
        let response = self.get_path("/account/authorizeddevices").send().await?.text().await?;

        let document = Html::parse_document(&response);
        if let Some(title) = document.select(sel_title()).next() {
            if title.text().collect::<String>() == "Sign In" {
                return Err(SteamUserError::Other("Not logged in".into()));
            }
        }

        Ok(parse_account_details_html(&response))
    }
}

/// Parse an account-details page HTML string into [`AccountDetails`].
///
/// Pure parsing — no network request. Pass the raw HTML from
/// `https://store.steampowered.com/account/authorizeddevices`.
/// Useful for testing against saved HTML or caching the raw response.
pub fn parse_account_details_html(html: &str) -> AccountDetails {
    let document = Html::parse_document(html);

    fn parse_json<T: for<'de> serde::Deserialize<'de>>(doc: &Html, attr: &str) -> Option<T> {
        let sel = Selector::parse(&format!("[{}]", attr)).ok()?;
        let val = doc.select(&sel).next()?.value().attr(attr)?;
        serde_json::from_str(val).ok()
    }

    fn parse_str(doc: &Html, attr: &str) -> Option<String> {
        let sel = Selector::parse(&format!("[{}]", attr)).ok()?;
        let val = doc.select(&sel).next()?.value().attr(attr)?;
        serde_json::from_str(val).ok()
    }

    let mut page = AccountDetails {
        active_devices: parse_json::<Vec<_>>(&document, "data-active_devices").unwrap_or_default(),
        revoked_devices: parse_json::<Vec<_>>(&document, "data-revoked_devices").unwrap_or_default(),
        two_factor_status: parse_json(&document, "data-two_factor_status"),
        user_info: parse_json(&document, "data-userinfo"),
        hw_info: parse_json(&document, "data-hwinfo"),
        page_config: parse_json(&document, "data-config"),
        store_user_config: parse_json(&document, "data-store_user_config"),
        notifications: parse_json(&document, "data-steam_notifications"),
        broadcast_user: parse_json(&document, "data-broadcastuser"),
        account_name: parse_str(&document, "data-accountname"),
        email: parse_str(&document, "data-email"),
        phone_hint: parse_str(&document, "data-phone_hint"),
        latest_android_app_version: parse_str(&document, "data-latest_android_app_version"),
        requesting_token_id: parse_str(&document, "data-requesting_token_id"),
        wallet_balance: Some(parse_wallet_balance(&document)).filter(|w| w.main_balance.is_some()),
        ..Default::default()
    };

    page.avatar_hash = document.select(sel_player_avatar_img()).next().and_then(|el| el.value().attr("src")).and_then(get_avatar_hash_from_url);

    page.country = page.user_info.as_ref().and_then(|u| u.country_code.clone());

    page
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_purchase_history() {
        let html = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/steam_response/get_purchase_history.html")).expect("Failed to read HTML file");

        // The file `get_purchase_history.html` is saved as a view-source page from
        // Chrome, so it's nested in `.line-content`
        let mut html_to_parse = String::new();
        for line in html.lines() {
            if line.contains("<td class=\"line-content\">") {
                let text = line.replace("<td class=\"line-content\">", "").replace("</td>", "");
                html_to_parse.push_str(&text);
                html_to_parse.push('\n');
            }
        }

        if html_to_parse.trim().is_empty() {
            html_to_parse = html;
        }

        // We must decode html entities to turn &lt; back to <
        let html_to_parse = html_to_parse.replace("<span class=\"html-tag\">", "").replace("<span class=\"html-attribute-name\">", "").replace("<span class=\"html-attribute-value\">", "").replace("<a class=\"html-attribute-value html-external-link\"", "<a").replace("</span>", "").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&");

        let result = SteamUser::parse_purchase_history_html(&html_to_parse);
        assert!(result.is_ok(), "Should parse HTML successfully: {:?}", result.err());
        let history = result.unwrap();

        assert!(!history.is_empty(), "History should not be empty, html string length: {}", html_to_parse.len());

        // Verify the first item (noting the test data structure might vary, so adapt to
        // it)
        let first = &history[0];
        // The date parsing relies on proper dates in HTML, we skip the exact date check
        // if it fails and just check it parses
        assert!(!first.transaction_type.is_empty());
        assert!(!first.total.is_empty());

        tracing::info!("Successfully parsed {} history items", history.len());
    }
}