"""Build/refresh steam.db from the local Steam client cache. Usage: python tools/import_steam.py python tools/import_steam.py --refresh-tags python tools/import_steam.py --steam-root "D:\\Steam" --steamid 76561198000000000 """ import argparse import json import os import sys 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 import steam_source TAG_URL = "https://store.steampowered.com/tagdata/populartags/english" def iso_from_unix(ts): if not ts: return None return datetime.fromtimestamp(int(ts), tz=timezone.utc).strftime("%Y-%m-%d") def fetch_tag_names(): req = urllib.request.Request(TAG_URL, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=30) as resp: data = json.load(resp) return {int(t["tagid"]): t["name"] for t in data} def main(): ap = argparse.ArgumentParser(description="Import the local Steam library into SQLite") ap.add_argument("--steam-root") ap.add_argument("--steamid", help="17-digit SteamID64 (default: most recent login)") ap.add_argument("--db", default=db.DEFAULT_DB) ap.add_argument("--refresh-tags", action="store_true", help="re-download Steam tag names") ap.add_argument("--incremental", action="store_true", help="only add new apps; update install/playtime for existing") ap.add_argument("--no-network", action="store_true", help="never download tag names") args = ap.parse_args() root = args.steam_root or steam_source.find_steam_root() users = steam_source.read_users(root) if args.steamid: steamid = args.steamid else: recent = [u for u in users if u["most_recent"]] or users if not recent: raise SystemExit("No Steam users found; pass --steamid") steamid = recent[0]["steamid"] roots = steam_source.library_roots(root) lib_ids = steam_source.library_appids(root) if not lib_ids: raise SystemExit(f"Empty library cache under {root}\\appcache\\librarycache") print(f"Steam: {root}") print(f"User: {steamid}") print(f"Libraries: {', '.join(roots)}") print(f"Apps in library cache: {len(lib_ids)}") appinfo = steam_source.read_appinfo(root) playtime = steam_source.read_playtime(root, steamid) installed = steam_source.installed_apps(roots) con = db.connect(args.db) db.init(con) db.seed_moods(con) existing_tags = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")} new_tags = {} if not args.no_network and (args.refresh_tags or len(existing_tags) < 50): try: new_tags = fetch_tag_names() print(f"Tag names downloaded: {len(new_tags)}") except Exception as exc: print(f"Tag download skipped: {exc}", file=sys.stderr) now = datetime.now(timezone.utc).isoformat(timespec="seconds") def upsert_game(row): con.execute( """INSERT INTO games (appid, name, type, release_date, metacritic, review_pct, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(appid) DO UPDATE SET name = excluded.name, type = excluded.type, release_date = excluded.release_date, metacritic = excluded.metacritic, review_pct = excluded.review_pct, updated_at = excluded.updated_at""", row, ) def write_playtime(appid, pt): if pt: con.execute( """INSERT INTO game_playtime (appid, minutes, last_played) VALUES (?, ?, ?) ON CONFLICT(appid) DO UPDATE SET minutes = excluded.minutes, last_played = excluded.last_played""", (appid, pt["minutes"], iso_from_unix(pt["last_played"])), ) else: con.execute("INSERT OR IGNORE INTO game_playtime (appid, minutes) VALUES (?, 0)", (appid,)) def write_install(appid, inst): if inst: con.execute( """INSERT INTO game_install (appid, installed, size_bytes, library_path) VALUES (?, 1, ?, ?) ON CONFLICT(appid) DO UPDATE SET installed = 1, size_bytes = excluded.size_bytes, library_path = excluded.library_path""", (appid, inst["size_bytes"], inst["library_path"]), ) else: con.execute("INSERT OR IGNORE INTO game_install (appid, installed) VALUES (?, 0)", (appid,)) con.execute("UPDATE game_install SET installed = 0 WHERE appid = ?", (appid,)) existing_ids = {r["appid"] for r in con.execute("SELECT appid FROM games")} imported = new_count = updated_count = 0 with con: if new_tags: con.executemany("INSERT OR REPLACE INTO tag_names (tag_id, name) VALUES (?, ?)", new_tags.items()) for appid in lib_ids: pt = playtime.get(appid) inst = installed.get(appid) is_new = appid not in existing_ids if args.incremental and not is_new: write_playtime(appid, pt) write_install(appid, inst) updated_count += 1 continue info = appinfo.get(appid, {}) name = info.get("name") or installed.get(appid, {}).get("name") or f"App {appid}" upsert_game((appid, name, info.get("type"), iso_from_unix(info.get("release")), info.get("metacritic"), info.get("review_pct"), now)) genre_ids = info.get("genres") or {} con.execute("DELETE FROM game_genres WHERE appid = ?", (appid,)) con.executemany( "INSERT OR IGNORE INTO game_genres (appid, genre) VALUES (?, ?)", [(appid, steam_source.GENRES.get(v, f"Genre {v}")) for v in genre_ids.values() if isinstance(v, int) and v not in steam_source.SKIP_GENRE_IDS], ) tag_ids = info.get("tags") or {} con.execute("DELETE FROM game_tags WHERE appid = ?", (appid,)) con.executemany( "INSERT OR IGNORE INTO game_tags (appid, tag_id) VALUES (?, ?)", [(appid, v) for v in tag_ids.values() if isinstance(v, int)], ) write_playtime(appid, pt) write_install(appid, inst) default_status = "played" if pt and pt["minutes"] > 0 else "backlog" con.execute("INSERT OR IGNORE INTO personal (appid, status, updated_at) VALUES (?, ?, ?)", (appid, default_status, now)) imported += 1 if is_new: new_count += 1 else: updated_count += 1 con.execute("""UPDATE personal SET status = 'played' WHERE status = 'backlog' AND appid IN (SELECT appid FROM game_playtime WHERE minutes > 0)""") con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('imported_at', ?)", (now,)) con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('steam_root', ?)", (root,)) con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('steamid', ?)", (steamid,)) counts = {r["type"]: r["n"] for r in con.execute( "SELECT COALESCE(LOWER(type), 'unknown') AS type, COUNT(*) AS n FROM games GROUP BY 1")} con.close() print(f"Processed: {new_count + updated_count} apps (new: {new_count}, existing: {updated_count}) -> {args.db}") print(f"By type: {counts}") if __name__ == "__main__": main()