Skip to main content

steam_user/services/
trade.rs

1//! Trade service for Steam Community.
2
3use std::sync::OnceLock;
4
5use regex::Regex;
6use scraper::{Html, Selector};
7use serde_json::json;
8use steamid::SteamID;
9
10use crate::{
11    client::SteamUser,
12    endpoint::steam_endpoint,
13    error::SteamUserError,
14    types::{ParsedTradeURL, TradeOffer, TradeOfferAsset, TradeOfferItem, TradeOfferItems, TradeOfferPartner, TradeOfferResult, TradeOfferStatus, TradeOfferSummary, TradeOffersResponse},
15};
16
17// Selectors used by `get_trade_offer` are static — hoisted to module-level
18// `OnceLock<Selector>` so they compile exactly once instead of per trade
19// offer (the page can list dozens at a time).
20static SEL_TRADE_URL: OnceLock<Selector> = OnceLock::new();
21fn sel_trade_url() -> &'static Selector {
22    SEL_TRADE_URL.get_or_init(|| Selector::parse("#trade_offer_access_url").expect("valid CSS selector"))
23}
24
25static SEL_SUBPAGE: OnceLock<Selector> = OnceLock::new();
26fn sel_subpage() -> &'static Selector {
27    SEL_SUBPAGE.get_or_init(|| Selector::parse(".profile_subpage_selector > a").expect("valid CSS selector"))
28}
29
30static SEL_ESCROW: OnceLock<Selector> = OnceLock::new();
31fn sel_escrow() -> &'static Selector {
32    SEL_ESCROW.get_or_init(|| Selector::parse(".trade_offers_escrow_explanation > .title").expect("valid CSS selector"))
33}
34
35static SEL_TRADEOFFER: OnceLock<Selector> = OnceLock::new();
36fn sel_tradeoffer() -> &'static Selector {
37    SEL_TRADEOFFER.get_or_init(|| Selector::parse(".profile_leftcol > .tradeoffer").expect("valid CSS selector"))
38}
39
40static SEL_PLAYER_AVATAR: OnceLock<Selector> = OnceLock::new();
41fn sel_player_avatar() -> &'static Selector {
42    SEL_PLAYER_AVATAR.get_or_init(|| Selector::parse(".playerAvatar").expect("valid CSS selector"))
43}
44
45static SEL_IMG: OnceLock<Selector> = OnceLock::new();
46fn sel_img() -> &'static Selector {
47    SEL_IMG.get_or_init(|| Selector::parse("img").expect("valid CSS selector"))
48}
49
50static SEL_A: OnceLock<Selector> = OnceLock::new();
51fn sel_a() -> &'static Selector {
52    SEL_A.get_or_init(|| Selector::parse("a").expect("valid CSS selector"))
53}
54
55static SEL_TRADEOFFER_HEADER: OnceLock<Selector> = OnceLock::new();
56fn sel_tradeoffer_header() -> &'static Selector {
57    SEL_TRADEOFFER_HEADER.get_or_init(|| Selector::parse(".tradeoffer_header").expect("valid CSS selector"))
58}
59
60static SEL_ITEMS_CTN: OnceLock<Selector> = OnceLock::new();
61fn sel_items_ctn() -> &'static Selector {
62    SEL_ITEMS_CTN.get_or_init(|| Selector::parse(".tradeoffer_items_ctn").expect("valid CSS selector"))
63}
64
65static SEL_PRIMARY_ITEMS: OnceLock<Selector> = OnceLock::new();
66fn sel_primary_items() -> &'static Selector {
67    SEL_PRIMARY_ITEMS.get_or_init(|| Selector::parse(".tradeoffer_items_ctn .tradeoffer_items.primary").expect("valid CSS selector"))
68}
69
70static SEL_SECONDARY_ITEMS: OnceLock<Selector> = OnceLock::new();
71fn sel_secondary_items() -> &'static Selector {
72    SEL_SECONDARY_ITEMS.get_or_init(|| Selector::parse(".tradeoffer_items_ctn .tradeoffer_items.secondary").expect("valid CSS selector"))
73}
74
75static SEL_AVATAR_LINK: OnceLock<Selector> = OnceLock::new();
76fn sel_avatar_link() -> &'static Selector {
77    SEL_AVATAR_LINK.get_or_init(|| Selector::parse("a.tradeoffer_avatar").expect("valid CSS selector"))
78}
79
80static SEL_TRADE_ITEM: OnceLock<Selector> = OnceLock::new();
81fn sel_trade_item() -> &'static Selector {
82    SEL_TRADE_ITEM.get_or_init(|| Selector::parse(".tradeoffer_item_list > .trade_item").expect("valid CSS selector"))
83}
84
85static SEL_ITEMS_BANNER: OnceLock<Selector> = OnceLock::new();
86fn sel_items_banner() -> &'static Selector {
87    SEL_ITEMS_BANNER.get_or_init(|| Selector::parse(".tradeoffer_items_banner").expect("valid CSS selector"))
88}
89
90static RE_HTML_TAGS: OnceLock<Regex> = OnceLock::new();
91fn re_html_tags() -> &'static Regex {
92    RE_HTML_TAGS.get_or_init(|| Regex::new(r"<[^>]+>").expect("valid regex"))
93}
94
95impl SteamUser {
96    /// Retrieves the authenticated user's unique trade offer URL.
97    ///
98    /// This URL allows other users to send you trade offers without being on
99    /// your friends list. The URL is scraped from the user's trade privacy
100    /// settings page.
101    #[steam_endpoint(GET, host = Community, path = "/my/tradeoffers/privacy", kind = Read)]
102    pub async fn get_trade_url(&self) -> Result<Option<String>, SteamUserError> {
103        let response = self.get_path("/my/tradeoffers/privacy").send().await?.text().await?;
104
105        let html = Html::parse_document(&response);
106
107        Ok(html.select(sel_trade_url()).next().and_then(|el| el.value().attr("value").map(|v| v.to_string())))
108    }
109
110    /// Retrieves a list of active trade offers (incoming and outgoing) from the
111    /// trade offers page.
112    ///
113    /// Scrapes `https://steamcommunity.com/my/tradeoffers/` to extract offer IDs, status, and item summaries.
114    #[steam_endpoint(GET, host = Community, path = "/my/tradeoffers/", kind = Read)]
115    pub async fn get_trade_offer(&self) -> Result<TradeOffersResponse, SteamUserError> {
116        let response = self.get_with_manual_redirects("https://steamcommunity.com/my/tradeoffers/").await?;
117        Ok(Self::parse_trade_offers_page(&response))
118    }
119
120    /// Retrieves the account's own **outgoing** (sent) trade offers.
121    ///
122    /// `get_trade_offer` scrapes `/my/tradeoffers/` (the incoming page), which
123    /// reports the *sent count* but not the sent offers themselves. This scrapes
124    /// `/my/tradeoffers/sent/` so the parsed `trade_offers` list contains the
125    /// outgoing offers (needed to cancel stale ones). The `sent_offers` /
126    /// `incoming_offers` summary counts are populated the same way on both pages.
127    #[steam_endpoint(GET, host = Community, path = "/my/tradeoffers/sent/", kind = Read)]
128    pub async fn get_sent_trade_offers(&self) -> Result<TradeOffersResponse, SteamUserError> {
129        let response = self.get_with_manual_redirects("https://steamcommunity.com/my/tradeoffers/sent/").await?;
130        Ok(Self::parse_trade_offers_page(&response))
131    }
132
133    /// Parses a Steam trade-offers HTML page (incoming or sent) into a
134    /// [`TradeOffersResponse`]. Pure function over the page HTML — no I/O — so
135    /// both `get_trade_offer` and `get_sent_trade_offers` share it.
136    fn parse_trade_offers_page(response: &str) -> TradeOffersResponse {
137        let html = Html::parse_document(response);
138
139        let mut incoming_offers = TradeOfferSummary { link: String::new(), count: 0 };
140        let mut sent_offers = TradeOfferSummary { link: String::new(), count: 0 };
141        let mut trade_hold_count = 0;
142
143        for el in html.select(sel_subpage()) {
144            let text = el.text().collect::<String>();
145            let link = el.value().attr("href").unwrap_or("").trim_end_matches('/').to_string();
146            let mut count = 0;
147            if let (Some(start), Some(end)) = (text.find('('), text.find(')')) {
148                count = text[start + 1..end].trim().parse().unwrap_or(0);
149            }
150
151            if link.ends_with("tradeoffers") {
152                incoming_offers = TradeOfferSummary { link, count };
153            } else if link.ends_with("tradeoffers/sent") {
154                sent_offers = TradeOfferSummary { link, count };
155            }
156        }
157
158        if let Some(el) = html.select(sel_escrow()).next() {
159            let text = el.text().collect::<String>().trim().to_string();
160            if text.ends_with("trade on hold") || text.ends_with("trades on hold") {
161                trade_hold_count = text.split(' ').next().and_then(|s| s.parse().ok()).unwrap_or(0);
162            }
163        }
164
165        let mut trade_offers = Vec::new();
166        for el in html.select(sel_tradeoffer()) {
167            let id_str = el.value().attr("id").unwrap_or("");
168            if !id_str.starts_with("tradeofferid_") {
169                continue;
170            }
171            let tradeofferid = id_str["tradeofferid_".len()..].parse().unwrap_or(0);
172            if tradeofferid == 0 {
173                continue;
174            }
175
176            let html_content = el.html();
177            let partner_data = if let Some(start) = html_content.find("ReportTradeScam(") {
178                let rest = &html_content[start + "ReportTradeScam(".len()..];
179                if let Some(end) = rest.find(");") {
180                    let part = rest[..end].trim();
181                    let parts: Vec<String> = part
182                        .split(',')
183                        .map(|s| {
184                            // Decode HTML entities first, then trim quotes/whitespace
185                            let decoded = s.trim().replace("&quot;", "\"").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'");
186                            decoded.trim_matches(|c: char| c == '\'' || c == '"').trim().to_string()
187                        })
188                        .collect();
189                    if parts.len() >= 2 {
190                        // Steam embeds the partner SteamID64 as a decimal
191                        // string. Parse to SteamID at this boundary; drop the
192                        // offer if it doesn't parse so we never carry a
193                        // bogus ID forward.
194                        let steam_id = parts[0].parse::<SteamID>().ok();
195                        let name = decode_js_unicode_escapes(&parts[1]);
196                        Some((steam_id, name))
197                    } else {
198                        None
199                    }
200                } else {
201                    None
202                }
203            } else {
204                None
205            };
206
207            let (partner_steam_id, partner_name) = partner_data.unwrap_or_default();
208
209            let player_avatar = el.select(sel_player_avatar()).next();
210            let avatar_url = player_avatar.and_then(|a| a.select(sel_img()).next()).and_then(|i| i.value().attr("src")).unwrap_or("");
211            let avatar_hash = if let Some(pos) = avatar_url.rfind('/') {
212                let filename = &avatar_url[pos + 1..];
213                if let Some(dot_pos) = filename.find('.') {
214                    filename[..dot_pos].to_string()
215                } else {
216                    filename.to_string()
217                }
218            } else {
219                String::new()
220            };
221
222            let link = player_avatar.and_then(|a| a.select(sel_a()).next()).and_then(|l| l.value().attr("href")).unwrap_or("").to_string();
223            let header = el.select(sel_tradeoffer_header()).next().map(|h| h.text().collect::<String>().trim().to_string()).unwrap_or_default();
224            let active = el.select(sel_items_ctn()).next().map(|c| c.value().has_class("active", scraper::CaseSensitivity::AsciiCaseInsensitive)).unwrap_or(false);
225
226            let primary_items_ctn = el.select(sel_primary_items()).next();
227            let secondary_items_ctn = el.select(sel_secondary_items()).next();
228
229            let primary_steam_id = primary_items_ctn.and_then(|c| c.select(sel_avatar_link()).next()).and_then(|a| a.value().attr("data-miniprofile")).and_then(|m| m.parse::<u32>().ok()).map(SteamID::from_individual_account_id);
230
231            let secondary_steam_id = secondary_items_ctn.and_then(|c| c.select(sel_avatar_link()).next()).and_then(|a| a.value().attr("data-miniprofile")).and_then(|m| m.parse::<u32>().ok()).map(SteamID::from_individual_account_id);
232
233            let parse_items = |ctn: Option<scraper::ElementRef>| {
234                let mut items = Vec::new();
235                if let Some(ctn) = ctn {
236                    for item_el in ctn.select(sel_trade_item()) {
237                        let economy_item = item_el.value().attr("data-economy-item").unwrap_or("").to_string();
238                        let img = item_el.select(sel_img()).next().and_then(|i| i.value().attr("src")).unwrap_or("").to_string();
239                        // Extract high-res image from srcset (2x variant)
240                        let img_hi = item_el
241                            .select(sel_img())
242                            .next()
243                            .and_then(|i| i.value().attr("srcset"))
244                            .and_then(|srcset| {
245                                srcset.split(',').find_map(|entry| {
246                                    let entry = entry.trim();
247                                    if entry.ends_with("2x") {
248                                        Some(entry.trim_end_matches("2x").trim().to_string())
249                                    } else {
250                                        None
251                                    }
252                                })
253                            })
254                            .unwrap_or_default();
255                        let missing = item_el.value().has_class("missing", scraper::CaseSensitivity::AsciiCaseInsensitive);
256                        items.push(TradeOfferItem { economy_item, img, img_hi, missing });
257                    }
258                }
259                items
260            };
261
262            // Parse banner text and status
263            let banner_el = el.select(sel_items_banner()).next();
264            let banner_text = banner_el.map(|b| b.text().collect::<String>().trim().to_string()).unwrap_or_default();
265            let status = if active {
266                TradeOfferStatus::Active
267            } else if banner_el.map(|b| b.value().has_class("accepted", scraper::CaseSensitivity::AsciiCaseInsensitive)).unwrap_or(false) {
268                TradeOfferStatus::Accepted
269            } else if banner_text.contains("Unavailable") || banner_text.contains("unavailable") {
270                TradeOfferStatus::Unavailable
271            } else if banner_text.contains("Counter") || banner_text.contains("counter") {
272                TradeOfferStatus::Countered
273            } else {
274                TradeOfferStatus::Inactive
275            };
276
277            let banner_timestamp = parse_steam_banner_timestamp(&banner_text);
278
279            trade_offers.push(TradeOffer {
280                tradeofferid,
281                partner: TradeOfferPartner { steamid: partner_steam_id, name: partner_name, avatar_hash, link, header },
282                active,
283                primary: TradeOfferItems { steamid: primary_steam_id, items: parse_items(primary_items_ctn) },
284                secondary: TradeOfferItems { steamid: secondary_steam_id, items: parse_items(secondary_items_ctn) },
285                banner_text,
286                banner_timestamp,
287                status,
288            });
289        }
290
291        TradeOffersResponse { incoming_offers, sent_offers, trade_hold_count, trade_offers }
292    }
293
294    /// Sends a new trade offer to a partner using their trade URL.
295    ///
296    /// # Arguments
297    ///
298    /// * `trade_url` - The full trade offer URL of the partner.
299    /// * `my_assets` - A list of [`TradeOfferAsset`] from your inventory to
300    ///   give.
301    /// * `their_assets` - A list of [`TradeOfferAsset`] from their inventory to
302    ///   receive.
303    /// * `message` - An optional message to include with the trade offer.
304    #[steam_endpoint(POST, host = Community, path = "/tradeoffer/new/send", kind = Write)]
305    pub async fn send_trade_offer(&self, trade_url: &str, my_assets: Vec<TradeOfferAsset>, their_assets: Vec<TradeOfferAsset>, message: &str) -> Result<TradeOfferResult, SteamUserError> {
306        let parsed = self.parse_trade_url(trade_url).ok_or_else(|| SteamUserError::Other("Invalid trade URL".into()))?;
307
308        let json_tradeoffer = json!({
309            "newversion": true,
310            "version": 3,
311            "me": {
312                "assets": my_assets,
313                "currency": [],
314                "ready": false,
315            },
316            "them": {
317                "assets": their_assets,
318                "currency": [],
319                "ready": false,
320            }
321        });
322
323        let mut form = Vec::new();
324        form.push(("serverid", "1".to_string()));
325        form.push(("partner", parsed.steam_id.steam_id64().to_string()));
326        form.push(("tradeoffermessage", message.to_string()));
327        form.push(("json_tradeoffer", json_tradeoffer.to_string()));
328        form.push(("captcha", "".to_string()));
329        form.push(("trade_offer_create_params", json!({ "trade_offer_access_token": parsed.token }).to_string()));
330
331        let response = self.post_path("/tradeoffer/new/send").header(reqwest::header::REFERER, trade_url).form(&form).send().await?.text().await?;
332
333        // Check for strError first — Steam returns this on failure instead of
334        // tradeofferid
335        let raw: serde_json::Value = serde_json::from_str(&response).map_err(|e| SteamUserError::Other(format!("Failed to parse response: {}", e)))?;
336        if let Some(str_error) = raw.get("strError").and_then(|v| v.as_str()) {
337            // Strip HTML tags for a clean error message
338            let clean = str_error.replace("<br>", "\n").replace("<br/>", "\n");
339            let clean = re_html_tags().replace_all(&clean, "").to_string();
340            return Err(SteamUserError::Other(clean.trim().to_string()));
341        }
342
343        let result: TradeOfferResult = serde_json::from_value(raw).map_err(|e| SteamUserError::Other(format!("Failed to parse response: {}", e)))?;
344        Ok(result)
345    }
346
347    /// Accepts an incoming trade offer.
348    ///
349    /// # Arguments
350    ///
351    /// * `trade_offer_id` - The unique ID of the trade offer to accept.
352    /// * `partner_steam_id` - Optional Steam ID of the partner. If not
353    ///   provided, it will be scraped from the offer page.
354    #[steam_endpoint(POST, host = Community, path = "/tradeoffer/{trade_offer_id}/accept", kind = Write)]
355    pub async fn accept_trade_offer(&self, trade_offer_id: u64, partner_steam_id: Option<String>) -> Result<String, SteamUserError> {
356        let partner_id = if let Some(id) = partner_steam_id {
357            id
358        } else {
359            let page = self.get_path(format!("/tradeoffer/{}", trade_offer_id)).send().await?.text().await?;
360            if let Some(start) = page.find("var g_ulTradePartnerSteamID = '") {
361                let rest = &page[start + "var g_ulTradePartnerSteamID = '".len()..];
362                if let Some(end) = rest.find("';") {
363                    rest[..end].to_string()
364                } else {
365                    return Err(SteamUserError::MalformedResponse("Failed to extract partner Steam ID".into()));
366                }
367            } else {
368                return Err(SteamUserError::MalformedResponse("Failed to extract partner Steam ID".into()));
369            }
370        };
371
372        let form = vec![("serverid", "1".to_string()), ("tradeofferid", trade_offer_id.to_string()), ("partner", partner_id), ("captcha", String::new())];
373
374        let referer = format!("https://steamcommunity.com/tradeoffer/{}/", trade_offer_id);
375        let response = self.post_path(format!("/tradeoffer/{}/accept", trade_offer_id)).header(reqwest::header::REFERER, &referer).form(&form).send().await?.text().await?;
376
377        let data: serde_json::Value = serde_json::from_str(&response).map_err(|e| SteamUserError::Other(format!("Failed to parse response: {}", e)))?;
378        if let Some(trade_id) = data.get("tradeid").and_then(|v| v.as_str()) {
379            Ok(trade_id.to_string())
380        } else {
381            Err(SteamUserError::Other(format!("Unexpected response: {}", response)))
382        }
383    }
384
385    /// Declines or cancels a Steam trade offer.
386    ///
387    /// # Arguments
388    ///
389    /// * `trade_offer_id` - The unique ID of the trade offer to decline.
390    #[steam_endpoint(POST, host = Community, path = "/tradeoffer/{trade_offer_id}/decline", kind = Write)]
391    pub async fn decline_trade_offer(&self, trade_offer_id: u64) -> Result<(), SteamUserError> {
392        let referer = format!("https://steamcommunity.com/tradeoffer/{}/", trade_offer_id);
393        let response = self.post_path(format!("/tradeoffer/{}/decline", trade_offer_id)).header(reqwest::header::REFERER, &referer).form(&([] as [(&str, &str); 0])).send().await?.text().await?;
394
395        let data: serde_json::Value = serde_json::from_str(&response).map_err(|e| SteamUserError::Other(format!("Failed to parse response: {}", e)))?;
396        let success = data.get("success").and_then(|v| v.as_bool().or_else(|| v.as_i64().map(|i| i == 1))).unwrap_or(false);
397
398        if success || data.get("tradeofferid").is_some() || data.get("tradeoffer_id").is_some() {
399            Ok(())
400        } else {
401            Err(SteamUserError::Other(format!("Failed to decline trade offer: {}", response)))
402        }
403    }
404
405    /// Cancels (retracts) one of *our own* **outgoing** trade offers.
406    ///
407    /// Steam's `/decline` endpoint is for the **recipient** of an *incoming*
408    /// offer; the **sender** retracts an *outgoing* offer via `/cancel`. Calling
409    /// `decline_trade_offer` on an offer we sent returns HTTP 422 `{"success":42}`
410    /// and does nothing — use this for outgoing offers.
411    #[steam_endpoint(POST, host = Community, path = "/tradeoffer/{trade_offer_id}/cancel", kind = Write)]
412    pub async fn cancel_trade_offer(&self, trade_offer_id: u64) -> Result<(), SteamUserError> {
413        let referer = format!("https://steamcommunity.com/tradeoffer/{}/", trade_offer_id);
414        let response = self.post_path(format!("/tradeoffer/{}/cancel", trade_offer_id)).header(reqwest::header::REFERER, &referer).form(&([] as [(&str, &str); 0])).send().await?.text().await?;
415
416        let data: serde_json::Value = serde_json::from_str(&response).map_err(|e| SteamUserError::Other(format!("Failed to parse response: {}", e)))?;
417        let success = data.get("success").and_then(|v| v.as_bool().or_else(|| v.as_i64().map(|i| i == 1))).unwrap_or(false);
418
419        if success || data.get("tradeofferid").is_some() || data.get("tradeoffer_id").is_some() {
420            Ok(())
421        } else {
422            Err(SteamUserError::Other(format!("Failed to cancel trade offer: {}", response)))
423        }
424    }
425
426    /// Parses a Steam trade offer URL and extracts key partner information.
427    pub fn parse_trade_url(&self, trade_url: &str) -> Option<ParsedTradeURL> {
428        let url = url::Url::parse(trade_url).ok()?;
429        let partner = url.query_pairs().find(|(k, _)| k == "partner")?.1.to_string();
430        let token = url.query_pairs().find(|(k, _)| k == "token").map(|(_, v)| v.to_string());
431
432        let account_id = partner.parse::<u32>().ok()?;
433        let steam_id = SteamID::from_individual_account_id(account_id);
434
435        Some(ParsedTradeURL { account_id: partner, steam_id, token })
436    }
437}
438
439/// Parse a Steam banner timestamp string like "Trade Accepted 8 Mar, 2026 @
440/// 3:46am" and return a UTC Unix timestamp (seconds).
441///
442/// Steam renders these timestamps server-side in the timezone given by the
443/// `timezoneOffset` cookie; the session pins it to `0,0`
444/// ([`crate::session::TIMEZONE_OFFSET_COOKIE`]), so the banner text is UTC.
445fn parse_steam_banner_timestamp(banner_text: &str) -> Option<i64> {
446    // Look for the `@` separator — format is: "<prefix> <day> <Mon>, <year> @
447    // <hour>:<min><am/pm>"
448    let at_pos = banner_text.find('@');
449    if at_pos.is_none() {
450        tracing::debug!("[TradeOffer] No '@' in banner text: {:?}", banner_text);
451        return None;
452    }
453    let at_pos = at_pos?;
454    let time_part = banner_text[at_pos + 1..].trim(); // "5:20am" or "11:20pm"
455    let date_part = banner_text[..at_pos].trim(); // "Trade Accepted 15 Mar, 2026"
456
457    // Extract the date portion: find the first digit to get "<day> <Mon>, <year>"
458    let date_start = date_part.find(|c: char| c.is_ascii_digit())?;
459    let date_str = date_part[date_start..].trim(); // "15 Mar, 2026"
460
461    // Parse time: "5:20am" -> (hour, minute)
462    // Handle possible trailing text after am/pm (e.g., from extra banner content)
463    let time_token = time_part.split_whitespace().next().unwrap_or(time_part);
464    let am_pm = if time_token.ends_with("am") {
465        "AM"
466    } else if time_token.ends_with("pm") {
467        "PM"
468    } else {
469        tracing::debug!("[TradeOffer] Cannot determine AM/PM from time_token: {:?} (full time_part: {:?})", time_token, time_part);
470        return None;
471    };
472    let time_digits = time_token.trim_end_matches(|c: char| c.is_ascii_alphabetic());
473    let mut time_split = time_digits.split(':');
474    let mut hour: u32 = time_split.next()?.trim().parse().ok()?;
475    let minute: u32 = time_split.next()?.trim().parse().ok()?;
476
477    // Convert 12-hour to 24-hour
478    if am_pm == "AM" && hour == 12 {
479        hour = 0;
480    }
481    if am_pm == "PM" && hour != 12 {
482        hour += 12;
483    }
484
485    // Parse date: "15 Mar, 2026"
486    let date_str = date_str.replace(',', "");
487    let mut parts = date_str.split_whitespace();
488    let day: u32 = parts.next()?.parse().ok()?;
489    let month_str = parts.next()?;
490    let year: i32 = parts.next()?.parse().ok()?;
491
492    let month = match month_str {
493        "Jan" => 1,
494        "Feb" => 2,
495        "Mar" => 3,
496        "Apr" => 4,
497        "May" => 5,
498        "Jun" => 6,
499        "Jul" => 7,
500        "Aug" => 8,
501        "Sep" => 9,
502        "Oct" => 10,
503        "Nov" => 11,
504        "Dec" => 12,
505        _ => {
506            tracing::debug!("[TradeOffer] Unknown month: {:?}", month_str);
507            return None;
508        }
509    };
510
511    // The session's `timezoneOffset=0,0` cookie makes Steam render this in UTC.
512    let naive = chrono::NaiveDate::from_ymd_opt(year, month, day)?.and_hms_opt(hour, minute, 0)?;
513    let ts = naive.and_utc().timestamp();
514    tracing::debug!("[TradeOffer] Parsed banner timestamp: {:?} -> UTC {}", banner_text, ts);
515    Some(ts)
516}
517
518/// Decode JavaScript unicode escape sequences (e.g., `\u01b0\u01a1ng` →
519/// `ương`).
520fn decode_js_unicode_escapes(s: &str) -> String {
521    let mut result = String::with_capacity(s.len());
522    let mut chars = s.chars().peekable();
523    while let Some(ch) = chars.next() {
524        if ch == '\\' && chars.peek() == Some(&'u') {
525            chars.next(); // consume 'u'
526            let hex: String = chars.by_ref().take(4).collect();
527            if hex.len() == 4 {
528                if let Ok(code) = u32::from_str_radix(&hex, 16) {
529                    // Handle surrogate pairs (\uD800-\uDFFF)
530                    if (0xD800..=0xDBFF).contains(&code) {
531                        // High surrogate — look for low surrogate
532                        let mut low_chars = chars.clone();
533                        if low_chars.next() == Some('\\') && low_chars.next() == Some('u') {
534                            let low_hex: String = low_chars.by_ref().take(4).collect();
535                            if let Ok(low_code) = u32::from_str_radix(&low_hex, 16) {
536                                if (0xDC00..=0xDFFF).contains(&low_code) {
537                                    let cp = 0x10000 + ((code - 0xD800) << 10) + (low_code - 0xDC00);
538                                    if let Some(c) = char::from_u32(cp) {
539                                        result.push(c);
540                                        // Advance the real iterator past the low surrogate
541                                        for _ in 0..6 {
542                                            chars.next();
543                                        }
544                                        continue;
545                                    }
546                                }
547                            }
548                        }
549                        // Fallback: emit replacement char if surrogate pair is broken
550                        result.push(char::REPLACEMENT_CHARACTER);
551                    } else if let Some(c) = char::from_u32(code) {
552                        result.push(c);
553                    } else {
554                        result.push(char::REPLACEMENT_CHARACTER);
555                    }
556                } else {
557                    result.push_str("\\u");
558                    result.push_str(&hex);
559                }
560            } else {
561                result.push_str("\\u");
562                result.push_str(&hex);
563            }
564        } else {
565            result.push(ch);
566        }
567    }
568    result
569}