"""Cache short descriptions and metadata from the Steam Store API. One request per app (the public endpoint does not accept batches), so the script is resumable and rate-limited. Examples: python tools/fetch_details.py --limit 200 python tools/fetch_details.py --all --delay 1.6 python tools/fetch_details.py --stats """ import argparse import json import os import sys import time import urllib.error import urllib.parse import urllib.request from datetime import datetime, timezone for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(encoding="utf-8") except Exception: pass sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import db API = "https://store.steampowered.com/api/appdetails" def _fetch_once(appid, lang, cc, timeout=30): params = urllib.parse.urlencode({"appids": appid, "l": lang, "cc": cc}) req = urllib.request.Request(f"{API}?{params}", headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=timeout) as resp: payload = json.load(resp) entry = payload.get(str(appid)) or {} if not entry.get("success"): return None data = entry.get("data") or {} return { "short_description": data.get("short_description"), "about": data.get("about_the_game"), "header_image": data.get("header_image"), "developers": ", ".join(data.get("developers") or []), "publishers": ", ".join(data.get("publishers") or []), "release_date": (data.get("release_date") or {}).get("date"), "lang": lang, } def fetch_app_details_region(appid, lang, cc, timeout=30): """Single attempt in one store region (used by the recovery tool).""" return _fetch_once(appid, lang, cc, timeout=timeout) def fetch_app_details(appid, lang="russian", timeout=30): """Fetch store details, preferring the requested language. Some games are region/age-gated in the Russian store and answer ``success: false``; for those we retry in English before giving up. """ attempts = [(lang, "ru")] if lang != "english": attempts.append(("english", "us")) for attempt_lang, cc in attempts: details = _fetch_once(appid, attempt_lang, cc, timeout=timeout) if details and (details["short_description"] or details["about"]): return details return None def save_details(con, appid, details, status="ok", source_appid=None): now = datetime.now(timezone.utc).isoformat(timespec="seconds") if details is not None: if details.get("short_description"): details["short_description"] = details["short_description"].replace("\ufeff", "").strip() if details.get("about"): details["about"] = details["about"].replace("\ufeff", "").strip() if details is None: con.execute( """INSERT INTO game_details (appid, lang, fetched_at, status) VALUES (?, ?, ?, 'missing') ON CONFLICT(appid) DO UPDATE SET lang=excluded.lang, fetched_at=excluded.fetched_at, status='missing'""", (appid, "russian", now), ) db.refresh_search_game(con, appid) con.commit() return con.execute( """INSERT INTO game_details (appid, short_description, about, header_image, developers, publishers, release_date, lang, fetched_at, status, source_appid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(appid) DO UPDATE SET short_description=excluded.short_description, about=excluded.about, header_image=excluded.header_image, developers=excluded.developers, publishers=excluded.publishers, release_date=excluded.release_date, lang=excluded.lang, fetched_at=excluded.fetched_at, status=excluded.status, source_appid=excluded.source_appid""", (appid, details["short_description"], details["about"], details["header_image"], details["developers"], details["publishers"], details["release_date"], details["lang"], now, status, source_appid), ) db.refresh_search_game(con, appid) con.commit() def missing_appids(con, limit=None, unplayed_only=False, min_review=None): sql = """SELECT g.appid FROM games g LEFT JOIN game_details d ON d.appid = g.appid LEFT JOIN game_playtime p ON p.appid = g.appid WHERE LOWER(g.type) = 'game' AND (d.appid IS NULL OR d.status IS NULL) ORDER BY (COALESCE(p.minutes, 0) = 0) DESC, COALESCE(g.review_pct, 0) DESC, g.name""" rows = [r["appid"] for r in con.execute(sql)] if unplayed_only: rows = [a for a in rows if con.execute( "SELECT COALESCE(minutes, 0) FROM game_playtime WHERE appid = ?", (a,)).fetchone()[0] == 0] if min_review is not None: rows = [a for a in rows if (lambda r: r is None or r >= min_review)( con.execute("SELECT review_pct FROM games WHERE appid = ?", (a,)).fetchone()[0])] return rows[:limit] if limit else rows def main(): ap = argparse.ArgumentParser(description="Cache Steam Store details") ap.add_argument("--db", default=db.DEFAULT_DB) ap.add_argument("--limit", type=int) ap.add_argument("--all", action="store_true") ap.add_argument("--stats", action="store_true") ap.add_argument("--retry-missing", action="store_true", help="retry games marked missing") ap.add_argument("--unplayed-only", action="store_true") ap.add_argument("--min-review", type=int) ap.add_argument("--delay", type=float, default=1.4, help="seconds between requests") ap.add_argument("--lang", default="russian") args = ap.parse_args() con = db.connect(args.db) db.init(con) if args.stats: total = con.execute("SELECT COUNT(*) FROM games WHERE LOWER(type)='game'").fetchone()[0] done = con.execute("""SELECT COUNT(*) FROM game_details d JOIN games g ON g.appid=d.appid WHERE LOWER(g.type)='game' AND d.status='ok'""").fetchone()[0] missing = con.execute("""SELECT COUNT(*) FROM game_details d JOIN games g ON g.appid=d.appid WHERE LOWER(g.type)='game' AND d.status='missing'""").fetchone()[0] print(f"games: {total} | cached: {done} | missing: {missing} | left: {total - done - missing}") return if args.retry_missing: con.execute("DELETE FROM game_details WHERE status = 'missing'") con.commit() limit = None if args.all else (args.limit or 100) ids = missing_appids(con, limit, args.unplayed_only, args.min_review) print(f"To fetch: {len(ids)}") ok = miss = err = 0 consecutive_errors = 0 for i, appid in enumerate(ids, 1): try: details = fetch_app_details(appid, lang=args.lang) save_details(con, appid, details) if details is None: miss += 1 else: ok += 1 consecutive_errors = 0 except urllib.error.HTTPError as exc: err += 1 consecutive_errors += 1 if exc.code == 429: print(" rate limited, sleeping 60s") time.sleep(60) elif consecutive_errors >= 5: print(f" stopping after {consecutive_errors} consecutive HTTP errors ({exc.code})") break except Exception as exc: err += 1 print(f" {appid}: {exc}") if i % 10 == 0 or i == len(ids): print(f" {i}/{len(ids)} ok={ok} missing={miss} errors={err}") time.sleep(args.delay) print("Done.") if __name__ == "__main__": main()