diff --git a/tests/test_api.py b/tests/test_api.py index f0e6345..b22df19 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -12,6 +12,7 @@ import urllib.error import urllib.parse import urllib.request from http.server import ThreadingHTTPServer +from types import SimpleNamespace from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -834,6 +835,47 @@ class ApiTests(unittest.TestCase): data = self.post("/api/hltb", {"limit": 5}, expect=400) self.assertIn("howlongtobeatpy", data["error"]) + def test_hltb_manual_match(self): + entry = SimpleNamespace(main_story=10.0, main_extra=12.0, + completionist=15.0, game_id=999) + + class FakeSearch: + def search_from_id(self, hltb_id): + return entry if hltb_id == 999 else None + + try: + with mock.patch.object(server.importlib.util, "find_spec", return_value=object()), \ + mock.patch.object(server.fetch_hltb, "HowLongToBeat", + return_value=FakeSearch()): + data = self.post("/api/hltb/match", {"appid": 2, "hltb_id": 999}) + self.assertEqual(data["estimated_hours"], 10.0) + self.assertEqual(self.post("/api/hltb/match", { + "appid": 2, "hltb_id": 0}, expect=400)["error"], "invalid HLTB id") + self.post("/api/hltb/match", {"appid": 2, "hltb_id": 123}, expect=404) + + con = db.connect(self.db_path) + try: + row = con.execute( + "SELECT hltb_main, hltb_match, hltb_id FROM games WHERE appid = 2" + ).fetchone() + finally: + con.close() + self.assertEqual(row["hltb_main"], 10.0) + self.assertEqual(row["hltb_match"], 1) + self.assertEqual(row["hltb_id"], 999) + finally: + con = db.connect(self.db_path) + try: + con.execute( + """UPDATE games SET hltb_main = NULL, hltb_extra = NULL, + hltb_complete = NULL, hltb_id = NULL, + hltb_checked_at = '2026-01-02', hltb_match = 0, + hltb_updated_at = NULL, estimated_hours = 10 + WHERE appid = 2""") + con.commit() + finally: + con.close() + if __name__ == "__main__": unittest.main() diff --git a/web/server.py b/web/server.py index c12c922..980f9c3 100644 --- a/web/server.py +++ b/web/server.py @@ -40,6 +40,7 @@ for stream in (sys.stdout, sys.stderr): import check_updates import covers import db +import fetch_hltb import reco import steam_api import steam_source @@ -821,6 +822,8 @@ class Handler(BaseHTTPRequestHandler): self._json({"started": JOBS.retry()}) elif path == "/api/hltb": self._start_hltb(self._body()) + elif path == "/api/hltb/match": + self._hltb_match(self._body()) elif path == "/api/refresh": body = self._body() mode = body.get("mode", "incremental") @@ -1957,6 +1960,62 @@ class Handler(BaseHTTPRequestHandler): finally: con.close() + def _hltb_match(self, body): + if importlib.util.find_spec("howlongtobeatpy") is None: + self._error(400, "howlongtobeatpy не установлен: pip install -r requirements-hltb.txt") + return + try: + appid = int(body.get("appid")) + except (TypeError, ValueError): + self._error(400, "invalid appid") + return + try: + hltb_id = int(body.get("hltb_id")) + except (TypeError, ValueError): + self._error(400, "invalid HLTB id") + return + if hltb_id <= 0: + self._error(400, "invalid HLTB id") + return + try: + entry = fetch_hltb.HowLongToBeat().search_from_id(hltb_id) + except Exception as exc: + self._error(502, f"HLTB: {exc}") + return + if not entry: + self._error(404, "HLTB game not found") + return + main_hours = fetch_hltb.positive(getattr(entry, "main_story", None)) + extra_hours = fetch_hltb.positive(getattr(entry, "main_extra", None)) + complete_hours = fetch_hltb.positive(getattr(entry, "completionist", None)) + best = main_hours or extra_hours or complete_hours + if not best: + self._error(422, "no playtime for this HLTB game") + return + + 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( + """UPDATE games SET hltb_main = ?, hltb_extra = ?, hltb_complete = ?, + hltb_id = ?, hltb_checked_at = ?, hltb_match = 1, + hltb_updated_at = ?, estimated_hours = ? + WHERE appid = ?""", + (main_hours, extra_hours, complete_hours, hltb_id, now, now, + best, appid)) + con.commit() + self._json({ + "appid": appid, "hltb_id": hltb_id, + "main": main_hours, "extra": extra_hours, "complete": complete_hours, + "estimated_hours": best, + }) + 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") diff --git a/web/static/app.js b/web/static/app.js index 5570663..da57aa6 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -1122,10 +1122,12 @@ function hltbDate(value) { } function hltbRowHtml(item) { - const hours = (value) => value ? (Math.round(value * 10) / 10).toString() : "—"; + const hours = (value) => value ? (Math.round(value * 10) / 10).toString() : "-"; + const manual = item.status === "match" ? "" : + ` `; return ` - ${esc(item.name)} + ${esc(item.name)}${manual} ${item.status === "match" ? "совпало" : "не найдено"} ${hours(item.main)} ${hours(item.extra)} @@ -1176,6 +1178,51 @@ $("#hltbFilter").addEventListener("change", () => loadHltb(true)); $("#hltbReload").addEventListener("click", () => loadHltb(true)); $("#hltbMore").addEventListener("click", () => loadHltb(false)); +function openHltbMatch(appid, name) { + const dialog = $("#hltbMatchDialog"); + $("#hltbMatchName").textContent = name; + $("#hltbMatchId").value = ""; + dialog.dataset.appid = appid; + dialog.showModal(); + $("#hltbMatchId").focus(); +} + +$("#hltbBody").addEventListener("click", (event) => { + const button = event.target.closest(".hltb-manual"); + if (!button) return; + event.preventDefault(); + event.stopPropagation(); + openHltbMatch(button.dataset.appid, button.dataset.name); +}, true); + +$("#hltbMatchForm").addEventListener("submit", async (event) => { + event.preventDefault(); + const dialog = $("#hltbMatchDialog"); + const appid = Number(dialog.dataset.appid); + const hltbId = Number($("#hltbMatchId").value); + if (!Number.isInteger(hltbId) || hltbId <= 0) { + toast("Введи HLTB ID"); + return; + } + const button = $("#hltbMatchSave"); + button.disabled = true; + try { + const data = await api("/api/hltb/match", { + method: "POST", + body: JSON.stringify({ appid, hltb_id: hltbId }), + }); + dialog.close(); + toast(`HLTB: ${data.estimated_hours} ч`); + await loadHltb(true); + await loadMeta(); + } catch (err) { + toast(err.message); + } finally { + button.disabled = false; + } +}); +$("#hltbMatchCancel").addEventListener("click", () => $("#hltbMatchDialog").close()); + async function runRecommend(scroll = true) { const text = $("#moodText").value.trim(); if (!state.preset && !text) { diff --git a/web/static/index.html b/web/static/index.html index 28a9394..f8d1387 100644 --- a/web/static/index.html +++ b/web/static/index.html @@ -510,6 +510,20 @@ try { + +
+

Сопоставить с HLTB

+

+ + +
+
+
diff --git a/web/static/styles.css b/web/static/styles.css index 78bc390..30cf2f2 100644 --- a/web/static/styles.css +++ b/web/static/styles.css @@ -1152,6 +1152,11 @@ html[data-theme="light"] .game-table tbody tr:hover { background: rgba(23, 32, 5 overscroll-behavior: contain; } .modal::backdrop { background: rgba(4, 6, 10, .72); backdrop-filter: blur(6px); } +.modal.small { width: min(420px, calc(100vw - 36px)); } +.hltb-match-form { display: flex; flex-direction: column; gap: 10px; padding: 20px; } +.hltb-match-form h2 { margin: 0; font-size: 18px; } +.hltb-match-form label { display: flex; flex-direction: column; gap: 6px; font-size: 12px; color: var(--muted); } +.modal-actions { display: flex; align-items: center; gap: 10px; } .modal-grid { display: grid;