Skip to main content

steam_user/services/
trade.rs

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