CI / test (push) Successful in 29s
Show lastlogoff as relative last-seen time, label friend_since as 'friends since YYYY', and show the Steam account creation year in the comparison header.
2026 lines
79 KiB
Python
2026 lines
79 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 csv
|
|
import importlib.util
|
|
import io
|
|
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_api
|
|
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
|
|
|
|
|
|
def _env_float(name, default):
|
|
try:
|
|
return float(os.environ.get(name, default))
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
COVER_MAINTENANCE_HOURS = _env_float("STEAMBASE_COVER_MAINTENANCE_HOURS", 24)
|
|
COVER_MAX_MB = _env_float("STEAMBASE_COVER_MAX_MB", 500)
|
|
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))
|
|
|
|
|
|
def cover_maintenance():
|
|
markers = covers.cleanup_negative_markers(CACHE_DIR, COVER_MISSING_TTL)
|
|
pruned = 0
|
|
left = None
|
|
if COVER_MAX_MB > 0:
|
|
result = covers.prune_cache(CACHE_DIR, int(COVER_MAX_MB * 1024 * 1024))
|
|
pruned = result["removed"]
|
|
left = result["bytes"]
|
|
log_event("cover_maintenance", markers_removed=markers, pruned=pruned)
|
|
return {"markers_removed": markers, "pruned": pruned, "bytes": left}
|
|
|
|
|
|
def cover_maintenance_loop():
|
|
while True:
|
|
try:
|
|
cover_maintenance()
|
|
except Exception as exc:
|
|
log_event("cover_maintenance_error", error=str(exc))
|
|
time.sleep(max(1.0, COVER_MAINTENANCE_HOURS) * 3600)
|
|
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)
|
|
|
|
|
|
def suspend_process(pid):
|
|
if os.name == "nt":
|
|
import ctypes
|
|
handle = ctypes.windll.kernel32.OpenProcess(0x0800, False, pid)
|
|
if not handle:
|
|
return False
|
|
try:
|
|
return ctypes.windll.ntdll.NtSuspendProcess(handle) == 0
|
|
finally:
|
|
ctypes.windll.kernel32.CloseHandle(handle)
|
|
import signal
|
|
os.kill(pid, signal.SIGSTOP)
|
|
return True
|
|
|
|
|
|
def resume_process(pid):
|
|
if os.name == "nt":
|
|
import ctypes
|
|
handle = ctypes.windll.kernel32.OpenProcess(0x0800, False, pid)
|
|
if not handle:
|
|
return False
|
|
try:
|
|
return ctypes.windll.ntdll.NtResumeProcess(handle) == 0
|
|
finally:
|
|
ctypes.windll.kernel32.CloseHandle(handle)
|
|
import signal
|
|
os.kill(pid, signal.SIGCONT)
|
|
return True
|
|
|
|
|
|
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, "paused": 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, "paused": 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 pause(self):
|
|
deadline = time.time() + 2
|
|
while True:
|
|
with self._lock:
|
|
if not self._state["running"] or self._state["paused"]:
|
|
return False
|
|
proc = self._proc
|
|
if proc is not None:
|
|
name = self._state["name"]
|
|
break
|
|
if time.time() >= deadline:
|
|
return False
|
|
time.sleep(0.02)
|
|
if not suspend_process(proc.pid):
|
|
return False
|
|
with self._lock:
|
|
self._state["paused"] = True
|
|
log_event("job_pause", name=name)
|
|
return True
|
|
|
|
def resume(self):
|
|
with self._lock:
|
|
if not self._state["running"] or not self._state["paused"] or not self._proc:
|
|
return False
|
|
proc = self._proc
|
|
name = self._state["name"]
|
|
if not resume_process(proc.pid):
|
|
return False
|
|
with self._lock:
|
|
self._state["paused"] = False
|
|
log_event("job_resume", name=name)
|
|
return True
|
|
|
|
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"]
|
|
was_paused = self._state["paused"]
|
|
break
|
|
if time.time() >= deadline:
|
|
return False
|
|
time.sleep(0.02)
|
|
if was_paused:
|
|
resume_process(proc.pid)
|
|
with self._lock:
|
|
self._state["paused"] = False
|
|
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["paused"] = 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"],
|
|
"hltb": {
|
|
"main": r["hltb_main"] if "hltb_main" in r.keys() else None,
|
|
"extra": r["hltb_extra"] if "hltb_extra" in r.keys() else None,
|
|
"complete": r["hltb_complete"] if "hltb_complete" in r.keys() else None,
|
|
} if "hltb_main" in r.keys() and r["hltb_main"] else None,
|
|
"installed": bool(r["installed"]),
|
|
"owned": r["owned"] if "owned" in r.keys() else None,
|
|
"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),
|
|
}
|
|
|
|
|
|
def scope_appids(con, scope, appid=None, tag=None):
|
|
"""Return appids for a series (by name) or a Steam tag."""
|
|
if scope == "series":
|
|
row = con.execute("SELECT appid, name FROM games WHERE appid = ? AND LOWER(type) = 'game'",
|
|
(appid,)).fetchone()
|
|
if not row:
|
|
return None
|
|
key = reco.series_key(row["name"])
|
|
return [r["appid"] for r in con.execute(
|
|
"SELECT appid, name FROM games WHERE LOWER(type) = 'game'")
|
|
if reco.series_key(r["name"]) == key]
|
|
if scope == "tag":
|
|
if not tag:
|
|
return None
|
|
return [r["appid"] for r in con.execute(
|
|
"""SELECT DISTINCT g.appid
|
|
FROM games g
|
|
JOIN game_tags gt ON gt.appid = g.appid
|
|
JOIN tag_names tn ON tn.tag_id = gt.tag_id
|
|
WHERE LOWER(g.type) = 'game' AND tn.name = ? COLLATE NOCASE""", (tag,))]
|
|
return None
|
|
|
|
|
|
def game_filters(qs):
|
|
"""Shared WHERE/ORDER construction for the library and export."""
|
|
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)
|
|
ownership = q("ownership")
|
|
if ownership == "owned":
|
|
where.append("o.owned = 1")
|
|
elif ownership == "shared":
|
|
where.append("o.owned = 0")
|
|
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"
|
|
return where, params, order, q
|
|
|
|
|
|
MOOD_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,39}$")
|
|
|
|
|
|
def normalize_mood_payload(body):
|
|
"""Validate and normalize a mood profile payload."""
|
|
name = str(body.get("name") or "").strip().lower()
|
|
if name in db.MOOD_PRESETS:
|
|
raise ValueError("builtin profile")
|
|
if not MOOD_NAME_RE.match(name):
|
|
raise ValueError("invalid name")
|
|
description = str(body.get("description") or "").strip()[:200]
|
|
genres = []
|
|
for genre in body.get("genres") or []:
|
|
value = str(genre).strip()
|
|
if value and value not in genres:
|
|
genres.append(value)
|
|
tags = {}
|
|
for tag, weight in (body.get("tags") or {}).items():
|
|
try:
|
|
value = float(weight)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
tag = str(tag).strip()
|
|
if tag and 0.1 <= value <= 5.0:
|
|
tags[tag] = round(value, 2)
|
|
tags = dict(list(tags.items())[:30])
|
|
if not genres and not tags:
|
|
raise ValueError("empty profile")
|
|
return {"name": name, "description": description, "genres": genres, "tags": tags}
|
|
|
|
|
|
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_DELETE(self):
|
|
parsed = urllib.parse.urlparse(self.path)
|
|
path = parsed.path
|
|
try:
|
|
if path.startswith("/api/moods/"):
|
|
name = urllib.parse.unquote(path.rsplit("/", 1)[1])
|
|
self._delete_mood(name)
|
|
else:
|
|
self._error(404, "not found")
|
|
except Exception as exc:
|
|
log_event("http_error", method="DELETE", path=path, error=str(exc))
|
|
self._error(500, str(exc))
|
|
|
|
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/moods":
|
|
self._save_mood(self._body())
|
|
elif path == "/api/moods/import":
|
|
self._import_moods(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 == "/api/personal/hide-scope":
|
|
self._hide_scope(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/pause":
|
|
self._json({"paused": JOBS.pause()})
|
|
elif path == "/api/job/resume":
|
|
self._json({"paused": JOBS.resume()})
|
|
elif path == "/api/job/retry":
|
|
self._json({"started": JOBS.retry()})
|
|
elif path == "/api/hltb":
|
|
self._start_hltb(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:
|
|
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/export":
|
|
self._export(qs)
|
|
elif path == "/api/hltb/status":
|
|
self._hltb_status(qs)
|
|
elif path == "/api/moods":
|
|
self._moods()
|
|
elif path == "/api/compare":
|
|
self._compare(qs)
|
|
elif path == "/api/activity":
|
|
self._activity(qs)
|
|
elif path == "/api/steam/friends":
|
|
self._steam_friends()
|
|
elif path.startswith("/api/steam/friends/"):
|
|
tail = path.rsplit("/", 1)[1]
|
|
if not (tail.isdigit() and len(tail) == 17):
|
|
self._error(400, "invalid steamid")
|
|
else:
|
|
self._steam_friend(tail)
|
|
elif path.startswith("/api/steam/achievements/"):
|
|
tail = path.rsplit("/", 1)[1]
|
|
if not tail.isdigit():
|
|
self._error(400, "invalid appid")
|
|
else:
|
|
self._steam_achievements(int(tail))
|
|
elif path == "/api/moods/export":
|
|
self._export_moods(qs)
|
|
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"]
|
|
hltb_checked = con.execute(
|
|
"""SELECT COUNT(*) FROM games WHERE LOWER(type)='game'
|
|
AND hltb_checked_at IS NOT NULL""").fetchone()[0]
|
|
hltb_matched = con.execute(
|
|
"""SELECT COUNT(*) FROM games WHERE LOWER(type)='game'
|
|
AND hltb_match = 1""").fetchone()[0]
|
|
ownership = con.execute(
|
|
"""SELECT COALESCE(SUM(CASE WHEN o.owned=1 THEN 1 ELSE 0 END), 0) AS owned,
|
|
COALESCE(SUM(CASE WHEN o.owned=0 THEN 1 ELSE 0 END), 0) AS shared
|
|
FROM game_ownership o JOIN games g ON g.appid=o.appid
|
|
WHERE LOWER(g.type)='game'""").fetchone()
|
|
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, "hltb_checked": hltb_checked,
|
|
"hltb_matched": hltb_matched,
|
|
"owned": ownership["owned"], "shared": ownership["shared"],
|
|
"steam_api": bool(steam_api.has_key() and steam_api.steam_id(con)),
|
|
})
|
|
finally:
|
|
con.close()
|
|
|
|
def _games(self, qs):
|
|
where, params, order, q = game_filters(qs)
|
|
|
|
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
|
|
LEFT JOIN game_ownership o ON o.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, g.hltb_main, g.hltb_extra, g.hltb_complete,
|
|
COALESCE(p.minutes,0) minutes, COALESCE(i.installed,0) installed,
|
|
COALESCE(pe.status,'backlog') status, pe.rating,
|
|
COALESCE(pe.favorite,0) favorite, pe.notes, o.owned
|
|
{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 _hltb_status(self, qs):
|
|
def q(name, default=None):
|
|
return qs.get(name, [default])[0]
|
|
|
|
where = ["LOWER(g.type) = 'game'", "g.hltb_checked_at IS NOT NULL"]
|
|
params = []
|
|
status = q("status")
|
|
if status == "match":
|
|
where.append("g.hltb_match = 1")
|
|
elif status == "miss":
|
|
where.append("COALESCE(g.hltb_match, 0) = 0")
|
|
if q("q"):
|
|
where.append("g.name LIKE ? COLLATE NOCASE")
|
|
params.append(f"%{q('q')}%")
|
|
try:
|
|
limit = max(1, min(500, int(q("limit", "100") or 100)))
|
|
offset = max(0, int(q("offset", "0") or 0))
|
|
except (TypeError, ValueError):
|
|
self._error(400, "invalid pagination")
|
|
return
|
|
|
|
base = f"FROM games g WHERE {' AND '.join(where)}"
|
|
con = connect()
|
|
try:
|
|
total = con.execute(f"SELECT COUNT(*) c {base}", params).fetchone()["c"]
|
|
checked = con.execute(
|
|
"""SELECT COUNT(*) FROM games WHERE LOWER(type)='game'
|
|
AND hltb_checked_at IS NOT NULL""").fetchone()[0]
|
|
matched = con.execute(
|
|
"""SELECT COUNT(*) FROM games WHERE LOWER(type)='game'
|
|
AND hltb_match = 1""").fetchone()[0]
|
|
rows = con.execute(
|
|
f"""SELECT g.appid, g.name, g.hltb_match, g.hltb_main, g.hltb_extra,
|
|
g.hltb_complete, g.hltb_id, g.hltb_checked_at, g.hltb_updated_at
|
|
{base} ORDER BY g.hltb_checked_at DESC, g.name
|
|
LIMIT ? OFFSET ?""", [*params, limit, offset]).fetchall()
|
|
items = [{
|
|
"appid": row["appid"],
|
|
"name": row["name"],
|
|
"status": "match" if row["hltb_match"] else "miss",
|
|
"main": row["hltb_main"],
|
|
"extra": row["hltb_extra"],
|
|
"complete": row["hltb_complete"],
|
|
"hltb_id": row["hltb_id"],
|
|
"checked_at": row["hltb_checked_at"],
|
|
"updated_at": row["hltb_updated_at"],
|
|
} for row in rows]
|
|
self._json({"total": total, "checked": checked, "matched": matched,
|
|
"limit": limit, "offset": offset, "items": items})
|
|
finally:
|
|
con.close()
|
|
|
|
def _export(self, qs):
|
|
fmt = (qs.get("format", ["csv"])[0] or "csv").lower()
|
|
if fmt not in ("csv", "json"):
|
|
self._error(400, "unknown format")
|
|
return
|
|
where, params, order, _q = game_filters(qs)
|
|
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
|
|
LEFT JOIN game_ownership o ON o.appid=g.appid
|
|
WHERE {' AND '.join(where)}"""
|
|
con = connect()
|
|
try:
|
|
rows = con.execute(
|
|
f"""SELECT g.appid, g.name, g.type, g.release_date, g.review_pct, g.metacritic,
|
|
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, o.owned
|
|
{base} ORDER BY {order}""", params).fetchall()
|
|
ids = [row["appid"] for row in rows]
|
|
tags = game_tags_map(con, ids)
|
|
genres = game_genres_map(con, ids)
|
|
finally:
|
|
con.close()
|
|
|
|
records = []
|
|
for row in rows:
|
|
records.append({
|
|
"appid": row["appid"],
|
|
"name": row["name"],
|
|
"type": row["type"],
|
|
"year": release_year(row["release_date"]),
|
|
"release_date": row["release_date"],
|
|
"review": row["review_pct"],
|
|
"metacritic": row["metacritic"],
|
|
"hours": round((row["minutes"] or 0) / 60, 1),
|
|
"duration": row["estimated_hours"],
|
|
"status": row["status"],
|
|
"rating": row["rating"],
|
|
"favorite": bool(row["favorite"]),
|
|
"installed": bool(row["installed"]),
|
|
"owned": row["owned"],
|
|
"size_gb": round((row["size_bytes"] or 0) / (1024 ** 3), 2),
|
|
"last_played": row["last_played"],
|
|
"genres": genres.get(row["appid"], []),
|
|
"tags": tags.get(row["appid"], []),
|
|
})
|
|
|
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
|
filename = f"steambase-library-{stamp}.{fmt}"
|
|
if fmt == "json":
|
|
data = json.dumps(records, ensure_ascii=False, indent=2).encode("utf-8")
|
|
content_type = "application/json; charset=utf-8"
|
|
else:
|
|
columns = ["appid", "name", "type", "year", "release_date", "review", "metacritic",
|
|
"hours", "duration", "status", "rating", "favorite", "installed",
|
|
"size_gb", "last_played", "genres", "tags"]
|
|
buffer = io.StringIO()
|
|
writer = csv.writer(buffer)
|
|
writer.writerow(columns)
|
|
for record in records:
|
|
writer.writerow([
|
|
record["appid"], record["name"], record["type"], record["year"],
|
|
record["release_date"], record["review"], record["metacritic"],
|
|
record["hours"], record["duration"], record["status"], record["rating"],
|
|
1 if record["favorite"] else 0, 1 if record["installed"] else 0,
|
|
record["size_gb"], record["last_played"],
|
|
"|".join(record["genres"]), "|".join(record["tags"]),
|
|
])
|
|
data = buffer.getvalue().encode("utf-8-sig")
|
|
content_type = "text/csv; charset=utf-8"
|
|
self._send(200, data, content_type, cache=False,
|
|
extra_headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
|
|
|
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.parent_appid,
|
|
g.estimated_hours, g.hltb_main, g.hltb_extra, g.hltb_complete,
|
|
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,
|
|
o.owned, o.checked_at AS ownership_checked_at
|
|
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_ownership o ON o.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"],
|
|
"ownership_checked_at": r["ownership_checked_at"],
|
|
"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)
|
|
item["addons"] = [
|
|
{"appid": row["appid"], "name": row["name"], "type": row["type"]}
|
|
for row in con.execute(
|
|
"""SELECT appid, name, type FROM games
|
|
WHERE parent_appid = ? ORDER BY type, name""", (appid,))
|
|
]
|
|
item["parent"] = None
|
|
if r["parent_appid"]:
|
|
parent = con.execute(
|
|
"SELECT appid, name, type FROM games WHERE appid = ?",
|
|
(r["parent_appid"],)).fetchone()
|
|
if parent:
|
|
item["parent"] = {
|
|
"appid": parent["appid"], "name": parent["name"],
|
|
"type": parent["type"],
|
|
}
|
|
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"]),
|
|
"builtin": r["name"] in db.MOOD_PRESETS}
|
|
for r in con.execute("SELECT * FROM moods ORDER BY name")]
|
|
self._json({"moods": moods})
|
|
finally:
|
|
con.close()
|
|
|
|
def _steam_friends(self):
|
|
con = connect()
|
|
try:
|
|
if not steam_api.has_key():
|
|
self._error(400, "Steam API key is not configured")
|
|
return
|
|
steamid = steam_api.steam_id(con)
|
|
if not steamid:
|
|
self._error(400, "SteamID is not known; run import_steam.py")
|
|
return
|
|
try:
|
|
friends = steam_api.friends(steamid)
|
|
ids = [item.get("steamid") for item in friends if item.get("steamid")]
|
|
summaries = steam_api.player_summaries(ids) if ids else []
|
|
except steam_api.SteamApiError as exc:
|
|
if exc.status in (401, 403):
|
|
self._json({"friends": [], "total": 0, "private": True})
|
|
return
|
|
self._error(502, str(exc))
|
|
return
|
|
by_id = {str(player.get("steamid")): player for player in summaries}
|
|
items = []
|
|
for item in friends:
|
|
sid = str(item.get("steamid") or "")
|
|
if not sid:
|
|
continue
|
|
player = by_id.get(sid) or {}
|
|
items.append({
|
|
"steamid": sid,
|
|
"name": player.get("personaname") or sid,
|
|
"avatar": player.get("avatarmedium") or player.get("avatar") or "",
|
|
"profile_url": player.get("profileurl")
|
|
or f"https://steamcommunity.com/profiles/{sid}",
|
|
"state": player.get("personastate"),
|
|
"lastlogoff": player.get("lastlogoff"),
|
|
"created": player.get("timecreated"),
|
|
"friend_since": item.get("friend_since"),
|
|
})
|
|
items.sort(key=lambda row: row["name"].lower())
|
|
self._json({"friends": items, "total": len(items)})
|
|
finally:
|
|
con.close()
|
|
|
|
def _steam_friend(self, friend_id):
|
|
con = connect()
|
|
try:
|
|
if not steam_api.has_key():
|
|
self._error(400, "Steam API key is not configured")
|
|
return
|
|
try:
|
|
games = steam_api.owned_games(friend_id)
|
|
summaries = steam_api.player_summaries([friend_id])
|
|
except steam_api.SteamApiError as exc:
|
|
self._error(502, str(exc))
|
|
return
|
|
local = {
|
|
row["appid"]: row for row in con.execute(
|
|
"""SELECT g.appid, g.name, COALESCE(pe.status, 'backlog') AS status,
|
|
COALESCE(p.minutes, 0) AS minutes,
|
|
COALESCE(i.installed, 0) AS installed
|
|
FROM games g
|
|
LEFT JOIN personal pe ON pe.appid = g.appid
|
|
LEFT JOIN game_playtime p ON p.appid = g.appid
|
|
LEFT JOIN game_install i ON i.appid = g.appid
|
|
WHERE LOWER(g.type) = 'game'""")
|
|
}
|
|
common, friend_only = [], []
|
|
for game in games:
|
|
appid = game.get("appid")
|
|
if not appid:
|
|
continue
|
|
hours = round((game.get("playtime_forever") or 0) / 60, 1)
|
|
if appid in local:
|
|
common.append({
|
|
"appid": appid, "name": local[appid]["name"],
|
|
"status": local[appid]["status"], "friend_hours": hours,
|
|
"local_hours": round((local[appid]["minutes"] or 0) / 60, 1),
|
|
"installed": bool(local[appid]["installed"]),
|
|
})
|
|
else:
|
|
friend_only.append({
|
|
"appid": appid, "name": game.get("name") or str(appid),
|
|
"friend_hours": hours,
|
|
})
|
|
common.sort(key=lambda row: row["friend_hours"], reverse=True)
|
|
friend_only.sort(key=lambda row: row["friend_hours"], reverse=True)
|
|
player = summaries[0] if summaries else {}
|
|
self._json({
|
|
"steamid": friend_id,
|
|
"name": player.get("personaname") or friend_id,
|
|
"avatar": player.get("avatarmedium") or player.get("avatar") or "",
|
|
"profile_url": player.get("profileurl")
|
|
or f"https://steamcommunity.com/profiles/{friend_id}",
|
|
"state": player.get("personastate"),
|
|
"lastlogoff": player.get("lastlogoff"),
|
|
"created": player.get("timecreated"),
|
|
"total_games": len(games),
|
|
"common_count": len(common),
|
|
"friend_only_count": len(friend_only),
|
|
"common": common[:500],
|
|
"friend_only": friend_only[:500],
|
|
})
|
|
finally:
|
|
con.close()
|
|
|
|
def _steam_achievements(self, appid):
|
|
con = connect()
|
|
try:
|
|
if not steam_api.has_key():
|
|
self._error(400, "Steam API key is not configured")
|
|
return
|
|
steamid = steam_api.steam_id(con)
|
|
if not steamid:
|
|
self._error(400, "SteamID is not known; run import_steam.py")
|
|
return
|
|
try:
|
|
data = steam_api.achievements(appid, steamid)
|
|
except steam_api.SteamApiError as exc:
|
|
self._error(502, str(exc))
|
|
return
|
|
if data is None:
|
|
self._error(404, "no achievements for this game")
|
|
return
|
|
self._json(data)
|
|
finally:
|
|
con.close()
|
|
|
|
def _activity(self, qs):
|
|
year = (qs.get("year", [""])[0] or "").strip()
|
|
if year and (len(year) != 4 or not year.isdigit()):
|
|
self._error(400, "invalid year")
|
|
return
|
|
con = connect()
|
|
try:
|
|
years = [r["year"] for r in con.execute(
|
|
"""SELECT DISTINCT substr(last_played, 1, 4) AS year
|
|
FROM game_playtime
|
|
WHERE last_played IS NOT NULL AND last_played <> ''
|
|
AND length(last_played) >= 4
|
|
ORDER BY year DESC""")]
|
|
if not year:
|
|
year = years[0] if years else str(datetime.now(timezone.utc).year)
|
|
rows = con.execute(
|
|
"""SELECT substr(p.last_played, 1, 10) AS day,
|
|
COUNT(*) AS games,
|
|
COALESCE(SUM(p.minutes), 0) / 60.0 AS hours
|
|
FROM game_playtime p JOIN games g ON g.appid = p.appid
|
|
WHERE LOWER(g.type) = 'game'
|
|
AND substr(p.last_played, 1, 4) = ?
|
|
GROUP BY day ORDER BY day""", (year,)).fetchall()
|
|
days = [{"date": r["day"], "games": r["games"], "hours": round(r["hours"], 1)}
|
|
for r in rows]
|
|
self._json({
|
|
"year": year,
|
|
"years": years,
|
|
"days": days,
|
|
"total_games": sum(day["games"] for day in days),
|
|
"total_hours": round(sum(day["hours"] for day in days), 1),
|
|
"max_games": max((day["games"] for day in days), default=0),
|
|
})
|
|
finally:
|
|
con.close()
|
|
|
|
def _compare(self, qs):
|
|
a = (qs.get("a", [""])[0] or "").strip()
|
|
b = (qs.get("b", [""])[0] or "").strip()
|
|
if not a or not b:
|
|
self._error(400, "two presets required")
|
|
return
|
|
try:
|
|
limit = max(1, min(100, int(qs.get("limit", ["20"])[0])))
|
|
except (TypeError, ValueError):
|
|
limit = 20
|
|
con = connect()
|
|
try:
|
|
db.seed_moods(con)
|
|
try:
|
|
mood_a = reco.load_mood(con, preset=a)
|
|
mood_b = reco.load_mood(con, preset=b)
|
|
except KeyError:
|
|
self._error(404, "unknown preset")
|
|
return
|
|
_, results_a = reco.recommend(con, mood_a, limit=limit)
|
|
_, results_b = reco.recommend(con, mood_b, limit=limit)
|
|
set_a = {g["appid"] for g in results_a}
|
|
set_b = {g["appid"] for g in results_b}
|
|
common_ids = set_a & set_b
|
|
union = set_a | set_b
|
|
|
|
def brief(game):
|
|
return {"appid": game["appid"], "name": game["name"], "score": game["score"]}
|
|
|
|
self._json({
|
|
"a": a, "b": b, "limit": limit,
|
|
"jaccard": round(len(common_ids) / len(union), 4) if union else 0.0,
|
|
"common": [brief(g) for g in results_a if g["appid"] in common_ids],
|
|
"only_a": [brief(g) for g in results_a if g["appid"] not in set_b],
|
|
"only_b": [brief(g) for g in results_b if g["appid"] not in set_a],
|
|
})
|
|
finally:
|
|
con.close()
|
|
|
|
def _save_mood(self, body):
|
|
try:
|
|
mood = normalize_mood_payload(body)
|
|
except ValueError as exc:
|
|
self._error(400, str(exc))
|
|
return
|
|
con = connect()
|
|
try:
|
|
self._store_mood(con, mood)
|
|
self._json({"mood": mood, "builtin": False})
|
|
finally:
|
|
con.close()
|
|
|
|
@staticmethod
|
|
def _store_mood(con, mood):
|
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
con.execute(
|
|
"""INSERT INTO moods (name, description, genres, tags, updated_at)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT(name) DO UPDATE SET
|
|
description = excluded.description,
|
|
genres = excluded.genres,
|
|
tags = excluded.tags,
|
|
updated_at = excluded.updated_at""",
|
|
(mood["name"], mood["description"], json.dumps(mood["genres"]),
|
|
json.dumps(mood["tags"]), now))
|
|
con.commit()
|
|
|
|
def _export_moods(self, qs):
|
|
custom_only = (qs.get("custom", ["0"])[0] or "").lower() in ("1", "true", "yes")
|
|
con = connect()
|
|
try:
|
|
moods = [{"name": r["name"], "description": r["description"],
|
|
"genres": json.loads(r["genres"]), "tags": json.loads(r["tags"]),
|
|
"builtin": r["name"] in db.MOOD_PRESETS}
|
|
for r in con.execute("SELECT * FROM moods ORDER BY name")]
|
|
if custom_only:
|
|
moods = [mood for mood in moods if not mood["builtin"]]
|
|
self._json({
|
|
"version": 1,
|
|
"exported_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
"moods": moods,
|
|
})
|
|
finally:
|
|
con.close()
|
|
|
|
def _import_moods(self, body):
|
|
items = body.get("moods") if isinstance(body, dict) else body
|
|
if not isinstance(items, list):
|
|
self._error(400, "expected list of moods")
|
|
return
|
|
imported = updated = 0
|
|
skipped = []
|
|
con = connect()
|
|
try:
|
|
existing = {r["name"] for r in con.execute("SELECT name FROM moods")}
|
|
for item in items:
|
|
if not isinstance(item, dict):
|
|
skipped.append({"name": None, "reason": "invalid item"})
|
|
continue
|
|
try:
|
|
mood = normalize_mood_payload(item)
|
|
except ValueError as exc:
|
|
skipped.append({"name": item.get("name"), "reason": str(exc)})
|
|
continue
|
|
if mood["name"] in existing:
|
|
updated += 1
|
|
else:
|
|
imported += 1
|
|
existing.add(mood["name"])
|
|
self._store_mood(con, mood)
|
|
self._json({"imported": imported, "updated": updated, "skipped": skipped})
|
|
finally:
|
|
con.close()
|
|
|
|
def _delete_mood(self, name):
|
|
name = (name or "").strip().lower()
|
|
if name in db.MOOD_PRESETS:
|
|
self._error(400, "builtin profile")
|
|
return
|
|
con = connect()
|
|
try:
|
|
cursor = con.execute("DELETE FROM moods WHERE name = ?", (name,))
|
|
con.commit()
|
|
if not cursor.rowcount:
|
|
self._error(404, "unknown profile")
|
|
return
|
|
self._json({"deleted": True})
|
|
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"}
|
|
if body.get("include_played"):
|
|
allowed.add("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
|
|
time_of_day = body.get("time_of_day")
|
|
if time_of_day not in {"morning", "day", "evening", "night"}:
|
|
time_of_day = None
|
|
taste_profile = body.get("taste_profile") or None
|
|
if taste_profile not in reco.TASTE_PROFILES and taste_profile is not None:
|
|
self._error(400, "unknown taste profile")
|
|
return
|
|
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,
|
|
time_of_day=time_of_day,
|
|
taste_profile=taste_profile,
|
|
)
|
|
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 _hide_scope(self, body):
|
|
scope = body.get("scope")
|
|
if scope not in ("series", "tag"):
|
|
self._error(400, "unknown scope")
|
|
return
|
|
appid = tag = None
|
|
try:
|
|
if body.get("appid") is not None:
|
|
appid = int(body["appid"])
|
|
except (TypeError, ValueError):
|
|
self._error(400, "invalid appid")
|
|
return
|
|
if scope == "series" and appid is None:
|
|
self._error(400, "invalid appid")
|
|
return
|
|
if scope == "tag":
|
|
tag = (body.get("tag") or "").strip()
|
|
if not tag:
|
|
self._error(400, "empty tag")
|
|
return
|
|
|
|
con = connect()
|
|
try:
|
|
ids = scope_appids(con, scope, appid=appid, tag=tag)
|
|
if ids is None:
|
|
self._error(404, "unknown appid")
|
|
return
|
|
if not ids:
|
|
self._error(404, "no games")
|
|
return
|
|
placeholders = ",".join("?" * len(ids))
|
|
rows = con.execute(
|
|
f"""SELECT appid, COALESCE(status, 'backlog') status,
|
|
COALESCE(favorite, 0) favorite
|
|
FROM personal WHERE appid IN ({placeholders})""", ids).fetchall()
|
|
previous_map = {r["appid"]: {"appid": r["appid"], "status": r["status"],
|
|
"favorite": r["favorite"]} for r in rows}
|
|
previous = [previous_map.get(appid_value,
|
|
{"appid": appid_value, "status": "backlog",
|
|
"favorite": 0}) for appid_value in ids]
|
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
con.executemany(
|
|
"INSERT OR IGNORE INTO personal (appid, status, updated_at) "
|
|
"VALUES (?, 'backlog', ?)", [(value, now) for value in ids])
|
|
con.execute(
|
|
f"UPDATE personal SET status = 'ignore', updated_at = ? "
|
|
f"WHERE appid IN ({placeholders})", [now, *ids])
|
|
con.commit()
|
|
self._json({"updated": len(ids), "appids": ids, "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 _start_hltb(self, body):
|
|
if importlib.util.find_spec("howlongtobeatpy") is None:
|
|
self._error(400, "howlongtobeatpy не установлен: pip install -r requirements-hltb.txt")
|
|
return
|
|
try:
|
|
limit = max(1, min(1000, int(body.get("limit", 200))))
|
|
except (TypeError, ValueError):
|
|
self._error(400, "invalid limit")
|
|
return
|
|
script = os.path.join(BASE, "tools", "fetch_hltb.py")
|
|
args = [script, "--limit", str(limit)]
|
|
if body.get("refresh"):
|
|
args.append("--refresh")
|
|
if body.get("retry_missed"):
|
|
args.append("--retry-missed")
|
|
if not JOBS.start("hltb", args):
|
|
self._error(409, "another job is running")
|
|
return
|
|
self._json({"started": True, "limit": limit})
|
|
|
|
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)
|
|
if COVER_MAINTENANCE_HOURS > 0:
|
|
threading.Thread(target=cover_maintenance_loop, daemon=True).start()
|
|
|
|
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()
|