feat: add manual HLTB matching

Allow setting an HLTB ID for missed games via POST /api/hltb/match and a small modal on the HLTB page.
This commit is contained in:
strsv committed 2026-11-07 05:03:56 +03:00
1 parent 92c4c62ca9
commit 6644a94d8c
5 files changed
+169 -2

No files matched your search

+42
View File
@@ -12,6 +12,7 @@ import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
from http.server import ThreadingHTTPServer from http.server import ThreadingHTTPServer
from types import SimpleNamespace
from unittest import mock from unittest import mock
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 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) data = self.post("/api/hltb", {"limit": 5}, expect=400)
self.assertIn("howlongtobeatpy", data["error"]) 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+59
View File
@@ -40,6 +40,7 @@ for stream in (sys.stdout, sys.stderr):
import check_updates import check_updates
import covers import covers
import db import db
import fetch_hltb
import reco import reco
import steam_api import steam_api
import steam_source import steam_source
@@ -821,6 +822,8 @@ class Handler(BaseHTTPRequestHandler):
self._json({"started": JOBS.retry()}) self._json({"started": JOBS.retry()})
elif path == "/api/hltb": elif path == "/api/hltb":
self._start_hltb(self._body()) self._start_hltb(self._body())
elif path == "/api/hltb/match":
self._hltb_match(self._body())
elif path == "/api/refresh": elif path == "/api/refresh":
body = self._body() body = self._body()
mode = body.get("mode", "incremental") mode = body.get("mode", "incremental")
@@ -1957,6 +1960,62 @@ class Handler(BaseHTTPRequestHandler):
finally: finally:
con.close() 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): def _start_hltb(self, body):
if importlib.util.find_spec("howlongtobeatpy") is None: if importlib.util.find_spec("howlongtobeatpy") is None:
self._error(400, "howlongtobeatpy не установлен: pip install -r requirements-hltb.txt") self._error(400, "howlongtobeatpy не установлен: pip install -r requirements-hltb.txt")
+49 -2
View File
@@ -1122,10 +1122,12 @@ function hltbDate(value) {
} }
function hltbRowHtml(item) { 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" ? "" :
` <button class="link hltb-manual" type="button" data-appid="${item.appid}" data-name="${esc(item.name)}">сопоставить</button>`;
return ` return `
<tr data-appid="${item.appid}" tabindex="0" role="button" aria-label="Открыть ${esc(item.name)}"> <tr data-appid="${item.appid}" tabindex="0" role="button" aria-label="Открыть ${esc(item.name)}">
<td class="hltb-name">${esc(item.name)}</td> <td class="hltb-name">${esc(item.name)}${manual}</td>
<td><span class="status-chip ${item.status === "match" ? "st-playing" : "st-ignore"}">${item.status === "match" ? "совпало" : "не найдено"}</span></td> <td><span class="status-chip ${item.status === "match" ? "st-playing" : "st-ignore"}">${item.status === "match" ? "совпало" : "не найдено"}</span></td>
<td>${hours(item.main)}</td> <td>${hours(item.main)}</td>
<td>${hours(item.extra)}</td> <td>${hours(item.extra)}</td>
@@ -1176,6 +1178,51 @@ $("#hltbFilter").addEventListener("change", () => loadHltb(true));
$("#hltbReload").addEventListener("click", () => loadHltb(true)); $("#hltbReload").addEventListener("click", () => loadHltb(true));
$("#hltbMore").addEventListener("click", () => loadHltb(false)); $("#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) { async function runRecommend(scroll = true) {
const text = $("#moodText").value.trim(); const text = $("#moodText").value.trim();
if (!state.preset && !text) { if (!state.preset && !text) {
+14
View File
@@ -510,6 +510,20 @@ try {
</section> </section>
</main> </main>
<dialog id="hltbMatchDialog" class="modal small" aria-labelledby="hltbMatchTitle">
<form class="hltb-match-form" id="hltbMatchForm">
<h2 id="hltbMatchTitle">Сопоставить с HLTB</h2>
<p class="muted" id="hltbMatchName"></p>
<label>HLTB ID
<input id="hltbMatchId" type="number" min="1" placeholder="например, 11097">
</label>
<div class="modal-actions">
<button type="submit" class="primary" id="hltbMatchSave">Сохранить</button>
<button type="button" class="link" id="hltbMatchCancel">отмена</button>
</div>
</form>
</dialog>
<dialog id="modal" class="modal" aria-labelledby="modalTitle"> <dialog id="modal" class="modal" aria-labelledby="modalTitle">
<div id="modalBody"></div> <div id="modalBody"></div>
</dialog> </dialog>
+5
View File
@@ -1152,6 +1152,11 @@ html[data-theme="light"] .game-table tbody tr:hover { background: rgba(23, 32, 5
overscroll-behavior: contain; overscroll-behavior: contain;
} }
.modal::backdrop { background: rgba(4, 6, 10, .72); backdrop-filter: blur(6px); } .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 { .modal-grid {
display: grid; display: grid;