Files
SteamBase/tools/recover_missing.py
T
2026-11-06 04:58:38 +03:00

192 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Recover descriptions for delisted / region-locked games.
Fallbacks, in order:
1. explicit base-edition map (Dishonored RHCP -> Dishonored, ...)
2. exact normalized title match inside the library (regional -> base edition)
3. exact normalized title match in the Steam store search
4. the same appid requested from a different store region (CN/JP/KR)
Only exact title matches are accepted, so a similar-but-different game is
never used as the source.
python tools/recover_missing.py
python tools/recover_missing.py --dry-run --limit 20
"""
import argparse
import difflib
import html
import json
import os
import re
import sys
import time
import urllib.error
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
from fetch_details import fetch_app_details, fetch_app_details_region, save_details
STORE_SEARCH = "https://store.steampowered.com/api/storesearch/"
# Known regional / retail variants whose base edition has a store page.
BASE_MAP = {
217980: 205100, # Dishonored RHCP -> Dishonored
22490: 22380, # Fallout: New Vegas PCR -> Fallout: New Vegas
}
REGIONS = [
("schinese", "cn"),
("japanese", "jp"),
("koreana", "kr"),
]
def safe_fetch(appid, lang=None, cc=None, delay=0.4):
try:
if lang:
return fetch_app_details_region(appid, lang, cc)
return fetch_app_details(appid)
except urllib.error.HTTPError as exc:
if exc.code == 429:
print(" rate limited, sleeping 60s")
time.sleep(60)
return None
except Exception:
return None
finally:
time.sleep(delay)
SUFFIXES = re.compile(r"\b(PCR|RHCP|RU|CIS|ROW|Retail|PTS|Beta|Demo)\b", re.I)
def normalize(name):
name = (name or "").replace("™", "").replace("®", "").replace("(R)", "").replace("(TM)", "")
name = SUFFIXES.sub(" ", name)
name = re.sub(r"[^0-9a-zа-яё]+", " ", name.lower())
return " ".join(name.split())
def store_search(term, delay=0.4):
import urllib.parse
import urllib.request
url = STORE_SEARCH + urllib.parse.urlencode({"term": term, "l": "russian", "cc": "RU"})
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.load(resp)
time.sleep(delay)
return data.get("items", [])
def copy_details(row):
return {
"short_description": row["short_description"],
"about": row["about"],
"header_image": row["header_image"],
"developers": row["developers"],
"publishers": row["publishers"],
"release_date": row["release_date"],
"lang": row["lang"] or "unknown",
}
def main():
ap = argparse.ArgumentParser(description="Recover descriptions for delisted games")
ap.add_argument("--db", default=db.DEFAULT_DB)
ap.add_argument("--limit", type=int)
ap.add_argument("--delay", type=float, default=0.4)
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
con = db.connect(args.db)
db.init(con)
missing = con.execute("""
SELECT g.appid, g.name FROM games g
JOIN game_details d ON d.appid = g.appid
WHERE d.status = 'missing' AND LOWER(g.type) = 'game'
ORDER BY COALESCE(g.review_pct, 0) DESC, g.name
""").fetchall()
if args.limit:
missing = missing[: args.limit]
print(f"Missing: {len(missing)}")
ok_rows = con.execute("""
SELECT g.appid, g.name, d.short_description, d.about, d.header_image,
d.developers, d.publishers, d.release_date, d.lang
FROM games g JOIN game_details d ON d.appid = g.appid
WHERE d.status = 'ok' AND LOWER(g.type) = 'game'
""").fetchall()
by_norm = {}
for row in ok_rows:
by_norm.setdefault(normalize(row["name"]), []).append(row)
by_appid = {row["appid"]: row for row in ok_rows}
recovered = skipped = 0
for target in missing:
appid, name = target["appid"], target["name"]
norm = normalize(name)
source = None
details = None
if appid in BASE_MAP:
base = BASE_MAP[appid]
details = safe_fetch(base, delay=args.delay)
if details:
source = base
if details is None and norm in by_norm:
row = by_norm[norm][0]
if row["appid"] != appid:
details = copy_details(row)
source = row["appid"]
if details is None and norm:
try:
for item in store_search(name, args.delay):
cand = item.get("id")
if not cand or cand == appid:
continue
if normalize(item.get("name")) != norm:
continue
found = safe_fetch(cand, delay=args.delay)
if found and (found["short_description"] or found["about"]):
details = found
source = cand
break
except Exception as exc:
print(f" search failed for {appid}: {exc}")
if details is None:
for lang, cc in REGIONS:
details = safe_fetch(appid, lang, cc, delay=args.delay)
if details and (details["short_description"] or details["about"]):
source = appid
break
details = None
if details is None:
skipped += 1
continue
recovered += 1
src = "base" if source != appid else "same"
print(f" {appid} {name} <- {src} {source} [{details.get('lang')}] "
f"{('(dry run)' if args.dry_run else '')}")
if not args.dry_run:
save_details(con, appid, details, source_appid=source)
time.sleep(args.delay)
print(f"Recovered: {recovered}, still missing: {len(missing) - recovered} (skipped {skipped})")
if __name__ == "__main__":
main()