feat: hide games by series or tag
CI / test (push) Successful in 6m46s

This commit is contained in:
strsv committed 2026-11-06 20:58:25 +03:00
1 parent 419bd12dec
commit 710a9026df
12 files changed
+229 -11

No files matched your search

+77
View File
@@ -458,6 +458,29 @@ def serialize(r, tags, genres, details):
}
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):
@@ -618,6 +641,8 @@ class Handler(BaseHTTPRequestHandler):
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())
@@ -1208,6 +1233,58 @@ class Handler(BaseHTTPRequestHandler):
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 []:
+49 -1
View File
@@ -38,6 +38,7 @@ const state = {
selected: new Set(),
recommendContext: null,
lastReco: null,
itemsById: new Map(),
};
const $ = (sel) => document.querySelector(sel);
@@ -713,7 +714,8 @@ function applySavedView(view) {
/* ---------- bulk selection ---------- */
const BULK_CONTROLS = ["#bulkStatus", "#bulkFavorite", "#bulkUnfavorite", "#bulkHide", "#bulkClear"];
const BULK_CONTROLS = ["#bulkStatus", "#bulkFavorite", "#bulkUnfavorite", "#bulkHide",
"#bulkSeries", "#bulkTag", "#bulkClear"];
function updateBulkBar() {
const count = state.selected.size;
@@ -767,6 +769,30 @@ async function bulkUpdate(fields) {
}
}
function firstSelectedGame() {
const appid = state.selected.values().next().value;
return appid == null ? null : state.itemsById.get(appid);
}
async function hideScope(body) {
try {
const result = await api("/api/personal/hide-scope", {
method: "POST",
body: JSON.stringify(body),
});
clearSelection();
await loadGames(true);
await loadMeta();
const previous = result.previous || [];
toast(`Скрыто игр: ${result.updated}`, previous.length ? {
label: "отменить",
onClick: () => restoreBulk(previous),
} : null);
} catch (err) {
toast(err.message);
}
}
async function restoreBulk(items) {
try {
await api("/api/personal/restore", {
@@ -815,6 +841,7 @@ async function loadGames(reset = true) {
if (reset) {
state.page = 1;
state.total = 0;
state.itemsById.clear();
grid.innerHTML = tableMode
? '<div class="empty">загрузка…</div>'
: skeletons(12);
@@ -823,6 +850,7 @@ async function loadGames(reset = true) {
const params = filterParams();
params.set("page", state.page);
const data = await api(`/api/games?${params}`);
for (const game of data.items) state.itemsById.set(game.appid, game);
if (reset) grid.innerHTML = "";
if (!data.items.length && reset) {
grid.innerHTML = '<div class="empty">ничего не нашлось — ослабь фильтры</div>';
@@ -1388,6 +1416,26 @@ $("#bulkStatus").addEventListener("change", (event) => {
$("#bulkFavorite").addEventListener("click", () => bulkUpdate({ favorite: true }));
$("#bulkUnfavorite").addEventListener("click", () => bulkUpdate({ favorite: false }));
$("#bulkHide").addEventListener("click", () => bulkUpdate({ status: "ignore" }));
$("#bulkSeries").addEventListener("click", () => {
const game = firstSelectedGame();
if (!game) {
toast("Сначала выберите игру");
return;
}
if (!confirm(`Скрыть все игры серии «${game.name}»? Отменить можно в уведомлении.`)) return;
hideScope({ scope: "series", appid: game.appid });
});
$("#bulkTag").addEventListener("click", () => {
const game = firstSelectedGame();
if (!game) {
toast("Сначала выберите игру");
return;
}
const tag = (prompt("Тег для скрытия:", (game.tags || [])[0] || "") || "").trim();
if (!tag) return;
if (!confirm(`Скрыть все игры с тегом «${tag}»? Отменить можно в уведомлении.`)) return;
hideScope({ scope: "tag", tag });
});
$("#bulkClear").addEventListener("click", clearSelection);
updateBulkBar();
+2
View File
@@ -236,6 +236,8 @@ try {
<button id="bulkFavorite" class="ghost" type="button">в избранное</button>
<button id="bulkUnfavorite" class="ghost" type="button">из избранного</button>
<button id="bulkHide" class="ghost" type="button">скрыть</button>
<button id="bulkSeries" class="ghost" type="button" title="Скрыть все игры серии первой выбранной">скрыть серию</button>
<button id="bulkTag" class="ghost" type="button" title="Скрыть все игры с тегом">скрыть тег</button>
<button id="bulkClear" class="link" type="button">снять выбор</button>
</div>
<div id="grid" class="grid"></div>