397 lines
16 KiB
Python
397 lines
16 KiB
Python
"""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 time
|
|
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/{language}"
|
|
APP_URL = "https://store.steampowered.com/app/{appid}/?l={language}"
|
|
TAG_MODAL_MARKER = "InitAppTagModal"
|
|
|
|
|
|
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(language="english"):
|
|
url = TAG_URL.format(language=language)
|
|
req = urllib.request.Request(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 parse_app_tag_modal(html):
|
|
"""Return {tag_id: name} from the InitAppTagModal(...) call on a Store page.
|
|
|
|
The popular-tags endpoint exposes 429 browsable tags. A game page still lists
|
|
every tag it uses in the ``InitAppTagModal`` JSON, so this fills gaps for
|
|
tag ids outside the popular list.
|
|
"""
|
|
index = html.find(TAG_MODAL_MARKER)
|
|
if index == -1:
|
|
return {}
|
|
start = html.find("[", index)
|
|
if start == -1:
|
|
return {}
|
|
try:
|
|
payload, _ = json.JSONDecoder().raw_decode(html[start:])
|
|
except ValueError:
|
|
return {}
|
|
if not isinstance(payload, list):
|
|
return {}
|
|
names = {}
|
|
for item in payload:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
try:
|
|
tag_id = int(item.get("tagid"))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
name = item.get("name")
|
|
if tag_id and isinstance(name, str) and name.strip():
|
|
names[tag_id] = name.strip()
|
|
return names
|
|
|
|
|
|
def fetch_app_tag_names(appid, language="english", timeout=20):
|
|
url = APP_URL.format(appid=appid, language=language)
|
|
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
return parse_app_tag_modal(resp.read().decode("utf-8", "replace"))
|
|
|
|
|
|
def missing_tag_ids(con):
|
|
rows = con.execute(
|
|
"""SELECT DISTINCT gt.tag_id FROM game_tags gt
|
|
LEFT JOIN tag_names tn ON tn.tag_id = gt.tag_id
|
|
WHERE tn.tag_id IS NULL OR tn.name IS NULL""")
|
|
return {r["tag_id"] for r in rows}
|
|
|
|
|
|
def untranslated_tag_ids(con):
|
|
rows = con.execute(
|
|
"""SELECT tn.tag_id FROM tag_names tn
|
|
WHERE (tn.name_ru IS NULL OR tn.name_ru = '')
|
|
AND EXISTS (SELECT 1 FROM game_tags gt WHERE gt.tag_id = tn.tag_id)""")
|
|
return {r["tag_id"] for r in rows}
|
|
|
|
|
|
def resolve_missing_tag_names(con, max_pages=50, delay=0.4, log=print):
|
|
"""Name and translate tag ids outside the popular list using Store pages."""
|
|
missing_names = missing_tag_ids(con)
|
|
missing_ru = untranslated_tag_ids(con)
|
|
if not (missing_names or missing_ru):
|
|
return 0, 0
|
|
|
|
wanted_ids = missing_names | missing_ru
|
|
holders = {}
|
|
placeholders = ",".join("?" for _ in wanted_ids)
|
|
for row in con.execute(
|
|
f"SELECT appid, tag_id FROM game_tags WHERE tag_id IN ({placeholders}) ORDER BY appid",
|
|
sorted(wanted_ids)):
|
|
holders.setdefault(row["tag_id"], []).append(row["appid"])
|
|
|
|
pages = {}
|
|
for tag_id, appids in holders.items():
|
|
for appid in appids[:3]:
|
|
pages.setdefault(appid, set()).add(tag_id)
|
|
ordered = sorted(pages, key=lambda appid: (-len(pages[appid]), appid))[:max_pages]
|
|
|
|
resolved_names = resolved_ru = 0
|
|
for appid in ordered:
|
|
wanted = pages[appid] & (missing_names | missing_ru)
|
|
if not wanted:
|
|
continue
|
|
names_en = {}
|
|
names_ru = {}
|
|
if wanted & missing_names:
|
|
try:
|
|
names_en = fetch_app_tag_names(appid, "english")
|
|
except Exception as exc:
|
|
log(f" tag names from app {appid} skipped: {exc}")
|
|
time.sleep(delay)
|
|
try:
|
|
names_ru = fetch_app_tag_names(appid, "russian")
|
|
except Exception as exc:
|
|
log(f" tag translations from app {appid} skipped: {exc}")
|
|
time.sleep(delay)
|
|
|
|
rows = []
|
|
for tag_id in wanted:
|
|
name = names_en.get(tag_id)
|
|
if name:
|
|
rows.append((tag_id, name, names_ru.get(tag_id)))
|
|
if rows:
|
|
con.executemany(
|
|
"""INSERT INTO tag_names (tag_id, name, name_ru) VALUES (?, ?, ?)
|
|
ON CONFLICT(tag_id) DO UPDATE SET
|
|
name = COALESCE(excluded.name, tag_names.name),
|
|
name_ru = COALESCE(excluded.name_ru, tag_names.name_ru)""",
|
|
rows)
|
|
con.commit()
|
|
|
|
ru_only = [(names_ru[tag_id], tag_id) for tag_id in wanted
|
|
if tag_id not in missing_names and names_ru.get(tag_id)]
|
|
if ru_only:
|
|
con.executemany("UPDATE tag_names SET name_ru = ? WHERE tag_id = ?", ru_only)
|
|
con.commit()
|
|
|
|
if rows or ru_only:
|
|
log(f" tags from app {appid}: {len(rows)} names, {len(ru_only)} translations")
|
|
|
|
before_names, before_ru = len(missing_names), len(missing_ru)
|
|
missing_names = missing_tag_ids(con)
|
|
missing_ru = untranslated_tag_ids(con)
|
|
resolved_names += before_names - len(missing_names)
|
|
resolved_ru += before_ru - len(missing_ru)
|
|
if not (missing_names or missing_ru):
|
|
break
|
|
|
|
return resolved_names, resolved_ru
|
|
|
|
|
|
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")
|
|
ap.add_argument("--max-tag-pages", type=int, default=50,
|
|
help="max Store pages fetched to resolve tag names (default: 50)")
|
|
ap.add_argument("--tag-delay", type=float, default=0.4,
|
|
help="delay between Store requests in seconds (default: 0.4)")
|
|
ap.add_argument("--refresh-parents", action="store_true",
|
|
help="update games.parent_appid from appinfo and exit")
|
|
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)
|
|
cached_ids = steam_source.library_appids(root)
|
|
installed = steam_source.installed_apps(roots)
|
|
lib_ids = sorted(set(cached_ids) | set(installed))
|
|
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: {len(lib_ids)} (cache: {len(cached_ids)}, installed: {len(installed)})")
|
|
|
|
appinfo = steam_source.read_appinfo(root)
|
|
playtime = steam_source.read_playtime(root, steamid)
|
|
|
|
con = db.connect(args.db)
|
|
db.init(con)
|
|
db.seed_moods(con)
|
|
|
|
if args.refresh_parents:
|
|
updated = 0
|
|
for appid, info in appinfo.items():
|
|
parent = info.get("parent")
|
|
if not parent:
|
|
continue
|
|
cursor = con.execute(
|
|
"UPDATE games SET parent_appid = ? WHERE appid = ? AND "
|
|
"COALESCE(parent_appid, 0) <> ?", (parent, appid, parent))
|
|
updated += max(0, cursor.rowcount)
|
|
con.commit()
|
|
print(f"Parents updated: {updated}")
|
|
con.close()
|
|
return
|
|
|
|
existing_tags = {r["tag_id"]: r["name"] for r in con.execute("SELECT tag_id, name FROM tag_names")}
|
|
existing_ru = {r["tag_id"] for r in con.execute(
|
|
"SELECT tag_id FROM tag_names WHERE name_ru IS NOT NULL AND name_ru <> ''")}
|
|
new_tags = {}
|
|
new_tags_ru = {}
|
|
if not args.no_network:
|
|
if 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)
|
|
if args.refresh_tags or len(existing_tags) < 50 or len(existing_ru) < len(existing_tags):
|
|
try:
|
|
new_tags_ru = fetch_tag_names("russian")
|
|
print(f"Tag translations downloaded: {len(new_tags_ru)}")
|
|
except Exception as exc:
|
|
print(f"Tag translation 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,
|
|
parent_appid, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(appid) DO UPDATE SET
|
|
name = excluded.name, type = excluded.type,
|
|
release_date = COALESCE(excluded.release_date, games.release_date),
|
|
metacritic = excluded.metacritic, review_pct = excluded.review_pct,
|
|
parent_appid = COALESCE(excluded.parent_appid, games.parent_appid),
|
|
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
|
|
total_apps = len(lib_ids)
|
|
report_every = max(1, total_apps // 20)
|
|
with con:
|
|
if new_tags:
|
|
con.executemany(
|
|
"""INSERT INTO tag_names (tag_id, name) VALUES (?, ?)
|
|
ON CONFLICT(tag_id) DO UPDATE SET name = excluded.name""",
|
|
new_tags.items())
|
|
if new_tags_ru:
|
|
con.executemany(
|
|
"UPDATE tag_names SET name_ru = ? WHERE tag_id = ?",
|
|
[(name, tag_id) for tag_id, name in new_tags_ru.items()])
|
|
|
|
for index, appid in enumerate(lib_ids, 1):
|
|
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
|
|
else:
|
|
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"),
|
|
info.get("parent"), 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
|
|
|
|
if index % report_every == 0 or index == total_apps:
|
|
print(f" {index}/{total_apps} apps", flush=True)
|
|
|
|
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,))
|
|
|
|
unnamed = missing_tag_ids(con)
|
|
untranslated = untranslated_tag_ids(con)
|
|
if (unnamed or untranslated) and not args.no_network:
|
|
print(f"Tags without names/translations: {len(unnamed)}/{len(untranslated)}; "
|
|
f"resolving from Store pages...")
|
|
added_names, added_ru = resolve_missing_tag_names(
|
|
con, max_pages=args.max_tag_pages, delay=args.tag_delay)
|
|
unnamed = missing_tag_ids(con)
|
|
untranslated = untranslated_tag_ids(con)
|
|
print(f"Tag names resolved: +{added_names}, translations: +{added_ru} "
|
|
f"(unnamed now: {len(unnamed)}, untranslated now: {len(untranslated)})")
|
|
|
|
db.refresh_search_index(con)
|
|
db.refresh_duration_estimates(con)
|
|
db.backfill_release_dates(con)
|
|
|
|
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")}
|
|
named = con.execute("SELECT COUNT(*) FROM tag_names").fetchone()[0]
|
|
translated = con.execute(
|
|
"SELECT COUNT(*) FROM tag_names WHERE name_ru IS NOT NULL AND name_ru <> ''").fetchone()[0]
|
|
con.close()
|
|
|
|
print(f"Processed: {new_count + updated_count} apps (new: {new_count}, existing: {updated_count}) -> {args.db}")
|
|
print(f"By type: {counts}")
|
|
print(f"Tags: {named} named ({translated} ru), {len(unnamed)} unnamed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|