This commit is contained in:
1 parent
2828ec48c8
commit
88c4beabcd
10 files changed
+234
-98
No files matched your search
+177
-92
@@ -7,6 +7,8 @@ Binds to 127.0.0.1 by default: no auth, do not expose it to the internet.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -456,6 +458,103 @@ def serialize(r, tags, genres, details):
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "SteamBase/1.0"
|
||||
|
||||
@@ -710,6 +809,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._meta()
|
||||
elif path == "/api/games":
|
||||
self._games(qs)
|
||||
elif path == "/api/export":
|
||||
self._export(qs)
|
||||
elif path == "/api/moods":
|
||||
self._moods()
|
||||
elif path == "/api/descriptions":
|
||||
@@ -815,98 +916,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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"
|
||||
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)))
|
||||
@@ -939,6 +949,81 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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
|
||||
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
|
||||
{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"]),
|
||||
"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:
|
||||
|
||||
@@ -1346,6 +1346,14 @@ function applyLayout(mode) {
|
||||
button.setAttribute("aria-pressed", String(mode !== "grid"));
|
||||
}
|
||||
|
||||
$("#exportLibrary").addEventListener("click", () => {
|
||||
const params = filterParams();
|
||||
params.delete("page");
|
||||
params.delete("per_page");
|
||||
params.set("format", "csv");
|
||||
window.location.href = `/api/export?${params}`;
|
||||
});
|
||||
|
||||
$("#layoutToggle").addEventListener("click", () => {
|
||||
const current = grid.dataset.layout || "grid";
|
||||
const mode = current === "grid" ? "list" : current === "list" ? "table" : "grid";
|
||||
|
||||
@@ -217,6 +217,8 @@ try {
|
||||
</select>
|
||||
<button id="layoutToggle" class="ghost toolbar-select" type="button"
|
||||
aria-pressed="false" title="Компактный список" aria-keyshortcuts="g">список</button>
|
||||
<button id="exportLibrary" class="ghost toolbar-select" type="button"
|
||||
title="Экспорт текущего фильтра в CSV">экспорт</button>
|
||||
<button id="selectMode" class="ghost toolbar-select" type="button">выбрать</button>
|
||||
<span class="count" id="count" aria-live="polite"></span>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user