humble-bundle-keys 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """Humble Bundle key extractor.
2
+
3
+ Extract and (optionally) reveal your Humble Bundle game keys to a CSV.
4
+ """
5
+
6
+ __version__ = "0.4.0"
@@ -0,0 +1,6 @@
1
+ """Entry point for `python -m humble_bundle_keys`."""
2
+
3
+ from humble_bundle_keys.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,101 @@
1
+ """POST through the actual browser via ``page.evaluate(fetch)``.
2
+
3
+ Why this exists
4
+ ---------------
5
+ Humblebundle.com sits behind Cloudflare. Cloudflare fingerprints the
6
+ HTTP/2 + TLS handshake of incoming requests, and Playwright's
7
+ ``APIRequestContext`` (``context.request.post(...)``) uses a stack that
8
+ doesn't match a real Chrome — Cloudflare flags it as bot traffic and
9
+ returns a 403 challenge page for state-changing endpoints like
10
+ ``/humbler/redeemkey`` and ``/humbler/choosecontent``.
11
+
12
+ GETs (e.g. ``/api/v1/orders``) get through fine; only POSTs are
13
+ challenged. The fix is to route POSTs through the actual browser. The
14
+ caller keeps a ``Page`` navigated to humblebundle.com, we feed the
15
+ request to ``page.evaluate("fetch(...)")``, and Cloudflare sees a real
16
+ Chrome request originating from the right origin with full session
17
+ cookies attached — exactly what the SPA itself does, exactly the path
18
+ our 2026-05-04 diagnose capture confirmed works end-to-end.
19
+
20
+ We deliberately do NOT use ``credentials: "include"`` — same-origin
21
+ fetches send cookies automatically, and ``include`` triggers stricter
22
+ CORS / SameSite handling we don't need.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from dataclasses import dataclass
28
+ from typing import Any
29
+
30
+ from playwright.sync_api import Page
31
+
32
+
33
+ @dataclass
34
+ class BrowserFetchResponse:
35
+ status: int
36
+ body: Any
37
+ raw_text: str = ""
38
+
39
+
40
+ # JavaScript snippet evaluated inside the page. Single source of truth so
41
+ # tests can assert on the shape we send.
42
+ FETCH_SCRIPT = """
43
+ async ({ url, method, body, headers }) => {
44
+ // Same-origin POST. Cookies attach automatically; the include flag is
45
+ // intentionally omitted to keep CORS/SameSite handling permissive.
46
+ const resp = await fetch(url, {
47
+ method: method || 'POST',
48
+ headers: headers || {},
49
+ body: body,
50
+ });
51
+ const text = await resp.text();
52
+ let parsed = null;
53
+ try { parsed = JSON.parse(text); } catch (e) { /* leave parsed = null */ }
54
+ return {
55
+ status: resp.status,
56
+ raw_text: text,
57
+ body: parsed,
58
+ };
59
+ }
60
+ """.strip()
61
+
62
+
63
+ def post_form_in_browser(
64
+ page: Page,
65
+ url: str,
66
+ body: str,
67
+ *,
68
+ referer: str | None = None,
69
+ extra_headers: dict[str, str] | None = None,
70
+ timeout_ms: int = 20_000,
71
+ ) -> BrowserFetchResponse:
72
+ """POST a form-encoded body via fetch() inside ``page``'s real Chrome.
73
+
74
+ The ``page`` must already be on a humblebundle.com URL so that ``fetch``
75
+ treats the request as same-origin (cookies attach automatically). The
76
+ caller is responsible for keeping the page navigated.
77
+ """
78
+ headers: dict[str, str] = {
79
+ "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
80
+ "accept": "application/json, text/javascript, */*; q=0.01",
81
+ "x-requested-with": "XMLHttpRequest",
82
+ }
83
+ if referer:
84
+ # The browser sets Referer automatically based on the page's URL,
85
+ # but we can reinforce it via the meta-tag-equivalent header where
86
+ # the spec allows. (Most browsers will silently ignore an explicit
87
+ # Referer header set via fetch, falling back to the page's origin.)
88
+ headers["referer"] = referer
89
+ if extra_headers:
90
+ headers.update(extra_headers)
91
+
92
+ page.set_default_timeout(timeout_ms)
93
+ raw = page.evaluate(
94
+ FETCH_SCRIPT,
95
+ {"url": url, "method": "POST", "body": body, "headers": headers},
96
+ )
97
+ return BrowserFetchResponse(
98
+ status=int(raw.get("status") or 0),
99
+ body=raw.get("body"),
100
+ raw_text=raw.get("raw_text") or "",
101
+ )
@@ -0,0 +1,125 @@
1
+ """On-disk cache for /api/v1/order/<gamekey> responses.
2
+
3
+ Order data only changes when:
4
+ * the user buys a new bundle / subscription month (new gamekey appears)
5
+ * a key is revealed (``redeemed_key_val`` populates on a tpk)
6
+ * a Choice game is claimed (a tpk gets added to ``tpkd_dict.all_tpks``)
7
+
8
+ So caching individual order JSON for a few hours dramatically cuts run time
9
+ without staleness risk for the read-only metadata. The list of gamekeys
10
+ (``/api/v1/user/order``) is still fetched fresh every run — it's tiny and
11
+ shows new orders immediately.
12
+
13
+ Cache invalidation:
14
+ * TTL (default 6h) — silently re-fetch after expiry.
15
+ * Explicit invalidation on successful state-changing operations (e.g. after
16
+ ``_reveal`` returns a key, the caller should call ``invalidate(gamekey)``
17
+ so the next run picks up the new ``redeemed_key_val``).
18
+ * ``--no-cache`` flag bypasses entirely.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import logging
25
+ import time
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ DEFAULT_CACHE_DIR = Path.home() / ".humble-bundle-keys" / "orders-cache"
30
+ DEFAULT_TTL_S = 6 * 60 * 60 # 6 hours
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+
35
+ class OrderCache:
36
+ """Tiny single-process JSON cache for order detail responses."""
37
+
38
+ def __init__(
39
+ self,
40
+ cache_dir: Path = DEFAULT_CACHE_DIR,
41
+ ttl_s: int = DEFAULT_TTL_S,
42
+ enabled: bool = True,
43
+ ):
44
+ self.cache_dir = cache_dir
45
+ self.ttl_s = ttl_s
46
+ self.enabled = enabled
47
+ self._hits = 0
48
+ self._misses = 0
49
+ if enabled:
50
+ try:
51
+ cache_dir.mkdir(parents=True, exist_ok=True)
52
+ except Exception as e:
53
+ log.warning("Could not create cache dir %s: %s", cache_dir, e)
54
+ self.enabled = False
55
+
56
+ @property
57
+ def hits(self) -> int:
58
+ return self._hits
59
+
60
+ @property
61
+ def misses(self) -> int:
62
+ return self._misses
63
+
64
+ def _path(self, gamekey: str) -> Path:
65
+ # Sanitise to a safe filename. Gamekeys are alnum so this is mostly
66
+ # defensive against future shape changes.
67
+ safe = "".join(c if c.isalnum() else "_" for c in gamekey)
68
+ return self.cache_dir / f"{safe}.json"
69
+
70
+ def get(self, gamekey: str) -> dict[str, Any] | None:
71
+ if not self.enabled:
72
+ return None
73
+ path = self._path(gamekey)
74
+ if not path.exists():
75
+ self._misses += 1
76
+ return None
77
+ try:
78
+ age = time.time() - path.stat().st_mtime
79
+ except Exception:
80
+ self._misses += 1
81
+ return None
82
+ if age > self.ttl_s:
83
+ self._misses += 1
84
+ return None
85
+ try:
86
+ data = json.loads(path.read_text(encoding="utf-8"))
87
+ except Exception as e:
88
+ log.debug("Cache file %s unreadable (%s); treating as miss", path, e)
89
+ self._misses += 1
90
+ return None
91
+ self._hits += 1
92
+ return data
93
+
94
+ def put(self, gamekey: str, order: dict[str, Any]) -> None:
95
+ if not self.enabled:
96
+ return
97
+ path = self._path(gamekey)
98
+ try:
99
+ path.write_text(json.dumps(order), encoding="utf-8")
100
+ except Exception as e:
101
+ log.debug("Failed to write cache %s: %s", path, e)
102
+
103
+ def invalidate(self, gamekey: str) -> None:
104
+ """Drop a cached order — call after any state-changing operation."""
105
+ if not self.enabled:
106
+ return
107
+ path = self._path(gamekey)
108
+ try:
109
+ if path.exists():
110
+ path.unlink()
111
+ except Exception as e:
112
+ log.debug("Failed to invalidate cache %s: %s", path, e)
113
+
114
+ def clear_all(self) -> int:
115
+ """Remove every cached order. Returns count removed."""
116
+ if not self.enabled or not self.cache_dir.exists():
117
+ return 0
118
+ n = 0
119
+ for p in self.cache_dir.glob("*.json"):
120
+ try:
121
+ p.unlink()
122
+ n += 1
123
+ except Exception:
124
+ pass
125
+ return n
@@ -0,0 +1,432 @@
1
+ """JSON API scraper for humblebundle.com.
2
+
3
+ Humble has no public API, but their frontend SPA talks to a private JSON API
4
+ on the same domain that has been stable enough for community tools to use it
5
+ for years. This module hits those endpoints with the same authenticated
6
+ session that the DOM scraper uses.
7
+
8
+ Endpoints (all undocumented; subject to change without notice)
9
+ --------------------------------------------------------------
10
+ * ``GET /api/v1/user/order`` — list of order ``gamekey``s.
11
+ * ``GET /api/v1/order/<gamekey>?all_tpkds=true``
12
+ — full order detail incl. keys.
13
+ * ``POST /humbler/redeemkey`` — reveals + claims one key.
14
+
15
+ Fields we read from each TPK entry (best-effort; see ``_extract_tpk``)
16
+ ---------------------------------------------------------------------
17
+ * ``human_name`` — game title.
18
+ * ``key_type`` / ``key_type_human_name`` — platform.
19
+ * ``redeemed_key_val`` — actual key, or null if not yet revealed.
20
+ * ``is_expired``, ``expiry_date`` — redemption deadline.
21
+ * ``machine_name`` — used as the ``keytype`` form field when
22
+ POSTing to /humbler/redeemkey.
23
+ * ``key_index`` — used as the ``keyindex`` form field.
24
+ * ``gamekey`` — used as the ``key`` form field.
25
+
26
+ If the API returns a shape we don't recognise, we raise ``ApiUnsupported``
27
+ which the orchestrator uses to fall back to DOM scraping.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import logging
33
+ import time
34
+ from dataclasses import dataclass
35
+ from typing import Any
36
+ from urllib.parse import urlencode
37
+
38
+ from playwright.sync_api import APIRequestContext, BrowserContext, Page
39
+
40
+ from humble_bundle_keys._browser_fetch import post_form_in_browser
41
+ from humble_bundle_keys._orders_cache import OrderCache
42
+ from humble_bundle_keys.models import ExtractStats, GameKey
43
+ from humble_bundle_keys.scraper import PLATFORMS # reuse the platform normalisation
44
+
45
+ # Page we keep open as a "browser context anchor" so POSTs can route through
46
+ # the real Chrome stack (and bypass Cloudflare's bot detection on Playwright's
47
+ # raw APIRequestContext). Any humblebundle.com URL works — /home/keys is the
48
+ # obvious choice since we know it loads cleanly.
49
+ ANCHOR_URL = "https://www.humblebundle.com/home/keys"
50
+
51
+ ORDERS_LIST_URL = "https://www.humblebundle.com/api/v1/user/order"
52
+ ORDER_DETAIL_URL = "https://www.humblebundle.com/api/v1/order/{gamekey}?all_tpkds=true"
53
+ REDEEM_URL = "https://www.humblebundle.com/humbler/redeemkey"
54
+
55
+ log = logging.getLogger(__name__)
56
+
57
+
58
+ class ApiUnsupported(RuntimeError):
59
+ """Raised when the JSON API returns a shape we can't parse.
60
+
61
+ The orchestrator catches this and falls back to DOM scraping.
62
+ """
63
+
64
+
65
+ class ApiError(RuntimeError):
66
+ """Raised on an authoritative API failure (non-2xx, missing auth)."""
67
+
68
+
69
+ @dataclass
70
+ class ApiOptions:
71
+ reveal_keys: bool = True
72
+ dry_run: bool = False
73
+ polite_delay_ms: int = 800
74
+ request_timeout_ms: int = 20_000
75
+ # Cache control. When ``cache`` is None, no caching is done.
76
+ cache: OrderCache | None = None
77
+
78
+
79
+ def _normalise_platform(s: str | None) -> str:
80
+ if not s:
81
+ return ""
82
+ s = s.strip().lower()
83
+ return PLATFORMS.get(s, s if s.isalpha() and len(s) <= 16 else "")
84
+
85
+
86
+ def _expiry_to_deadline(tpk: dict[str, Any]) -> str:
87
+ """Convert API expiry fields to a human-readable deadline string."""
88
+ if tpk.get("is_expired"):
89
+ return "Expired"
90
+ expiry = tpk.get("expiry_date") or tpk.get("expires") or ""
91
+ if isinstance(expiry, str) and expiry:
92
+ return f"Must be redeemed by {expiry}"
93
+ return ""
94
+
95
+
96
+ def _extract_tpk(tpk: dict[str, Any], order: dict[str, Any]) -> GameKey:
97
+ """Build a GameKey from one entry in tpkd_dict.all_tpks[]."""
98
+ title = (
99
+ tpk.get("human_name")
100
+ or tpk.get("display_name")
101
+ or tpk.get("machine_name")
102
+ or "(unknown)"
103
+ )
104
+ platform = _normalise_platform(tpk.get("key_type") or tpk.get("key_type_human_name"))
105
+ key_val = tpk.get("redeemed_key_val") or ""
106
+ # Order metadata lives under ``order.product``, NOT at the root. The root
107
+ # has fields like gamekey, uid, created. Fall back to root for tolerance
108
+ # against API shape changes.
109
+ product = order.get("product") or {}
110
+ bundle_name = (
111
+ product.get("human_name")
112
+ or product.get("machine_name")
113
+ or order.get("human_name")
114
+ or order.get("machine_name")
115
+ or ""
116
+ )
117
+ deadline = _expiry_to_deadline(tpk)
118
+ gamekey = order.get("gamekey") or tpk.get("gamekey") or ""
119
+ humble_url = f"https://www.humblebundle.com/downloads?key={gamekey}" if gamekey else ""
120
+
121
+ # OS support — best effort. Humble doesn't have a clean per-tpk OS field,
122
+ # so we scan instructions_html for OS keywords. Don't bother trying to
123
+ # infer from steam_app_id presence etc. — we'd rather underreport than lie.
124
+ oses: list[str] = []
125
+ instructions = (tpk.get("instructions_html") or "").lower()
126
+ for needle, label in (("windows", "Windows"), ("mac", "macOS"), ("linux", "Linux")):
127
+ if needle in instructions:
128
+ oses.append(label)
129
+
130
+ return GameKey(
131
+ game_title=title,
132
+ platform=platform,
133
+ key=key_val,
134
+ bundle_name=bundle_name,
135
+ bundle_date="", # filled in by exporter from bundle_name
136
+ redemption_deadline=deadline,
137
+ redeemed_on_humble=bool(key_val),
138
+ os_support=", ".join(oses),
139
+ humble_url=humble_url,
140
+ )
141
+
142
+
143
+ class ApiScraper:
144
+ """Scrape via the private JSON API.
145
+
146
+ Uses the same authenticated context the DOM scraper uses; no separate
147
+ auth flow needed. Cookies are shared.
148
+ """
149
+
150
+ def __init__(self, context: BrowserContext, options: ApiOptions):
151
+ self.context = context
152
+ self.options = options
153
+ self.request: APIRequestContext = context.request
154
+ self.stats = ExtractStats()
155
+ # Populated as we walk orders so callers (e.g. ChoiceClaimer) can
156
+ # reuse the data without re-fetching.
157
+ self.orders: list[dict[str, Any]] = []
158
+ # Anchor page used to route POSTs through real Chrome's HTTP stack —
159
+ # the only path Cloudflare doesn't 403. Created lazily on first reveal
160
+ # so dry-run / GET-only operation stays cheap.
161
+ self._anchor_page: Page | None = None
162
+
163
+ def _get_anchor_page(self) -> Page:
164
+ """Lazy-create / heal a Page navigated to humblebundle.com.
165
+
166
+ The anchor's only job is to be a real-Chrome request origin. If it
167
+ gets closed, navigates away (e.g. an auth-refresh redirect), or
168
+ ends up off-origin, recreate or re-navigate it. Otherwise the next
169
+ ``page.evaluate`` will throw "Execution context was destroyed".
170
+ """
171
+ page = self._anchor_page
172
+ if page is None or page.is_closed():
173
+ page = self.context.new_page()
174
+ page.goto(ANCHOR_URL, wait_until="domcontentloaded")
175
+ self._anchor_page = page
176
+ return page
177
+
178
+ try:
179
+ current = page.url or ""
180
+ except Exception:
181
+ current = ""
182
+ if "humblebundle.com" not in current:
183
+ try:
184
+ page.goto(ANCHOR_URL, wait_until="domcontentloaded")
185
+ except Exception:
186
+ # Fall back to a fresh page
187
+ try:
188
+ page.close()
189
+ except Exception:
190
+ pass
191
+ page = self.context.new_page()
192
+ page.goto(ANCHOR_URL, wait_until="domcontentloaded")
193
+ self._anchor_page = page
194
+ return page
195
+
196
+ def close_anchor_page(self) -> None:
197
+ if self._anchor_page is not None and not self._anchor_page.is_closed():
198
+ try:
199
+ self._anchor_page.close()
200
+ except Exception:
201
+ pass
202
+ self._anchor_page = None
203
+
204
+ # ------------------------------------------------------------------
205
+ # Public entry point
206
+ # ------------------------------------------------------------------
207
+
208
+ def scrape(self) -> tuple[list[GameKey], ExtractStats]:
209
+ try:
210
+ gamekeys = self._list_gamekeys()
211
+ log.info("API: listing %d orders", len(gamekeys))
212
+ rows: list[GameKey] = []
213
+ for i, gk in enumerate(gamekeys, 1):
214
+ log.info("API: order %d/%d (%s)", i, len(gamekeys), gk[:6] + "…")
215
+ try:
216
+ order = self._get_order(gk)
217
+ except ApiError as e:
218
+ self.stats.errors.append(f"order {gk}: {e}")
219
+ continue
220
+
221
+ self.orders.append(order)
222
+ tpks = self._extract_tpks(order)
223
+ self.stats.bundles_processed += 1
224
+
225
+ for tpk in tpks:
226
+ game = _extract_tpk(tpk, order)
227
+ # Reveal if not already revealed.
228
+ if (
229
+ not game.key
230
+ and self.options.reveal_keys
231
+ and not self.options.dry_run
232
+ ):
233
+ revealed = self._reveal(tpk, order)
234
+ if revealed:
235
+ game.key = revealed
236
+ game.redeemed_on_humble = True
237
+ self.stats.keys_revealed += 1
238
+ time.sleep(self.options.polite_delay_ms / 1000.0)
239
+ elif game.key:
240
+ self.stats.keys_already_revealed += 1
241
+ rows.append(game)
242
+
243
+ self.stats.total_rows = len(rows)
244
+ return rows, self.stats
245
+ finally:
246
+ # Close the anchor page so we don't leak it. The caller still owns
247
+ # the BrowserContext lifecycle.
248
+ self.close_anchor_page()
249
+
250
+ # ------------------------------------------------------------------
251
+ # API calls
252
+ # ------------------------------------------------------------------
253
+
254
+ def _get_json(self, url: str) -> Any:
255
+ try:
256
+ resp = self.request.get(url, timeout=self.options.request_timeout_ms)
257
+ except Exception as e:
258
+ raise ApiError(f"GET {url} failed: {e}") from e
259
+ if resp.status == 401 or resp.status == 403:
260
+ raise ApiError(f"GET {url} returned {resp.status} — session not authenticated for API")
261
+ if resp.status >= 400:
262
+ raise ApiError(f"GET {url} returned {resp.status}")
263
+ try:
264
+ return resp.json()
265
+ except Exception as e:
266
+ raise ApiUnsupported(f"GET {url} returned non-JSON body: {e}") from e
267
+
268
+ def _list_gamekeys(self) -> list[str]:
269
+ body = self._get_json(ORDERS_LIST_URL)
270
+ # Expected: list of {"gamekey": "..."}
271
+ if not isinstance(body, list):
272
+ raise ApiUnsupported(
273
+ f"/api/v1/user/order returned {type(body).__name__}, expected list"
274
+ )
275
+ out = []
276
+ for item in body:
277
+ if isinstance(item, dict) and isinstance(item.get("gamekey"), str):
278
+ out.append(item["gamekey"])
279
+ elif isinstance(item, str):
280
+ out.append(item)
281
+ if not out and body:
282
+ raise ApiUnsupported(
283
+ "/api/v1/user/order returned items in an unrecognised shape; "
284
+ f"first item: {body[0]!r}"
285
+ )
286
+ return out
287
+
288
+ def _get_order(self, gamekey: str) -> dict[str, Any]:
289
+ cache = self.options.cache
290
+ if cache is not None:
291
+ cached = cache.get(gamekey)
292
+ if cached is not None:
293
+ return cached
294
+ body = self._get_json(ORDER_DETAIL_URL.format(gamekey=gamekey))
295
+ if not isinstance(body, dict):
296
+ raise ApiUnsupported(
297
+ f"/api/v1/order/{gamekey} returned {type(body).__name__}, expected dict"
298
+ )
299
+ if cache is not None:
300
+ cache.put(gamekey, body)
301
+ return body
302
+
303
+ def _extract_tpks(self, order: dict[str, Any]) -> list[dict[str, Any]]:
304
+ """Pull the list of key entries out of an order detail blob."""
305
+ tpkd = order.get("tpkd_dict")
306
+ if not isinstance(tpkd, dict):
307
+ return []
308
+ # Prefer all_tpks; fall back to chosen_tpks/primary_tpks if needed.
309
+ for k in ("all_tpks", "chosen_tpks", "primary_tpks"):
310
+ arr = tpkd.get(k)
311
+ if isinstance(arr, list) and arr:
312
+ return arr
313
+ return []
314
+
315
+ # ------------------------------------------------------------------
316
+ # Reveal + claim
317
+ # ------------------------------------------------------------------
318
+
319
+ def _csrf_token(self) -> str | None:
320
+ """Pull the CSRF token from the context's cookies."""
321
+ for c in self.context.cookies("https://www.humblebundle.com"):
322
+ if c.get("name") == "csrf_cookie":
323
+ return c.get("value")
324
+ return None
325
+
326
+ def _reveal(self, tpk: dict[str, Any], order: dict[str, Any]) -> str | None:
327
+ """POST to /humbler/redeemkey and return the revealed key string, or None."""
328
+ keytype = tpk.get("machine_name")
329
+ # Humble's order JSON uses ``keyindex`` (one word), not ``key_index``.
330
+ # We accept either to be defensive against future shape changes.
331
+ keyindex = tpk.get("keyindex")
332
+ if keyindex is None:
333
+ keyindex = tpk.get("key_index")
334
+ gamekey = order.get("gamekey")
335
+ if not (keytype and gamekey is not None and keyindex is not None):
336
+ log.debug("API: missing fields for reveal: keytype=%r keyindex=%r gamekey=%r",
337
+ keytype, keyindex, gamekey)
338
+ return None
339
+
340
+ form = urlencode(
341
+ [
342
+ ("keytype", str(keytype)),
343
+ ("key", str(gamekey)),
344
+ ("keyindex", str(keyindex)),
345
+ ]
346
+ )
347
+ # Route POST through the real browser to bypass Cloudflare's bot
348
+ # detection on Playwright's APIRequestContext. CSRF token (if any)
349
+ # is added as a header — same as the SPA does it.
350
+ extra_headers: dict[str, str] = {}
351
+ token = self._csrf_token()
352
+ if token:
353
+ extra_headers["CSRF-Prevention-Token"] = token
354
+
355
+ try:
356
+ page = self._get_anchor_page()
357
+ resp = post_form_in_browser(
358
+ page,
359
+ REDEEM_URL,
360
+ form,
361
+ referer="https://www.humblebundle.com/home/keys",
362
+ extra_headers=extra_headers,
363
+ timeout_ms=self.options.request_timeout_ms,
364
+ )
365
+ except Exception as e:
366
+ msg = f"reveal {tpk.get('human_name')!r}: {e}"
367
+ self.stats.errors.append(msg)
368
+ log.warning(msg)
369
+ return None
370
+
371
+ if resp.status >= 400:
372
+ detail = (resp.raw_text or "")[:200]
373
+ msg = (
374
+ f"reveal {tpk.get('human_name')!r}: "
375
+ f"status {resp.status} {detail!r}"
376
+ )
377
+ self.stats.errors.append(msg)
378
+ log.warning(msg)
379
+ return None
380
+
381
+ try:
382
+ log.debug("reveal %s status=%s", tpk.get("human_name"), resp.status)
383
+ except Exception:
384
+ pass
385
+
386
+ def _record_silent() -> None:
387
+ self.stats.keys_silent_no_response += 1
388
+ try:
389
+ product = order.get("product") or {}
390
+ self.stats.silent_no_response_tpks.append(
391
+ (
392
+ str(tpk.get("human_name") or "(unknown)"),
393
+ str(tpk.get("machine_name") or "(none)"),
394
+ str(product.get("machine_name") or order.get("machine_name") or "(none)"),
395
+ )
396
+ )
397
+ except Exception:
398
+ pass
399
+
400
+ body = resp.body
401
+ if body is None:
402
+ _record_silent()
403
+ return None
404
+
405
+ # Possible response shapes:
406
+ # {"key": "XXXXX-XXXXX-XXXXX"}
407
+ # {"redeemed_key_val": "XXXXX-XXXXX-XXXXX"}
408
+ # {"success": true, "key_val": "..."}
409
+ for candidate in ("key", "redeemed_key_val", "key_val"):
410
+ v = body.get(candidate) if isinstance(body, dict) else None
411
+ if isinstance(v, str) and v:
412
+ # Successful reveal — invalidate the order cache so future
413
+ # runs see the populated redeemed_key_val.
414
+ if self.options.cache is not None:
415
+ self.options.cache.invalidate(str(order.get("gamekey") or ""))
416
+ return v
417
+ # Some endpoints return success without echoing the key — fall back to
418
+ # re-fetching the order to get the now-populated redeemed_key_val.
419
+ try:
420
+ refreshed = self._get_order(str(order.get("gamekey")))
421
+ for tpk2 in self._extract_tpks(refreshed):
422
+ tpk2_idx = tpk2.get("keyindex", tpk2.get("key_index"))
423
+ if tpk2.get("machine_name") == keytype and tpk2_idx == keyindex:
424
+ val = tpk2.get("redeemed_key_val")
425
+ if isinstance(val, str) and val:
426
+ return val
427
+ except Exception:
428
+ pass
429
+ # Got a 2xx but couldn't extract a key — almost always means this is
430
+ # Humble Choice content that needs the two-step claim flow.
431
+ _record_silent()
432
+ return None