Spaces:
Sleeping

File size: 3,935 Bytes
270511d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time
import random

from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout
from config import API_KEYWORD, USER_AGENTS

# ══════════════════════════════════════════════════════════════════════════════
# FETCHER
# ══════════════════════════════════════════════════════════════════════════════

def convert_to_steamdt_url(steam_url: str) -> str:
    """Convert a Steam community inventory URL to steamdt.com search format."""
    if "steamcommunity.com" in steam_url:
        return f"https://www.steamdt.com/en/inventory/inventory?search={steam_url}"
    return steam_url


def _apply_stealth(page) -> None:
    """Inject stealth scripts to reduce bot-detection fingerprinting."""
    page.add_init_script("""
        Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
        Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
        Object.defineProperty(navigator, 'plugins',   { get: () => [1, 2, 3, 4] });
    """)


def fetch_inventory_from_site(url: str, retries: int = 3) -> dict | None:
    """
    Launch a headless Chromium browser, navigate to *url*, and intercept
    the first JSON response whose URL contains API_KEYWORD.

    Returns the parsed JSON dict on success, or None after *retries* failures.
    """
    for attempt in range(retries):
        try:
            with sync_playwright() as p:
                browser = p.chromium.launch(
                    headless=True,
                    args=[
                        "--disable-blink-features=AutomationControlled",
                        "--disable-dev-shm-usage",
                        "--no-sandbox",
                    ],
                )
                context = browser.new_context(
                    user_agent=random.choice(USER_AGENTS),
                    viewport={"width": 1920, "height": 1080},
                    locale="en-US",
                )
                page = context.new_page()
                _apply_stealth(page)

                # Speed up loading by blocking media assets
                page.route(
                    "**/*.{png,jpg,jpeg,gif,svg,webp,woff,woff2}",
                    lambda route: route.abort(),
                )

                captured_data = None

                def handle_response(response):
                    nonlocal captured_data
                    if API_KEYWORD in response.url and response.request.method != "OPTIONS":
                        try:
                            if response.status == 200:
                                captured_data = response.json()
                        except Exception:
                            pass

                page.on("response", handle_response)

                print(f"[{attempt + 1}/{retries}] Opening: {url}")
                page.goto(url, wait_until="domcontentloaded", timeout=60_000)

                page.mouse.move(random.randint(200, 900), random.randint(200, 700))
                page.evaluate("window.scrollTo(0, document.body.scrollHeight)")

                for _ in range(30):
                    if captured_data is not None:
                        break
                    page.wait_for_timeout(500)

                browser.close()

                if not captured_data:
                    raise RuntimeError("API response not received in time.")

                return captured_data

        except PlaywrightTimeout:
            print(f"  Timeout on attempt {attempt + 1}")
        except Exception as exc:
            print(f"  Error on attempt {attempt + 1}: {exc}")

        time.sleep(2)

    return None