1256 lines
48 KiB
Python
1256 lines
48 KiB
Python
"""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 logging
|
|
import os
|
|
import queue
|
|
import re
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
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
|
|
from logging.handlers import RotatingFileHandler
|
|
|
|
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 covers
|
|
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_MISSING_TTL = 7 * 24 * 60 * 60
|
|
CACHE_COVER_NAMES = steam_source.COVER_ORDER
|
|
PROGRESS_RE = re.compile(r"^\s*(\d+)/(\d+)\b")
|
|
|
|
LOG = logging.getLogger("steambase")
|
|
LOG.setLevel(logging.INFO)
|
|
LOG.propagate = False
|
|
LOG.addHandler(logging.NullHandler())
|
|
|
|
|
|
def setup_logging(path=None):
|
|
"""Attach a rotating JSON-lines log under data/ (no request bodies)."""
|
|
path = path or os.path.join(BASE, "data", "server.log")
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
target = os.path.abspath(path)
|
|
for handler in LOG.handlers:
|
|
if isinstance(handler, RotatingFileHandler) and handler.baseFilename == target:
|
|
return handler
|
|
handler = RotatingFileHandler(target, maxBytes=1024 * 1024, backupCount=3, encoding="utf-8")
|
|
handler.setFormatter(logging.Formatter("%(message)s"))
|
|
LOG.addHandler(handler)
|
|
return handler
|
|
|
|
|
|
def log_event(event, **fields):
|
|
record = {"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), "event": event}
|
|
record.update(fields)
|
|
LOG.info(json.dumps(record, ensure_ascii=False))
|
|
CDN_COVER_NAMES = (
|
|
"library_600x900.jpg",
|
|
"library_capsule.jpg",
|
|
"header.jpg",
|
|
"library_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",
|
|
".webp": "image/webp",
|
|
".webmanifest": "application/manifest+json; charset=utf-8",
|
|
}
|
|
|
|
|
|
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._proc = None
|
|
self._last = None
|
|
self._state = {
|
|
"name": None, "running": False, "cancelled": False, "exit_code": None,
|
|
"started_at": None, "finished_at": None, "progress": None, "output": [],
|
|
}
|
|
|
|
def start(self, name, args):
|
|
with self._lock:
|
|
if self._state["running"]:
|
|
return False
|
|
self._proc = None
|
|
self._last = (name, list(args))
|
|
self._state = {
|
|
"name": name, "running": True, "cancelled": False, "exit_code": None,
|
|
"started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
"finished_at": None, "progress": None, "output": [],
|
|
}
|
|
log_event("job_start", name=name)
|
|
threading.Thread(target=self._run, args=(name, args), daemon=True).start()
|
|
return True
|
|
|
|
def retry(self):
|
|
with self._lock:
|
|
if self._state["running"] or not self._last:
|
|
return False
|
|
name, args = self._last
|
|
return self.start(name, args)
|
|
|
|
def cancel(self):
|
|
deadline = time.time() + 2
|
|
while True:
|
|
with self._lock:
|
|
if not self._state["running"]:
|
|
return False
|
|
proc = self._proc
|
|
if proc is not None:
|
|
self._state["cancelled"] = True
|
|
name = self._state["name"]
|
|
break
|
|
if time.time() >= deadline:
|
|
return False
|
|
time.sleep(0.02)
|
|
try:
|
|
proc.terminate()
|
|
except OSError:
|
|
return False
|
|
try:
|
|
proc.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
log_event("job_cancel", name=name)
|
|
return True
|
|
|
|
def _update_progress(self, line, started):
|
|
match = PROGRESS_RE.match(line)
|
|
if not match:
|
|
return
|
|
current, total = int(match.group(1)), int(match.group(2))
|
|
if total <= 0 or current > total:
|
|
return
|
|
elapsed = time.monotonic() - started
|
|
eta = int(elapsed / current * (total - current)) if current else None
|
|
with self._lock:
|
|
self._state["progress"] = {
|
|
"current": current,
|
|
"total": total,
|
|
"percent": round(current / total * 100, 1),
|
|
"eta_seconds": max(0, eta) if eta is not None else None,
|
|
}
|
|
|
|
def _run(self, name, args):
|
|
code = None
|
|
proc = None
|
|
started = time.monotonic()
|
|
try:
|
|
proc = subprocess.Popen(
|
|
[sys.executable, "-u", *args], cwd=BASE,
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
text=True, encoding="utf-8", errors="replace",
|
|
)
|
|
self._proc = proc
|
|
for line in proc.stdout:
|
|
line = line.rstrip()
|
|
with self._lock:
|
|
self._state["output"].append(line)
|
|
self._state["output"] = self._state["output"][-80:]
|
|
self._update_progress(line, started)
|
|
code = proc.wait()
|
|
except Exception as exc:
|
|
with self._lock:
|
|
self._state["output"].append(str(exc))
|
|
code = -1
|
|
finally:
|
|
if proc is not None and proc.stdout is not None:
|
|
try:
|
|
proc.stdout.close()
|
|
except OSError:
|
|
pass
|
|
with self._lock:
|
|
self._state["running"] = False
|
|
self._state["exit_code"] = code
|
|
self._state["finished_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
cancelled = self._state["cancelled"]
|
|
self._proc = None
|
|
log_event("job_finish", name=name, exit_code=code, cancelled=cancelled,
|
|
duration_seconds=round(time.monotonic() - started, 1))
|
|
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 multi_values(qs, name):
|
|
"""Accept repeated and/or comma-separated query values."""
|
|
values = []
|
|
for raw in qs.get(name, []):
|
|
for value in raw.split(","):
|
|
value = value.strip()
|
|
if value and value not in values:
|
|
values.append(value)
|
|
return values
|
|
|
|
|
|
def number_param(qs, name, cast=float):
|
|
raw = qs.get(name, [""])[0]
|
|
if raw in (None, ""):
|
|
return None
|
|
try:
|
|
return cast(raw)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def fts_query(text):
|
|
"""Turn user text into a safe FTS5 prefix query."""
|
|
tokens = [t.lower() for t in re.findall(r"\w+", text or "", flags=re.UNICODE)
|
|
if len(t) > 1 or t.isdigit()]
|
|
return " ".join(f'"{token}"*' for token in tokens[:8])
|
|
|
|
|
|
def release_year(value):
|
|
match = re.search(r"\b(19|20)\d{2}\b", str(value or ""))
|
|
return int(match.group(0)) if match else None
|
|
|
|
|
|
def serialize(r, tags, genres, details):
|
|
release = r["release_date"] or (details["release_date"] if details else None)
|
|
year = release_year(release)
|
|
return {
|
|
"appid": r["appid"],
|
|
"name": r["name"],
|
|
"year": year,
|
|
"review": r["review_pct"],
|
|
"metacritic": r["metacritic"],
|
|
"hours": round((r["minutes"] or 0) / 60, 1),
|
|
"duration": r["estimated_hours"],
|
|
"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, extra_headers=None):
|
|
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")
|
|
for name, value in (extra_headers or {}).items():
|
|
self.send_header(name, value)
|
|
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:
|
|
log_event("http_error", method="GET", path=path, error=str(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/feedback":
|
|
self._feedback(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 == "/api/personal/bulk":
|
|
self._update_personal_bulk(self._body())
|
|
elif path == "/api/personal/restore":
|
|
self._restore_personal(self._body())
|
|
elif path.startswith("/api/personal/"):
|
|
appid = int(path.rsplit("/", 1)[1])
|
|
self._update_personal(appid, self._body())
|
|
elif path == "/api/job/cancel":
|
|
self._json({"cancelled": JOBS.cancel()})
|
|
elif path == "/api/job/retry":
|
|
self._json({"started": JOBS.retry()})
|
|
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:
|
|
log_event("http_error", method="POST", path=path, error=str(exc))
|
|
self._error(500, str(exc))
|
|
|
|
def _static(self, path):
|
|
if path in ("/", ""):
|
|
path = "/index.html"
|
|
if path == "/sw.js":
|
|
full = os.path.join(STATIC, "sw.js")
|
|
if os.path.isfile(full):
|
|
with open(full, "rb") as fh:
|
|
self._send(200, fh.read(), "application/javascript; charset=utf-8")
|
|
else:
|
|
self._error(404, "not found")
|
|
return
|
|
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 _download_cover(self, url, path):
|
|
with IMAGE_LOCK:
|
|
if os.path.isfile(path):
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
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)
|
|
return data
|
|
except Exception:
|
|
return None
|
|
return None
|
|
|
|
def _cover_marker(self, appid):
|
|
return os.path.join(CACHE_DIR, str(appid), ".missing")
|
|
|
|
def _cover_missing_fresh(self, appid):
|
|
path = self._cover_marker(appid)
|
|
try:
|
|
return time.time() - os.path.getmtime(path) < COVER_MISSING_TTL
|
|
except OSError:
|
|
return False
|
|
|
|
def _mark_cover_missing(self, appid):
|
|
path = self._cover_marker(appid)
|
|
try:
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
with open(path, "w", encoding="utf-8") as fh:
|
|
fh.write(str(int(time.time())))
|
|
except OSError:
|
|
pass
|
|
|
|
def _clear_cover_missing(self, appid):
|
|
try:
|
|
os.remove(self._cover_marker(appid))
|
|
except OSError:
|
|
pass
|
|
|
|
def _preview_for(self, app_cache, source):
|
|
if not covers.can_optimize():
|
|
return None
|
|
preview = os.path.join(app_cache, covers.PREVIEW_NAME)
|
|
if os.path.isfile(preview):
|
|
return preview
|
|
with IMAGE_LOCK:
|
|
if not os.path.isfile(preview):
|
|
covers.make_preview(source, preview)
|
|
return preview if os.path.isfile(preview) else None
|
|
|
|
def _cover(self, appid):
|
|
app_cache = os.path.join(CACHE_DIR, str(appid))
|
|
|
|
preview = os.path.join(app_cache, covers.PREVIEW_NAME)
|
|
if os.path.isfile(preview):
|
|
self._clear_cover_missing(appid)
|
|
self._serve_image(preview)
|
|
return
|
|
|
|
# 1. our own cache (including new-style names)
|
|
for name in CACHE_COVER_NAMES:
|
|
path = os.path.join(app_cache, name)
|
|
if os.path.isfile(path):
|
|
self._clear_cover_missing(appid)
|
|
self._serve_image(self._preview_for(app_cache, path) or path)
|
|
return
|
|
|
|
# 2. art already downloaded by the Steam client (old and new layout)
|
|
local = steam_source.find_cover(appid, LIB_CACHE)
|
|
if local:
|
|
self._clear_cover_missing(appid)
|
|
self._serve_image(self._preview_for(app_cache, local) or local)
|
|
return
|
|
|
|
# Do not hammer Steam CDN for apps known to have no cover.
|
|
if self._cover_missing_fresh(appid):
|
|
self._error(404, "no cover")
|
|
return
|
|
|
|
# 3. header_image from the cached store details (new hashed CDN URL)
|
|
con = connect()
|
|
try:
|
|
row = con.execute(
|
|
"SELECT header_image FROM game_details WHERE appid = ? AND COALESCE(header_image, '') <> ''",
|
|
(appid,)).fetchone()
|
|
finally:
|
|
con.close()
|
|
if row:
|
|
path = os.path.join(app_cache, "header.jpg")
|
|
data = self._download_cover(row["header_image"], path)
|
|
if data:
|
|
self._clear_cover_missing(appid)
|
|
preview = self._preview_for(app_cache, path)
|
|
if preview:
|
|
self._serve_image(preview)
|
|
else:
|
|
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
|
return
|
|
|
|
# 4. legacy CDN names, kept on disk
|
|
for name in CDN_COVER_NAMES:
|
|
path = os.path.join(app_cache, name)
|
|
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{name}"
|
|
data = self._download_cover(url, path)
|
|
if data:
|
|
self._clear_cover_missing(appid)
|
|
preview = self._preview_for(app_cache, path)
|
|
if preview:
|
|
self._serve_image(preview)
|
|
else:
|
|
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
|
return
|
|
|
|
self._mark_cover_missing(appid)
|
|
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 == "/api/backup":
|
|
self._backup()
|
|
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 _backup(self):
|
|
fd, tmp_path = tempfile.mkstemp(prefix="steambase-backup-", suffix=".db")
|
|
os.close(fd)
|
|
try:
|
|
source = db.connect(db.DEFAULT_DB)
|
|
try:
|
|
target = sqlite3.connect(tmp_path)
|
|
try:
|
|
source.backup(target)
|
|
finally:
|
|
target.close()
|
|
finally:
|
|
source.close()
|
|
with open(tmp_path, "rb") as fh:
|
|
data = fh.read()
|
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
|
self._send(
|
|
200, data, "application/octet-stream", cache=False,
|
|
extra_headers={
|
|
"Content-Disposition": f'attachment; filename="steambase-{stamp}.db"',
|
|
})
|
|
finally:
|
|
try:
|
|
os.remove(tmp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
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")}
|
|
signals = con.execute("""
|
|
SELECT (SELECT COUNT(*) FROM personal
|
|
WHERE COALESCE(favorite,0)=1 OR COALESCE(rating,0)>=8)
|
|
+ (SELECT COUNT(*) FROM reco_feedback) AS c
|
|
""").fetchone()["c"]
|
|
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,
|
|
"signals": signals,
|
|
})
|
|
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"):
|
|
match = fts_query(q("q"))
|
|
if match:
|
|
where.append("g.appid IN (SELECT appid FROM game_fts WHERE game_fts MATCH ?)")
|
|
params.append(match)
|
|
else:
|
|
where.append("0")
|
|
genres = multi_values(qs, "genre")
|
|
if genres:
|
|
placeholders = ",".join("?" * len(genres))
|
|
where.append(f"EXISTS (SELECT 1 FROM game_genres gg "
|
|
f"WHERE gg.appid=g.appid AND gg.genre IN ({placeholders}))")
|
|
params.extend(genres)
|
|
tags = multi_values(qs, "tag")
|
|
if tags:
|
|
placeholders = ",".join("?" * len(tags))
|
|
where.append(f"""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 IN ({placeholders}))""")
|
|
params.extend(tags)
|
|
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")
|
|
|
|
min_hours = number_param(qs, "min_hours")
|
|
max_hours = number_param(qs, "max_hours")
|
|
if min_hours is not None:
|
|
where.append("COALESCE(p.minutes,0) >= ?")
|
|
params.append(min_hours * 60)
|
|
if max_hours is not None:
|
|
where.append("COALESCE(p.minutes,0) <= ?")
|
|
params.append(max_hours * 60)
|
|
|
|
min_year = number_param(qs, "min_year", int)
|
|
max_year = number_param(qs, "max_year", int)
|
|
if min_year is not None or max_year is not None:
|
|
where.append("g.release_date GLOB '[0-9][0-9][0-9][0-9]*'")
|
|
if min_year is not None:
|
|
where.append("CAST(substr(g.release_date,1,4) AS INTEGER) >= ?")
|
|
params.append(min_year)
|
|
if max_year is not None:
|
|
where.append("CAST(substr(g.release_date,1,4) AS INTEGER) <= ?")
|
|
params.append(max_year)
|
|
|
|
min_review = number_param(qs, "min_review", int)
|
|
max_review = number_param(qs, "max_review", int)
|
|
if min_review is not None:
|
|
where.append("g.review_pct >= ?")
|
|
params.append(min_review)
|
|
if max_review is not None:
|
|
where.append("g.review_pct <= ?")
|
|
params.append(max_review)
|
|
|
|
duration = q("duration")
|
|
if duration == "short":
|
|
where.append("COALESCE(g.estimated_hours, 999) <= 8")
|
|
elif duration == "medium":
|
|
where.append("COALESCE(g.estimated_hours, 999) > 8 "
|
|
"AND COALESCE(g.estimated_hours, 999) <= 25")
|
|
elif duration == "long":
|
|
where.append("COALESCE(g.estimated_hours, 999) > 25")
|
|
|
|
sort = q("sort", "name")
|
|
columns = {
|
|
"name": "g.name COLLATE NOCASE",
|
|
"hours": "COALESCE(p.minutes,0)",
|
|
"review": "COALESCE(g.review_pct,0)",
|
|
"year": "COALESCE(g.release_date,'')",
|
|
"duration": "COALESCE(g.estimated_hours, 999)",
|
|
"favorite": "COALESCE(pe.favorite, 0)",
|
|
"genre": "(SELECT MIN(gg.genre) FROM game_genres gg WHERE gg.appid = g.appid)",
|
|
"added": "g.appid",
|
|
}
|
|
if sort not in columns:
|
|
sort = "name"
|
|
default_dir = "desc" if sort in ("hours", "review", "year", "favorite", "added") else "asc"
|
|
direction = q("dir", "").lower()
|
|
if direction not in ("asc", "desc"):
|
|
direction = default_dir
|
|
order = f"{columns[sort]} {direction.upper()}"
|
|
if sort != "name":
|
|
order += ", 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,
|
|
g.estimated_hours,
|
|
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,
|
|
g.estimated_hours,
|
|
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")
|
|
key = reco.mood_key(mood)
|
|
session = body.get("session")
|
|
if session not in {"short", "evening", "weekend"}:
|
|
session = None
|
|
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))),
|
|
feedback_key=key,
|
|
session=session,
|
|
)
|
|
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, "feedback_key": key})
|
|
finally:
|
|
con.close()
|
|
|
|
def _feedback(self, body):
|
|
try:
|
|
appid = int(body.get("appid"))
|
|
except (TypeError, ValueError):
|
|
self._error(400, "invalid appid")
|
|
return
|
|
verdict = body.get("verdict")
|
|
if verdict not in {"like", "dislike", "played", "ignore"}:
|
|
self._error(400, "unknown verdict")
|
|
return
|
|
|
|
con = connect()
|
|
try:
|
|
if not con.execute("SELECT 1 FROM games WHERE appid = ?", (appid,)).fetchone():
|
|
self._error(404, "unknown appid")
|
|
return
|
|
try:
|
|
mood = reco.load_mood(con, body.get("preset"), body.get("mood"))
|
|
except (KeyError, ValueError):
|
|
self._error(400, "unknown mood")
|
|
return
|
|
key = reco.mood_key(mood)
|
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
con.execute(
|
|
"""INSERT INTO reco_feedback (appid, mood_key, verdict, created_at)
|
|
VALUES (?, ?, ?, ?)
|
|
ON CONFLICT(appid, mood_key) DO UPDATE SET
|
|
verdict = excluded.verdict,
|
|
created_at = excluded.created_at""",
|
|
(appid, key, verdict, now))
|
|
if verdict == "played":
|
|
con.execute(
|
|
"INSERT OR IGNORE INTO personal (appid, status, updated_at) "
|
|
"VALUES (?, 'backlog', ?)", (appid, now))
|
|
con.execute(
|
|
"UPDATE personal SET status = 'played', updated_at = ? "
|
|
"WHERE appid = ? AND status = 'backlog'", (now, appid))
|
|
con.commit()
|
|
self._json({"saved": True, "appid": appid, "verdict": verdict, "key": key})
|
|
finally:
|
|
con.close()
|
|
|
|
def _update_personal_bulk(self, body):
|
|
appids = []
|
|
for value in body.get("appids") or []:
|
|
try:
|
|
appid = int(value)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if appid not in appids:
|
|
appids.append(appid)
|
|
if not appids:
|
|
self._error(400, "no appids")
|
|
return
|
|
|
|
sets, vals = [], []
|
|
if body.get("status") in STATUSES:
|
|
sets.append("status=?")
|
|
vals.append(body["status"])
|
|
if "favorite" in body:
|
|
sets.append("favorite=?")
|
|
vals.append(1 if body["favorite"] else 0)
|
|
if not sets:
|
|
self._error(400, "nothing to update")
|
|
return
|
|
|
|
con = connect()
|
|
try:
|
|
placeholders = ",".join("?" * len(appids))
|
|
rows = con.execute(
|
|
f"""SELECT g.appid, COALESCE(pe.status, 'backlog') AS status,
|
|
COALESCE(pe.favorite, 0) AS favorite
|
|
FROM games g LEFT JOIN personal pe ON pe.appid = g.appid
|
|
WHERE g.appid IN ({placeholders})""", appids).fetchall()
|
|
existing = [r["appid"] for r in rows]
|
|
if not existing:
|
|
self._error(404, "unknown appids")
|
|
return
|
|
previous = [{"appid": r["appid"], "status": r["status"],
|
|
"favorite": r["favorite"]} for r in rows]
|
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
con.executemany(
|
|
"INSERT OR IGNORE INTO personal (appid, status, updated_at) VALUES (?, 'backlog', ?)",
|
|
[(appid, now) for appid in existing])
|
|
sets.append("updated_at=?")
|
|
vals.append(now)
|
|
con.execute(
|
|
f"UPDATE personal SET {', '.join(sets)} "
|
|
f"WHERE appid IN ({','.join('?' * len(existing))})",
|
|
[*vals, *existing])
|
|
con.commit()
|
|
self._json({"updated": len(existing), "previous": previous})
|
|
finally:
|
|
con.close()
|
|
|
|
def _restore_personal(self, body):
|
|
items = []
|
|
for item in body.get("items") or []:
|
|
try:
|
|
appid = int(item.get("appid"))
|
|
except (AttributeError, TypeError, ValueError):
|
|
continue
|
|
if item.get("status") not in STATUSES:
|
|
continue
|
|
items.append((appid, item["status"], 1 if item.get("favorite") else 0))
|
|
if not items:
|
|
self._error(400, "no items")
|
|
return
|
|
|
|
con = connect()
|
|
try:
|
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
updated = 0
|
|
for appid, status, favorite in items:
|
|
if not con.execute("SELECT 1 FROM games WHERE appid = ?", (appid,)).fetchone():
|
|
continue
|
|
con.execute(
|
|
"INSERT OR IGNORE INTO personal (appid, status, updated_at) "
|
|
"VALUES (?, 'backlog', ?)", (appid, now))
|
|
con.execute(
|
|
"UPDATE personal SET status = ?, favorite = ?, updated_at = ? "
|
|
"WHERE appid = ?", (status, favorite, now, appid))
|
|
updated += 1
|
|
con.commit()
|
|
if not updated:
|
|
self._error(404, "unknown appids")
|
|
return
|
|
self._json({"updated": updated})
|
|
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
|
|
setup_logging()
|
|
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}/"
|
|
log_event("server_start", host=args.host, port=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
|
|
finally:
|
|
log_event("server_stop")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|