Files
SteamBase/tools/export_snapshot.py
T
strsv 697a098ddc
CI / test (push) Successful in 26s
feat: add portable build and release v1.1.0
Bundle SteamBase with embeddable Python, add launchers, docs and tests; bump VERSION to 1.1.0 and finalize the changelog.
2026-11-09 04:32:24 +03:00

340 lines
12 KiB
Python

"""Export a SteamBase library snapshot for SteamBaseServer.
python tools/export_snapshot.py --out snapshot.zip --handle strsv
python tools/export_snapshot.py --out snapshot.zip --no-notes
python tools/export_snapshot.py --out snapshot.zip --include-dlc
The archive follows the server contract in SteamBaseServer/docs/snapshot-contract.md:
manifest.json, catalog.jsonl, library.jsonl and optional attributes/feedback/moods.
The snapshot never includes API keys, tokens, logs or the database file itself.
"""
import argparse
import hashlib
import json
import os
import sys
import tempfile
import zipfile
from datetime import datetime, timezone
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8")
except Exception:
pass
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import db
FORMAT = "steambase-snapshot"
FORMAT_VERSION = 1
CHECKSUM_FILES = ("catalog.jsonl", "library.jsonl", "attributes.jsonl",
"feedback.jsonl", "moods.json")
VERSION_FILE = os.path.join(BASE_DIR, "VERSION")
def app_version():
try:
with open(VERSION_FILE, encoding="utf-8") as handle:
return handle.read().lstrip("\ufeff").strip() or "0.0.0"
except OSError:
return "0.0.0"
def _line(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
def _checksum(parts):
digest = hashlib.sha256()
for name in CHECKSUM_FILES:
data = parts.get(name)
if data is None:
continue
digest.update(name.encode("utf-8"))
digest.update(b"\0")
digest.update(str(len(data)).encode("ascii"))
digest.update(b"\0")
digest.update(data)
return digest.hexdigest()
def _load_json(value, fallback):
try:
return json.loads(value)
except (TypeError, ValueError):
return fallback
def _game_tags(con):
tags = {}
for row in con.execute("""
SELECT gt.appid, tn.name
FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id
ORDER BY gt.appid, tn.name
"""):
tags.setdefault(row["appid"], []).append(row["name"])
return tags
def _game_genres(con):
genres = {}
for row in con.execute("SELECT appid, genre FROM game_genres ORDER BY appid, genre"):
genres.setdefault(row["appid"], []).append(row["genre"])
return genres
def _details_map(con):
return {row["appid"]: row for row in con.execute("SELECT * FROM game_details")}
def _translations_map(con):
return {row["appid"]: row for row in con.execute("SELECT * FROM game_translations")}
def collect(con, handle=None, steamid=None, notes=True, translations=True,
include_dlc=False, mode="replace"):
"""Build snapshot files in memory and return (manifest, files)."""
if mode not in ("replace", "merge"):
raise ValueError("mode must be replace or merge")
handle = (handle or os.environ.get("STEAMBASE_SERVER_HANDLE") or "").strip()
row = con.execute("SELECT value FROM schema_meta WHERE key = 'steamid'").fetchone()
steamid = (steamid or (row[0] if row else "") or "").strip()
tags = _game_tags(con)
genres = _game_genres(con)
details = _details_map(con)
translations = _translations_map(con) if translations else {}
where = "" if include_dlc else "WHERE LOWER(g.type) = 'game'"
catalog_lines = []
catalog_count = 0
for game in con.execute(f"""
SELECT g.* FROM games g {where} ORDER BY g.appid
"""):
appid = game["appid"]
entry = {
"appid": appid,
"name": game["name"],
"type": game["type"],
"release_date": game["release_date"],
"metacritic": game["metacritic"],
"review_pct": game["review_pct"],
"parent_appid": game["parent_appid"],
"genres": genres.get(appid, []),
"tags": tags.get(appid, []),
}
detail = details.get(appid)
if detail:
entry["details"] = {
"short_description": detail["short_description"],
"about": detail["about"],
"header_image": detail["header_image"],
"developers": detail["developers"],
"publishers": detail["publishers"],
"release_date": detail["release_date"],
"lang": detail["lang"],
"status": detail["status"],
"source_appid": detail["source_appid"],
}
translation = translations.get(appid)
if translation:
entry["translation"] = {
"lang": translation["lang"],
"short_description": translation["short_description"],
"about": translation["about"],
"provider": translation["provider"],
"translated_at": translation["translated_at"],
}
if any(game[key] is not None for key in
("hltb_main", "hltb_extra", "hltb_complete", "hltb_id", "hltb_checked_at")):
entry["hltb"] = {
"main": game["hltb_main"],
"extra": game["hltb_extra"],
"complete": game["hltb_complete"],
"hltb_id": game["hltb_id"],
"checked_at": game["hltb_checked_at"],
"match": bool(game["hltb_match"]),
"updated_at": game["hltb_updated_at"],
}
catalog_lines.append(_line(entry))
catalog_count += 1
library_lines = []
library_count = 0
for row in con.execute("""
SELECT g.appid, COALESCE(p.minutes, 0) AS minutes, p.last_played,
COALESCE(i.installed, 0) AS installed, i.size_bytes,
COALESCE(pe.status, 'backlog') AS status, pe.rating,
COALESCE(pe.favorite, 0) AS favorite, pe.notes, o.owned
FROM games g
LEFT JOIN game_playtime p ON p.appid = g.appid
LEFT JOIN game_install i ON i.appid = g.appid
LEFT JOIN personal pe ON pe.appid = g.appid
LEFT JOIN game_ownership o ON o.appid = g.appid
WHERE LOWER(g.type) = 'game'
ORDER BY g.appid
"""):
item = {
"appid": row["appid"],
"minutes": row["minutes"],
"last_played": row["last_played"],
"installed": bool(row["installed"]),
"size_bytes": row["size_bytes"],
"status": row["status"],
"rating": row["rating"],
"favorite": bool(row["favorite"]),
"owned": None if row["owned"] is None else bool(row["owned"]),
}
if notes:
item["notes"] = row["notes"]
library_lines.append(_line(item))
library_count += 1
attributes = [
_line({"appid": row["appid"], "key": row["key"], "value": row["value"]})
for row in con.execute("""
SELECT appid, key, value FROM attributes ORDER BY appid, key
""")
]
feedback = [
_line({"appid": row["appid"], "mood_key": row["mood_key"],
"verdict": row["verdict"], "created_at": row["created_at"]})
for row in con.execute("""
SELECT appid, mood_key, verdict, created_at FROM reco_feedback
ORDER BY appid, mood_key
""")
]
builtins = set(db.MOOD_PRESETS)
moods = []
for row in con.execute("SELECT name, description, genres, tags, updated_at FROM moods ORDER BY name"):
if row["name"] in builtins:
continue
moods.append({
"name": row["name"],
"description": row["description"],
"genres": _load_json(row["genres"], []),
"tags": _load_json(row["tags"], {}),
"updated_at": row["updated_at"],
})
files = {
"catalog.jsonl": "".join(catalog_lines).encode("utf-8"),
"library.jsonl": "".join(library_lines).encode("utf-8"),
}
if attributes:
files["attributes.jsonl"] = "".join(attributes).encode("utf-8")
if feedback:
files["feedback.jsonl"] = "".join(feedback).encode("utf-8")
if moods:
files["moods.json"] = _line(moods).encode("utf-8")
manifest = {
"format": FORMAT,
"format_version": FORMAT_VERSION,
"app_version": app_version(),
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"user": {"handle": handle, "steamid": steamid, "display_name": handle or steamid},
"mode": mode,
"counts": {
"catalog": catalog_count,
"library": library_count,
"attributes": len(attributes),
"feedback": len(feedback),
"moods": len(moods),
},
"checksum_sha256": _checksum(files),
}
return manifest, files
def write_snapshot(con, out_path, **options):
manifest, files = collect(con, **options)
out_dir = os.path.dirname(os.path.abspath(out_path)) or "."
os.makedirs(out_dir, exist_ok=True)
tmp_path = out_path + ".tmp"
try:
with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("manifest.json", _line(manifest))
for name in CHECKSUM_FILES:
data = files.get(name)
if data is not None:
archive.writestr(name, data)
os.replace(tmp_path, out_path)
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
return manifest
def snapshot_checksum(path):
"""Recompute the checksum of an existing snapshot (manifest excluded)."""
with zipfile.ZipFile(path) as archive:
parts = {}
for name in CHECKSUM_FILES:
try:
parts[name] = archive.read(name)
except KeyError:
continue
return _checksum(parts)
def read_manifest(path):
with zipfile.ZipFile(path) as archive:
return json.loads(archive.read("manifest.json").decode("utf-8"))
def main():
ap = argparse.ArgumentParser(description="Export a SteamBase snapshot")
ap.add_argument("--db", default=db.DEFAULT_DB)
ap.add_argument("--out", default="snapshot.zip")
ap.add_argument("--handle", default=os.environ.get("STEAMBASE_SERVER_HANDLE"))
ap.add_argument("--steamid")
ap.add_argument("--no-notes", action="store_true", help="do not include personal notes")
ap.add_argument("--no-translations", action="store_true", help="do not include translations")
ap.add_argument("--include-dlc", action="store_true",
help="include DLC, soundtracks and tools in the catalog")
ap.add_argument("--mode", choices=("replace", "merge"), default="replace")
ap.add_argument("--format-version", type=int, default=FORMAT_VERSION)
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
if args.format_version != FORMAT_VERSION:
print(f"Unsupported format version: {args.format_version}", file=sys.stderr)
return 1
con = db.connect(args.db)
try:
options = {
"handle": args.handle,
"steamid": args.steamid,
"notes": not args.no_notes,
"translations": not args.no_translations,
"include_dlc": args.include_dlc,
"mode": args.mode,
}
if args.dry_run:
manifest, _ = collect(con, **options)
print(json.dumps(manifest, ensure_ascii=False, indent=2))
return 0
manifest = write_snapshot(con, args.out, **options)
size = os.path.getsize(args.out)
print(f"Snapshot: {args.out}")
print(f"Size: {size} bytes")
print(f"Catalog: {manifest['counts']['catalog']} | "
f"Library: {manifest['counts']['library']} | "
f"Attributes: {manifest['counts']['attributes']} | "
f"Feedback: {manifest['counts']['feedback']} | "
f"Moods: {manifest['counts']['moods']}")
print(f"Checksum: sha256={manifest['checksum_sha256']}")
return 0
finally:
con.close()
if __name__ == "__main__":
raise SystemExit(main())