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

109 lines
3.2 KiB
Python

"""Warm the local cover cache.
The web server already caches covers on first request. This script can prefetch
them in advance for games that have no art in the Steam client cache.
python tools/cache_covers.py --all
python tools/cache_covers.py --limit 200
"""
import argparse
import os
import sys
import time
import urllib.request
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
import steam_source
CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps"
NAMES = ("library_600x900.jpg", "header.jpg")
def has_any(paths):
for directory, names in paths:
if not directory:
continue
for name in names:
if os.path.isfile(os.path.join(directory, name)):
return True
return False
def main():
ap = argparse.ArgumentParser(description="Prefetch game covers")
ap.add_argument("--db", default=db.DEFAULT_DB)
ap.add_argument("--limit", type=int)
ap.add_argument("--all", action="store_true")
ap.add_argument("--delay", type=float, default=0.1)
args = ap.parse_args()
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
cache_dir = os.path.join(base, "cache", "covers")
try:
steam_root = steam_source.find_steam_root()
lib_cache = os.path.join(steam_root, "appcache", "librarycache")
except SystemExit:
lib_cache = None
con = db.connect(args.db)
db.init(con)
rows = con.execute("""SELECT appid, name FROM games
WHERE LOWER(type)='game' ORDER BY review_pct DESC""").fetchall()
if not args.all and args.limit:
rows = rows[: args.limit]
print(f"Games: {len(rows)}")
downloaded = skipped = failed = 0
for row in rows:
appid = row["appid"]
cached = os.path.join(cache_dir, str(appid))
steam_art = os.path.join(lib_cache, str(appid)) if lib_cache else None
if has_any([(cached, NAMES), (steam_art, steam_source_names())]):
skipped += 1
continue
got = False
for name in NAMES:
url = f"{CDN}/{appid}/{name}"
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=20) as resp:
data = resp.read()
if not data:
continue
os.makedirs(cached, exist_ok=True)
path = os.path.join(cached, name)
tmp = path + ".tmp"
with open(tmp, "wb") as f:
f.write(data)
os.replace(tmp, path)
got = True
break
except Exception:
continue
finally:
time.sleep(args.delay)
if got:
downloaded += 1
else:
failed += 1
print(f"downloaded={downloaded} skipped={skipped} failed={failed}")
print(f"cache: {cache_dir}")
def steam_source_names():
return ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
if __name__ == "__main__":
main()