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