feat: initial SteamBase 1.0.0
This commit is contained in:
commit
d1aee28115
37 files changed
+6518
No files matched your search
+778
@@ -0,0 +1,778 @@
|
||||
"""Local web UI for SteamBase.
|
||||
|
||||
python SteamBase/web/server.py
|
||||
python SteamBase/web/server.py --port 8765 --open
|
||||
|
||||
Binds to 127.0.0.1 by default: no auth, do not expose it to the internet.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import webbrowser
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(BASE, "tools"))
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import db
|
||||
import reco
|
||||
import steam_source
|
||||
import translate_details as td
|
||||
from fetch_details import fetch_app_details, save_details
|
||||
|
||||
try:
|
||||
STEAM_ROOT = steam_source.find_steam_root()
|
||||
except SystemExit:
|
||||
STEAM_ROOT = None
|
||||
LIB_CACHE = os.path.join(STEAM_ROOT, "appcache", "librarycache") if STEAM_ROOT else None
|
||||
CACHE_DIR = os.path.join(BASE, "cache", "covers")
|
||||
IMAGE_LOCK = threading.Lock()
|
||||
COVER_NAMES = ("library_600x900.jpg", "header.jpg")
|
||||
STEAM_COVER_NAMES = ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
|
||||
|
||||
STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
|
||||
STATUSES = {"backlog", "playing", "played", "tribute", "nostalgia", "ignore"}
|
||||
CONTENT_TYPES = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".ico": "image/x-icon",
|
||||
}
|
||||
|
||||
|
||||
class DetailsService:
|
||||
"""Background cache filler for Steam Store descriptions."""
|
||||
|
||||
def __init__(self, db_path, delay=1.4):
|
||||
self.db_path = db_path
|
||||
self.delay = delay
|
||||
self._queue = queue.Queue()
|
||||
self._queued = set()
|
||||
self._queued_lock = threading.Lock()
|
||||
self._rate_lock = threading.Lock()
|
||||
self._last_request = 0.0
|
||||
threading.Thread(target=self._worker, daemon=True).start()
|
||||
|
||||
def _connect(self):
|
||||
con = db.connect(self.db_path)
|
||||
return con
|
||||
|
||||
def _throttle(self):
|
||||
with self._rate_lock:
|
||||
wait = self._last_request + self.delay - time.time()
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
self._last_request = time.time()
|
||||
|
||||
def cached(self, appid):
|
||||
con = self._connect()
|
||||
try:
|
||||
row = con.execute(
|
||||
"SELECT short_description FROM game_details WHERE appid = ? AND status = 'ok'",
|
||||
(appid,)).fetchone()
|
||||
return row["short_description"] if row else None
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def enqueue(self, appid):
|
||||
with self._queued_lock:
|
||||
if appid in self._queued:
|
||||
return
|
||||
self._queued.add(appid)
|
||||
self._queue.put(appid)
|
||||
|
||||
def enqueue_many(self, appids):
|
||||
for appid in appids:
|
||||
self.enqueue(appid)
|
||||
|
||||
def fetch_now(self, appid):
|
||||
con = self._connect()
|
||||
try:
|
||||
row = con.execute("SELECT status FROM game_details WHERE appid = ?", (appid,)).fetchone()
|
||||
if row and row["status"] in ("ok", "missing"):
|
||||
return
|
||||
finally:
|
||||
con.close()
|
||||
self._throttle()
|
||||
try:
|
||||
details = fetch_app_details(appid)
|
||||
con = self._connect()
|
||||
try:
|
||||
save_details(con, appid, details)
|
||||
finally:
|
||||
con.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _worker(self):
|
||||
while True:
|
||||
appid = self._queue.get()
|
||||
try:
|
||||
con = self._connect()
|
||||
try:
|
||||
row = con.execute("SELECT status FROM game_details WHERE appid = ?", (appid,)).fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
if row and row["status"] in ("ok", "missing"):
|
||||
continue
|
||||
self._throttle()
|
||||
details = fetch_app_details(appid)
|
||||
con = self._connect()
|
||||
try:
|
||||
save_details(con, appid, details)
|
||||
finally:
|
||||
con.close()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 429:
|
||||
time.sleep(60)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
with self._queued_lock:
|
||||
self._queued.discard(appid)
|
||||
|
||||
|
||||
class JobManager:
|
||||
"""Runs a maintenance script in the background and exposes its state."""
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
self._state = {
|
||||
"name": None, "running": False, "exit_code": None,
|
||||
"started_at": None, "finished_at": None, "output": [],
|
||||
}
|
||||
|
||||
def start(self, name, args):
|
||||
with self._lock:
|
||||
if self._state["running"]:
|
||||
return False
|
||||
self._state = {
|
||||
"name": name, "running": True, "exit_code": None,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"finished_at": None, "output": [],
|
||||
}
|
||||
threading.Thread(target=self._run, args=(name, args), daemon=True).start()
|
||||
return True
|
||||
|
||||
def _run(self, name, args):
|
||||
code = None
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", *args], cwd=BASE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace",
|
||||
)
|
||||
for line in proc.stdout:
|
||||
with self._lock:
|
||||
self._state["output"].append(line.rstrip())
|
||||
self._state["output"] = self._state["output"][-80:]
|
||||
code = proc.wait()
|
||||
except Exception as exc:
|
||||
with self._lock:
|
||||
self._state["output"].append(str(exc))
|
||||
code = -1
|
||||
finally:
|
||||
with self._lock:
|
||||
self._state["running"] = False
|
||||
self._state["exit_code"] = code
|
||||
self._state["finished_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
if name == "import":
|
||||
try:
|
||||
DETAILS.enqueue_many(missing_detail_ids(1000))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def status(self):
|
||||
with self._lock:
|
||||
return {**self._state, "output": list(self._state["output"])}
|
||||
|
||||
|
||||
DETAILS = None
|
||||
JOBS = JobManager()
|
||||
|
||||
|
||||
def missing_detail_ids(limit=1000):
|
||||
con = connect()
|
||||
try:
|
||||
return [r["appid"] for r in con.execute("""
|
||||
SELECT g.appid FROM games g
|
||||
LEFT JOIN game_details d ON d.appid = g.appid
|
||||
LEFT JOIN game_playtime p ON p.appid = g.appid
|
||||
WHERE LOWER(g.type) = 'game' AND d.appid IS NULL
|
||||
ORDER BY (COALESCE(p.minutes,0) = 0) DESC, COALESCE(g.review_pct,0) DESC
|
||||
LIMIT ?""", (int(limit),))]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def connect():
|
||||
con = db.connect(db.DEFAULT_DB)
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
|
||||
def game_tags_map(con, appids):
|
||||
if not appids:
|
||||
return {}
|
||||
ph = ",".join("?" * len(appids))
|
||||
out = {}
|
||||
for r in con.execute(
|
||||
f"""SELECT gt.appid, tn.name FROM game_tags gt
|
||||
JOIN tag_names tn ON tn.tag_id = gt.tag_id
|
||||
WHERE gt.appid IN ({ph})
|
||||
ORDER BY tn.name""", appids):
|
||||
out.setdefault(r["appid"], []).append(r["name"])
|
||||
return out
|
||||
|
||||
|
||||
def game_genres_map(con, appids):
|
||||
if not appids:
|
||||
return {}
|
||||
ph = ",".join("?" * len(appids))
|
||||
out = {}
|
||||
for r in con.execute(f"SELECT appid, genre FROM game_genres WHERE appid IN ({ph}) ORDER BY genre", appids):
|
||||
out.setdefault(r["appid"], []).append(r["genre"])
|
||||
return out
|
||||
|
||||
|
||||
def details_map(con, appids):
|
||||
if not appids:
|
||||
return {}
|
||||
ph = ",".join("?" * len(appids))
|
||||
return {r["appid"]: r for r in con.execute(
|
||||
f"""SELECT d.*, t.short_description AS short_ru, t.about AS about_ru
|
||||
FROM game_details d
|
||||
LEFT JOIN game_translations t ON t.appid = d.appid
|
||||
WHERE d.appid IN ({ph})""", appids)}
|
||||
|
||||
|
||||
def clean_text(value):
|
||||
if not value:
|
||||
return None
|
||||
value = value.replace("\ufeff", "").strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def strip_html(value):
|
||||
text = re.sub(r"<[^>]+>", " ", value or "")
|
||||
text = text.replace(" ", " ").replace("&", "&")
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def description_of(details):
|
||||
if not details:
|
||||
return None
|
||||
text = clean_text(details["short_ru"]) or clean_text(details["short_description"])
|
||||
if not text:
|
||||
about = details["about_ru"] or details["about"]
|
||||
text = strip_html(about)[:240].strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def serialize(r, tags, genres, details):
|
||||
release = r["release_date"] or (details["release_date"] if details else None)
|
||||
year = None
|
||||
if release:
|
||||
for part in str(release).replace(".", "-").split("-"):
|
||||
if len(part) == 4 and part.isdigit():
|
||||
year = int(part)
|
||||
break
|
||||
return {
|
||||
"appid": r["appid"],
|
||||
"name": r["name"],
|
||||
"year": year,
|
||||
"review": r["review_pct"],
|
||||
"metacritic": r["metacritic"],
|
||||
"hours": round((r["minutes"] or 0) / 60, 1),
|
||||
"installed": bool(r["installed"]),
|
||||
"status": r["status"],
|
||||
"rating": r["rating"],
|
||||
"favorite": bool(r["favorite"]),
|
||||
"notes": r["notes"],
|
||||
"genres": genres,
|
||||
"tags": tags[:10],
|
||||
"description": description_of(details),
|
||||
"desc_status": (details["status"] if details else None),
|
||||
"developers": (details["developers"] if details else None),
|
||||
"publishers": (details["publishers"] if details else None),
|
||||
}
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "SteamBase/1.0"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
if "/api/" in (args[0] if args else ""):
|
||||
return
|
||||
super().log_message(fmt, *args)
|
||||
|
||||
def _send(self, status, body, content_type="application/json; charset=utf-8",
|
||||
cache=False, max_age=86400):
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control",
|
||||
f"public, max-age={max_age}" if cache else "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _json(self, obj, status=200):
|
||||
self._send(status, json.dumps(obj, ensure_ascii=False), "application/json; charset=utf-8")
|
||||
|
||||
def _error(self, status, message):
|
||||
self._json({"error": message}, status)
|
||||
|
||||
def _body(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if not length:
|
||||
return {}
|
||||
return json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
|
||||
def do_GET(self):
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
try:
|
||||
if path.startswith("/api/"):
|
||||
self._api_get(path, urllib.parse.parse_qs(parsed.query))
|
||||
return
|
||||
self._static(path)
|
||||
except Exception as exc:
|
||||
self._error(500, str(exc))
|
||||
|
||||
def do_POST(self):
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
try:
|
||||
if path == "/api/recommend":
|
||||
self._recommend(self._body())
|
||||
elif path == "/api/prefetch":
|
||||
body = self._body()
|
||||
ids = self._missing_ids(body.get("limit", 200), bool(body.get("retry_missing")))
|
||||
DETAILS.enqueue_many(ids)
|
||||
self._json({"queued": len(ids)})
|
||||
elif path.startswith("/api/personal/"):
|
||||
appid = int(path.rsplit("/", 1)[1])
|
||||
self._update_personal(appid, self._body())
|
||||
elif path == "/api/refresh":
|
||||
body = self._body()
|
||||
mode = body.get("mode", "incremental")
|
||||
if mode not in ("incremental", "full"):
|
||||
self._error(400, "unknown mode")
|
||||
return
|
||||
script = os.path.join(BASE, "tools", "import_steam.py")
|
||||
args = [script] + (["--incremental"] if mode == "incremental" else ["--refresh-tags"])
|
||||
if not JOBS.start("import", args):
|
||||
self._error(409, "another job is running")
|
||||
return
|
||||
self._json({"started": True, "mode": mode})
|
||||
elif path == "/api/translate":
|
||||
body = self._body()
|
||||
script = os.path.join(BASE, "tools", "translate_details.py")
|
||||
args = [script, "--limit", str(int(body.get("limit", 400)))]
|
||||
if body.get("about"):
|
||||
args.append("--about")
|
||||
if not JOBS.start("translate", args):
|
||||
self._error(409, "another job is running")
|
||||
return
|
||||
self._json({"started": True})
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
except Exception as exc:
|
||||
self._error(500, str(exc))
|
||||
|
||||
def _static(self, path):
|
||||
if path in ("/", ""):
|
||||
path = "/index.html"
|
||||
rel = path.lstrip("/")
|
||||
if rel.startswith("static/"):
|
||||
rel = rel[len("static/"):]
|
||||
full = os.path.normpath(os.path.join(STATIC, rel))
|
||||
if not full.startswith(STATIC) or not os.path.isfile(full):
|
||||
self._error(404, "not found")
|
||||
return
|
||||
ext = os.path.splitext(full)[1].lower()
|
||||
with open(full, "rb") as f:
|
||||
self._send(200, f.read(), CONTENT_TYPES.get(ext, "application/octet-stream"))
|
||||
|
||||
def _serve_image(self, path):
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
self._send(200, data, CONTENT_TYPES.get(ext, "image/jpeg"),
|
||||
cache=True, max_age=2592000)
|
||||
|
||||
def _cover(self, appid):
|
||||
# 1. our own cache
|
||||
for name in COVER_NAMES:
|
||||
path = os.path.join(CACHE_DIR, str(appid), name)
|
||||
if os.path.isfile(path):
|
||||
self._serve_image(path)
|
||||
return
|
||||
# 2. art already downloaded by the Steam client
|
||||
if LIB_CACHE:
|
||||
for name in STEAM_COVER_NAMES:
|
||||
path = os.path.join(LIB_CACHE, str(appid), name)
|
||||
if os.path.isfile(path):
|
||||
self._serve_image(path)
|
||||
return
|
||||
# 3. download once from the CDN and keep it on disk
|
||||
for name in COVER_NAMES:
|
||||
path = os.path.join(CACHE_DIR, str(appid), name)
|
||||
data = None
|
||||
with IMAGE_LOCK:
|
||||
if os.path.isfile(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
else:
|
||||
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{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 data:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(data)
|
||||
os.replace(tmp, path)
|
||||
except Exception:
|
||||
data = None
|
||||
if data:
|
||||
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
||||
return
|
||||
self._error(404, "no cover")
|
||||
|
||||
def _api_get(self, path, qs):
|
||||
if path == "/api/meta":
|
||||
self._meta()
|
||||
elif path == "/api/games":
|
||||
self._games(qs)
|
||||
elif path == "/api/moods":
|
||||
self._moods()
|
||||
elif path == "/api/descriptions":
|
||||
ids = [int(x) for x in (qs.get("ids", [""])[0] or "").split(",") if x.isdigit()]
|
||||
con = connect()
|
||||
try:
|
||||
dm = details_map(con, ids)
|
||||
self._json({str(i): description_of(dm.get(i)) for i in ids})
|
||||
finally:
|
||||
con.close()
|
||||
elif path == "/api/job":
|
||||
self._json(JOBS.status())
|
||||
elif path.startswith("/api/cover/"):
|
||||
self._cover(int(path.rsplit("/", 1)[1]))
|
||||
elif path.startswith("/api/game/"):
|
||||
appid = int(path.rsplit("/", 1)[1])
|
||||
self._game(appid, qs)
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
|
||||
def _meta(self):
|
||||
con = connect()
|
||||
try:
|
||||
total = con.execute("SELECT COUNT(*) c FROM games WHERE LOWER(type)='game'").fetchone()["c"]
|
||||
installed = con.execute("""SELECT COUNT(*) c FROM game_install i JOIN games g ON g.appid=i.appid
|
||||
WHERE i.installed=1 AND LOWER(g.type)='game'""").fetchone()["c"]
|
||||
played = con.execute("""SELECT COUNT(*) c FROM game_playtime p JOIN games g ON g.appid=p.appid
|
||||
WHERE p.minutes>0 AND LOWER(g.type)='game'""").fetchone()["c"]
|
||||
minutes = con.execute("""SELECT COALESCE(SUM(p.minutes),0) c FROM game_playtime p
|
||||
JOIN games g ON g.appid=p.appid WHERE LOWER(g.type)='game'""").fetchone()["c"]
|
||||
cached = con.execute("""SELECT COUNT(*) c FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE d.status='ok' AND LOWER(g.type)='game'""").fetchone()["c"]
|
||||
missing = con.execute("""SELECT COUNT(*) c FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE d.status='missing' AND LOWER(g.type)='game'""").fetchone()["c"]
|
||||
translated = con.execute("""SELECT COUNT(*) c FROM game_translations t
|
||||
JOIN games g ON g.appid=t.appid
|
||||
WHERE LOWER(g.type)='game'""").fetchone()["c"]
|
||||
untranslated = con.execute("""
|
||||
SELECT d.short_description, d.about FROM game_details d
|
||||
JOIN games g ON g.appid=d.appid
|
||||
LEFT JOIN game_translations t ON t.appid=d.appid
|
||||
WHERE d.status='ok' AND LOWER(g.type)='game' AND t.appid IS NULL
|
||||
""").fetchall()
|
||||
translate_pending = sum(
|
||||
1 for r in untranslated
|
||||
if td.looks_english(r["short_description"])
|
||||
or (not r["short_description"] and td.looks_english(r["about"]))
|
||||
)
|
||||
genres = [{"name": r["genre"], "count": r["c"]} for r in con.execute("""
|
||||
SELECT gg.genre, COUNT(*) c FROM game_genres gg JOIN games g ON g.appid=gg.appid
|
||||
WHERE LOWER(g.type)='game' GROUP BY gg.genre ORDER BY c DESC""")]
|
||||
tags = [{"name": r["name"], "count": r["c"]} for r in con.execute("""
|
||||
SELECT tn.name, COUNT(*) c FROM game_tags gt
|
||||
JOIN games g ON g.appid=gt.appid
|
||||
JOIN tag_names tn ON tn.tag_id=gt.tag_id
|
||||
WHERE LOWER(g.type)='game'
|
||||
GROUP BY tn.name ORDER BY c DESC LIMIT 80""")]
|
||||
statuses = {r["status"]: r["c"] for r in con.execute(
|
||||
"SELECT status, COUNT(*) c FROM personal GROUP BY status")}
|
||||
self._json({
|
||||
"total": total, "installed": installed, "played": played,
|
||||
"hours": round(minutes / 60), "cached": cached, "missing": missing,
|
||||
"pending": max(0, total - cached - missing),
|
||||
"translated": translated, "translate_pending": translate_pending,
|
||||
"genres": genres, "tags": tags, "statuses": statuses,
|
||||
})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _games(self, qs):
|
||||
def q(name, default=None):
|
||||
return qs.get(name, [default])[0]
|
||||
|
||||
where = ["LOWER(g.type)='game'"]
|
||||
params = []
|
||||
if q("q"):
|
||||
where.append("g.name LIKE ? COLLATE NOCASE")
|
||||
params.append(f"%{q('q')}%")
|
||||
if q("genre"):
|
||||
where.append("EXISTS (SELECT 1 FROM game_genres gg WHERE gg.appid=g.appid AND gg.genre=?)")
|
||||
params.append(q("genre"))
|
||||
if q("tag"):
|
||||
where.append("""EXISTS (SELECT 1 FROM game_tags gt JOIN tag_names tn ON tn.tag_id=gt.tag_id
|
||||
WHERE gt.appid=g.appid AND tn.name=?)""")
|
||||
params.append(q("tag"))
|
||||
if q("status"):
|
||||
where.append("COALESCE(pe.status,'backlog') = ?")
|
||||
params.append(q("status"))
|
||||
if q("installed") == "1":
|
||||
where.append("COALESCE(i.installed,0) = 1")
|
||||
if q("unplayed") == "1":
|
||||
where.append("COALESCE(p.minutes,0) = 0")
|
||||
if q("favorite") == "1":
|
||||
where.append("COALESCE(pe.favorite,0) = 1")
|
||||
|
||||
sort = q("sort", "name")
|
||||
order = {
|
||||
"name": "g.name COLLATE NOCASE ASC",
|
||||
"hours": "COALESCE(p.minutes,0) DESC, g.name COLLATE NOCASE",
|
||||
"review": "COALESCE(g.review_pct,0) DESC, g.name COLLATE NOCASE",
|
||||
"year": "COALESCE(g.release_date,'') DESC, g.name COLLATE NOCASE",
|
||||
"added": "g.appid DESC",
|
||||
}.get(sort, "g.name COLLATE NOCASE ASC")
|
||||
|
||||
page = max(1, int(q("page", "1") or 1))
|
||||
per_page = min(120, max(12, int(q("per_page", "60") or 60)))
|
||||
base = f"""FROM games g
|
||||
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_details d ON d.appid=g.appid
|
||||
WHERE {' AND '.join(where)}"""
|
||||
con = connect()
|
||||
try:
|
||||
total = con.execute(f"SELECT COUNT(*) c {base}", params).fetchone()["c"]
|
||||
rows = con.execute(
|
||||
f"""SELECT g.appid, g.name, g.release_date, g.metacritic, g.review_pct,
|
||||
COALESCE(p.minutes,0) minutes, COALESCE(i.installed,0) installed,
|
||||
COALESCE(pe.status,'backlog') status, pe.rating,
|
||||
COALESCE(pe.favorite,0) favorite, pe.notes
|
||||
{base} ORDER BY {order} LIMIT ? OFFSET ?""",
|
||||
[*params, per_page, (page - 1) * per_page]).fetchall()
|
||||
ids = [r["appid"] for r in rows]
|
||||
tags = game_tags_map(con, ids)
|
||||
genres = game_genres_map(con, ids)
|
||||
details = details_map(con, ids)
|
||||
items = [serialize(r, tags.get(r["appid"], []), genres.get(r["appid"], []),
|
||||
details.get(r["appid"])) for r in rows]
|
||||
missing = [r["appid"] for r in rows if r["appid"] not in details]
|
||||
DETAILS.enqueue_many(missing)
|
||||
self._json({"total": total, "page": page, "per_page": per_page, "items": items})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _game(self, appid, qs):
|
||||
con = connect()
|
||||
try:
|
||||
r = con.execute("""
|
||||
SELECT g.appid, g.name, g.type, g.release_date, g.metacritic, g.review_pct,
|
||||
COALESCE(p.minutes,0) minutes, p.last_played,
|
||||
COALESCE(i.installed,0) installed, i.size_bytes,
|
||||
COALESCE(pe.status,'backlog') status, pe.rating,
|
||||
COALESCE(pe.favorite,0) favorite, pe.notes
|
||||
FROM games g
|
||||
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
|
||||
WHERE g.appid = ?""", (appid,)).fetchone()
|
||||
if not r:
|
||||
self._error(404, "unknown appid")
|
||||
return
|
||||
if qs.get("fetch", ["0"])[0] == "1":
|
||||
DETAILS.fetch_now(appid)
|
||||
con.close()
|
||||
con = connect()
|
||||
tags = game_tags_map(con, [appid]).get(appid, [])
|
||||
genres = game_genres_map(con, [appid]).get(appid, [])
|
||||
d = details_map(con, [appid]).get(appid)
|
||||
item = serialize(r, tags, genres, d)
|
||||
item.update({
|
||||
"size_gb": round((r["size_bytes"] or 0) / (1024 ** 3), 1),
|
||||
"last_played": r["last_played"],
|
||||
"about": (d["about_ru"] or d["about"]) if d else None,
|
||||
"steam_url": f"https://store.steampowered.com/app/{appid}/",
|
||||
})
|
||||
attrs = [{"key": a["key"], "value": a["value"]} for a in con.execute(
|
||||
"SELECT key, value FROM attributes WHERE appid=? ORDER BY key", (appid,))]
|
||||
item["attributes"] = attrs
|
||||
item["similar"] = reco.similar_games(con, appid, limit=6)
|
||||
self._json(item)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _moods(self):
|
||||
con = connect()
|
||||
try:
|
||||
moods = [{"name": r["name"], "description": r["description"],
|
||||
"genres": json.loads(r["genres"]), "tags": json.loads(r["tags"])}
|
||||
for r in con.execute("SELECT * FROM moods ORDER BY name")]
|
||||
self._json({"moods": moods})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _recommend(self, body):
|
||||
con = connect()
|
||||
try:
|
||||
db.seed_moods(con)
|
||||
try:
|
||||
mood = reco.load_mood(con, body.get("preset"), body.get("mood"))
|
||||
except (KeyError, ValueError):
|
||||
self._error(400, "unknown mood")
|
||||
return
|
||||
allowed = {"backlog", "playing", "played"}
|
||||
if body.get("include_tribute"):
|
||||
allowed.add("tribute")
|
||||
if body.get("include_nostalgia"):
|
||||
allowed.add("nostalgia")
|
||||
mood, results = reco.recommend(
|
||||
con, mood,
|
||||
allowed_statuses=allowed,
|
||||
unplayed_only=bool(body.get("unplayed_only")),
|
||||
min_review=int(body.get("min_review", 65)),
|
||||
allow_unknown=bool(body.get("allow_unknown")),
|
||||
limit=min(100, int(body.get("limit", 36))),
|
||||
)
|
||||
ids = [g["appid"] for g in results]
|
||||
details = details_map(con, ids)
|
||||
DETAILS.enqueue_many([i for i in ids if i not in details])
|
||||
for g in results:
|
||||
row = details.get(g["appid"])
|
||||
g["description"] = description_of(row)
|
||||
g["desc_status"] = row["status"] if row else None
|
||||
self._json({"mood": mood, "results": results})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _update_personal(self, appid, body):
|
||||
con = connect()
|
||||
try:
|
||||
exists = con.execute("SELECT 1 FROM games WHERE appid=?", (appid,)).fetchone()
|
||||
if not exists:
|
||||
self._error(404, "unknown appid")
|
||||
return
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
con.execute("INSERT OR IGNORE INTO personal (appid, status, updated_at) VALUES (?, 'backlog', ?)",
|
||||
(appid, now))
|
||||
sets, vals = [], []
|
||||
if "status" in body and body["status"] in STATUSES:
|
||||
sets.append("status=?")
|
||||
vals.append(body["status"])
|
||||
if "rating" in body:
|
||||
rating = int(body["rating"])
|
||||
sets.append("rating=?")
|
||||
vals.append(rating if 1 <= rating <= 10 else None)
|
||||
if "favorite" in body:
|
||||
sets.append("favorite=?")
|
||||
vals.append(1 if body["favorite"] else 0)
|
||||
if "notes" in body:
|
||||
sets.append("notes=?")
|
||||
vals.append(body["notes"])
|
||||
if not sets:
|
||||
self._error(400, "nothing to update")
|
||||
return
|
||||
sets.append("updated_at=?")
|
||||
vals.append(now)
|
||||
con.execute(f"UPDATE personal SET {', '.join(sets)} WHERE appid=?", [*vals, appid])
|
||||
con.commit()
|
||||
row = con.execute("SELECT * FROM personal WHERE appid=?", (appid,)).fetchone()
|
||||
self._json({k: row[k] for k in row.keys()})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _missing_ids(self, limit, retry_missing=False):
|
||||
limit = int(limit)
|
||||
con = connect()
|
||||
try:
|
||||
if retry_missing:
|
||||
rows = con.execute("""
|
||||
SELECT d.appid FROM game_details d JOIN games g ON g.appid=d.appid
|
||||
WHERE d.status='missing' AND LOWER(g.type)='game'
|
||||
ORDER BY COALESCE(g.review_pct,0) DESC LIMIT ?""", (limit,)).fetchall()
|
||||
ids = [r["appid"] for r in rows]
|
||||
if ids:
|
||||
ph = ",".join("?" * len(ids))
|
||||
con.execute(f"DELETE FROM game_details WHERE appid IN ({ph})", ids)
|
||||
con.commit()
|
||||
return ids
|
||||
rows = con.execute("""
|
||||
SELECT g.appid FROM games g
|
||||
LEFT JOIN game_details d ON d.appid=g.appid
|
||||
LEFT JOIN game_playtime p ON p.appid=g.appid
|
||||
WHERE LOWER(g.type)='game' AND d.appid IS NULL
|
||||
ORDER BY (COALESCE(p.minutes,0)=0) DESC, COALESCE(g.review_pct,0) DESC
|
||||
LIMIT ?""", (limit,)).fetchall()
|
||||
return [r["appid"] for r in rows]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="SteamBase web UI")
|
||||
ap.add_argument("--host", default="127.0.0.1")
|
||||
ap.add_argument("--port", type=int, default=8765)
|
||||
ap.add_argument("--open", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
global DETAILS
|
||||
con = db.connect(db.DEFAULT_DB)
|
||||
db.init(con)
|
||||
db.seed_moods(con)
|
||||
con.close()
|
||||
DETAILS = DetailsService(db.DEFAULT_DB, delay=1.4)
|
||||
|
||||
url = f"http://{args.host}:{args.port}/"
|
||||
print(f"SteamBase UI: {url}")
|
||||
if args.open:
|
||||
threading.Timer(0.7, lambda: webbrowser.open(url)).start()
|
||||
server = ThreadingHTTPServer((args.host, args.port), Handler)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user