Track VERSION, compare it with Gitea tags via git ls-remote (API fallback), expose GET /api/update and a Services card with the current version.
This commit is contained in:
1 parent
eb8a9bb57b
commit
f1149974aa
15 files changed
+390
-2
No files matched your search
@@ -105,6 +105,7 @@ python tools/check_links.py
|
||||
python -m py_compile tools/*.py web/server.py
|
||||
python -m unittest discover -v
|
||||
python tools/check_links.py
|
||||
python tools/check_updates.py
|
||||
python tools/recommend.py --list-presets
|
||||
Invoke-RestMethod http://127.0.0.1:8765/api/meta
|
||||
Invoke-RestMethod "http://127.0.0.1:8765/api/games?per_page=3"
|
||||
|
||||
@@ -162,6 +162,10 @@
|
||||
- Личные и семейные игры: `tools/check_ownership.py` сверяет локальную библиотеку
|
||||
с `GetOwnedGames` и пишет `game_ownership` (схема v10); фильтр «владение»,
|
||||
бейдж «семейная», `owned`/`shared` в `/api/meta` и экспорте.
|
||||
- Проверка обновлений по тегам Gitea: файл `VERSION`, `tools/check_updates.py`,
|
||||
`GET /api/update` и карточка «Обновления» на вкладке «Сервисы»; теги читаются
|
||||
через `git ls-remote` (работает для приватного репозитория) с фолбэком на API.
|
||||
Текущая версия показывается сразу (из `/api/meta`), без автоскачивания.
|
||||
- Сортировка таблицы по жанру и избранному; опции в селекторе сортировки.
|
||||
- Демо-скриншоты текущего UI в README.
|
||||
|
||||
|
||||
@@ -49,6 +49,8 @@
|
||||
в карточке и переход к родительской игре;
|
||||
- **Личные и семейные игры**: `tools/check_ownership.py` помечает игры вне
|
||||
списка владения, фильтр «владение» и бейдж «семейная»;
|
||||
- **Проверка обновлений**: `tools/check_updates.py` и карточка «Обновления» на
|
||||
вкладке «Сервисы» сравнивают `VERSION` с тегами Gitea (без автоскачивания);
|
||||
- **Сервисы**: отдельная вкладка для описаний, перевода, обновления БД и бэкапа;
|
||||
- **Описания**: Steam Store API (русский с фолбэком на английский), восстановление для
|
||||
региональных изданий, перевод на русский.
|
||||
|
||||
@@ -109,6 +109,8 @@
|
||||
блок «Дополнения» в карточке, `import_steam.py --refresh-parents`.
|
||||
- Личные/семейные игры: `game_ownership` (схема v10), `tools/check_ownership.py`,
|
||||
фильтр «владение» и бейдж «семейная».
|
||||
- Проверка обновлений: `VERSION`, `tools/check_updates.py` (git/API), `/api/update`,
|
||||
карточка «Обновления» на вкладке «Сервисы».
|
||||
- Разнообразие выдачи: штраф за одну серию и сильное пересечение тегов.
|
||||
- Избранное и оценки 8+/10 дают бонус похожим по тегам играм.
|
||||
- Оценка длительности (`estimated_hours`) по жанрам/тегам; фильтр `duration` и сортировка.
|
||||
@@ -319,6 +321,7 @@ Invoke-RestMethod http://127.0.0.1:8765/api/meta
|
||||
57. Вкладка «Друзья» и сравнение библиотек.
|
||||
58. Связи DLC/саундтреков/тулз с базовой игрой (`parent_appid`).
|
||||
59. Личные/семейные игры (`game_ownership`).
|
||||
60. Проверка обновлений по тегам Gitea.
|
||||
|
||||
Дальше — новые версии `appinfo.vdf`, все теги Steam, portable-сборка, лицензия
|
||||
и ручной screen reader.
|
||||
|
||||
+2
-1
@@ -81,6 +81,7 @@
|
||||
- вкладка «Друзья»: список, сравнение библиотек и общие игры;
|
||||
- связи DLC/саундтреков/тулз с базовой игрой (`parent_appid`);
|
||||
- личные/семейные игры (`game_ownership`, фильтр «владение», бейдж);
|
||||
- проверка обновлений по тегам Gitea (`VERSION`, `check_updates.py`, `/api/update`);
|
||||
- пауза/продолжение фоновых задач отдельно от полной отмены;
|
||||
- служебная вкладка HLTB со статусом, данными и датами проверки;
|
||||
- документация и AGENTS.md.
|
||||
@@ -203,7 +204,7 @@
|
||||
|
||||
- [ ] Portable-сборка (PyInstaller) или zip «распаковал и запустил».
|
||||
- [ ] Релизы в Gitea с артефактами и changelog.
|
||||
- [ ] Проверка обновлений по тегам (без автоскачивания).
|
||||
- [x] Проверка обновлений по тегам (без автоскачивания).
|
||||
- [ ] MkDocs-сайт из `docs/`.
|
||||
- [ ] Шаблоны issue/PR, labels, roadmap в Issues.
|
||||
- [ ] Выбрать и добавить лицензию.
|
||||
|
||||
+17
@@ -28,6 +28,7 @@
|
||||
| POST | `/api/recommend` | подбор игр под настроение |
|
||||
| GET | `/api/compare?a=...&b=...` | сравнение двух пресетов (Jaccard) |
|
||||
| GET | `/api/activity?year=YYYY` | активность по дням (последние запуски) |
|
||||
| GET | `/api/update` | проверка новых тегов Gitea (без автоскачивания) |
|
||||
| GET | `/api/steam/achievements/{appid}` | достижения и прогресс (нужен ключ) |
|
||||
| GET | `/api/steam/friends` | список друзей Steam (нужен ключ) |
|
||||
| GET | `/api/steam/friends/{steamid}` | сравнение библиотек с другом |
|
||||
@@ -62,6 +63,7 @@
|
||||
"hltb_checked": 120,
|
||||
"hltb_matched": 98,
|
||||
"owned": 1620, "shared": 411,
|
||||
"version": "1.0.0",
|
||||
"steam_api": true
|
||||
}
|
||||
```
|
||||
@@ -395,6 +397,21 @@ DELETE → `{"deleted": true}`.
|
||||
Ответы кэшируются в памяти на 15 минут. Без ключа → 400, у игры нет статистики →
|
||||
404, ошибка Steam → 502. Ключ никогда не логируется и не возвращается клиенту.
|
||||
|
||||
## `GET /api/update`
|
||||
|
||||
Сравнивает `VERSION` с тегами репозитория. По умолчанию теги читаются через
|
||||
`git ls-remote --tags origin` (работает и для приватного репозитория), с
|
||||
фолбэком на Gitea API. `?refresh=1` сбрасывает часовой кэш.
|
||||
|
||||
```json
|
||||
{"current": "1.0.0", "latest": "v1.1.0", "update_available": true,
|
||||
"url": "https://gitea.strsv.ru/strsv/SteamBase/src/tag/v1.1.0",
|
||||
"checked_at": "2026-11-07T00:00:00+00:00", "tags": ["v1.1.0"]}
|
||||
```
|
||||
|
||||
Если тегов нет: `latest: null`, `update_available: false`. Ошибка сети → 502.
|
||||
Автоскачивания и автообновления нет.
|
||||
|
||||
## `GET /api/steam/friends` и `/api/steam/friends/{steamid}`
|
||||
|
||||
Список друзей (SteamID64, имя, аватар, профиль, статус) требует ключ и известный
|
||||
|
||||
+2
-1
@@ -184,11 +184,12 @@ python tools/recommend.py --preset adventure-rpg-party --limit 3
|
||||
|
||||
## Релиз
|
||||
|
||||
1. Обновите `CHANGELOG.md`.
|
||||
1. Обновите `VERSION` (SemVer) и `CHANGELOG.md`.
|
||||
2. Проверьте `README.md` и `docs/`.
|
||||
3. Убедитесь, что `steam.db`/`cache/` не попали в git (`git status`).
|
||||
4. Проставьте тег, например `v1.0.0`.
|
||||
5. Опубликуйте в Gitea.
|
||||
6. Проверьте: `python tools/check_updates.py` (должен увидеть новый тег).
|
||||
|
||||
## Полезные ссылки
|
||||
|
||||
|
||||
@@ -399,6 +399,11 @@ API может меняться. Без пакета проект работае
|
||||
100%, HLTB ID, даты проверки и обновления. Есть поиск, фильтр по статусу и
|
||||
«показать ещё».
|
||||
|
||||
На вкладке **Сервисы** есть карточка **Обновления**: кнопка «проверить» сравнивает
|
||||
`VERSION` с тегами Gitea через `git ls-remote` (или API) и показывает, доступна ли
|
||||
новая версия. Ничего не скачивается и не устанавливается автоматически; проверка
|
||||
кэшируется на час, кнопка всегда запрашивает заново.
|
||||
|
||||
### Друзья
|
||||
|
||||
Вкладка **Друзья** (нужен ключ Steam Web API) показывает список друзей с аватарами
|
||||
|
||||
@@ -190,6 +190,7 @@ class ApiTests(unittest.TestCase):
|
||||
self.assertEqual(data["hltb_matched"], 1)
|
||||
self.assertEqual(data["owned"], 1)
|
||||
self.assertEqual(data["shared"], 1)
|
||||
self.assertRegex(data["version"], r"^\d+\.\d+\.\d+")
|
||||
self.assertFalse(data["steam_api"])
|
||||
genres = {g["name"]: g["count"] for g in data["genres"]}
|
||||
self.assertEqual(genres["RPG"], 2)
|
||||
@@ -572,6 +573,15 @@ class ApiTests(unittest.TestCase):
|
||||
mock.patch.object(server.steam_api, "achievements", return_value=None):
|
||||
self.get("/api/steam/achievements/1", expect=404)
|
||||
|
||||
def test_update_check(self):
|
||||
payload = {"current": "1.0.0", "latest": "v1.1.0", "update_available": True,
|
||||
"url": "https://example/tag", "checked_at": "2026-01-01", "tags": []}
|
||||
with mock.patch.object(server.check_updates, "check", return_value=payload):
|
||||
self.assertEqual(self.get("/api/update"), payload)
|
||||
with mock.patch.object(server.check_updates, "check",
|
||||
side_effect=RuntimeError("offline")):
|
||||
self.assertEqual(self.get("/api/update", expect=502)["error"], "offline")
|
||||
|
||||
def test_activity_heatmap(self):
|
||||
data = self.get("/api/activity?year=2026")
|
||||
self.assertEqual(data["year"], "2026")
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Tests for the read-only Gitea tag update check."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.error
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
|
||||
import check_updates
|
||||
|
||||
|
||||
class VersionTests(unittest.TestCase):
|
||||
def test_parse_version(self):
|
||||
self.assertEqual(check_updates.parse_version("v1.2.3"), (1, 2, 3))
|
||||
self.assertEqual(check_updates.parse_version("1.2.3"), (1, 2, 3))
|
||||
self.assertEqual(check_updates.parse_version("v1.2.3-beta"), (1, 2, 3))
|
||||
self.assertIsNone(check_updates.parse_version("nightly"))
|
||||
|
||||
def test_latest_version(self):
|
||||
name, parsed = check_updates.latest_version(
|
||||
["v1.0.0", "v1.10.0", "v1.2.0", "bad"])
|
||||
self.assertEqual(name, "v1.10.0")
|
||||
self.assertEqual(parsed, (1, 10, 0))
|
||||
|
||||
def test_read_version(self):
|
||||
with tempfile.NamedTemporaryFile("w", delete=False, encoding="utf-8") as handle:
|
||||
handle.write("2.3.4\n")
|
||||
path = handle.name
|
||||
try:
|
||||
self.assertEqual(check_updates.read_version(path), "2.3.4")
|
||||
finally:
|
||||
os.unlink(path)
|
||||
self.assertEqual(check_updates.read_version("missing-file"), "0.0.0")
|
||||
|
||||
|
||||
class FetchTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
check_updates.clear_cache()
|
||||
self.addCleanup(check_updates.clear_cache)
|
||||
|
||||
def test_fetch_tags(self):
|
||||
payload = [{"name": "v1.1.0"}, {"name": "v1.0.0"}]
|
||||
|
||||
class Response:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
def read(self):
|
||||
return json.dumps(payload).encode("utf-8")
|
||||
|
||||
with mock.patch("urllib.request.urlopen", return_value=Response()):
|
||||
self.assertEqual(check_updates.fetch_tags_api("https://example/api"),
|
||||
["v1.1.0", "v1.0.0"])
|
||||
|
||||
def test_fetch_error(self):
|
||||
error = urllib.error.HTTPError("https://example", 500, "err", {}, None)
|
||||
with mock.patch("urllib.request.urlopen", side_effect=error):
|
||||
with self.assertRaises(RuntimeError):
|
||||
check_updates.fetch_tags_api("https://example/api")
|
||||
|
||||
def test_fetch_tags_git(self):
|
||||
stdout = (
|
||||
"abc\trefs/tags/v1.0.0\n"
|
||||
"def\trefs/tags/v1.2.0\n"
|
||||
"def\trefs/tags/v1.2.0^{}\n"
|
||||
"ghi\trefs/heads/main\n")
|
||||
completed = mock.Mock(returncode=0, stdout=stdout, stderr="")
|
||||
with mock.patch("subprocess.run", return_value=completed):
|
||||
self.assertEqual(check_updates.fetch_tags_git("origin"),
|
||||
["v1.0.0", "v1.2.0"])
|
||||
|
||||
def test_fetch_tags_falls_back_to_api(self):
|
||||
with mock.patch.object(check_updates, "fetch_tags_git",
|
||||
side_effect=RuntimeError("no git")), \
|
||||
mock.patch.object(check_updates, "fetch_tags_api",
|
||||
return_value=["v1.0.0"]) as api:
|
||||
self.assertEqual(check_updates.fetch_tags(method="auto"), ["v1.0.0"])
|
||||
self.assertEqual(api.call_count, 1)
|
||||
|
||||
def test_update_available(self):
|
||||
with mock.patch.object(check_updates, "fetch_tags",
|
||||
return_value=["v1.0.0", "v1.2.0"]):
|
||||
result = check_updates.check(current="1.1.0")
|
||||
self.assertTrue(result["update_available"])
|
||||
self.assertEqual(result["latest"], "v1.2.0")
|
||||
self.assertEqual(result["current"], "1.1.0")
|
||||
self.assertTrue(result["url"].endswith("/src/tag/v1.2.0"))
|
||||
|
||||
def test_actual_version(self):
|
||||
with mock.patch.object(check_updates, "fetch_tags",
|
||||
return_value=["v1.0.0", "v1.2.0"]):
|
||||
result = check_updates.check(current="1.2.0")
|
||||
self.assertFalse(result["update_available"])
|
||||
|
||||
def test_no_tags(self):
|
||||
with mock.patch.object(check_updates, "fetch_tags", return_value=[]):
|
||||
result = check_updates.check(current="1.0.0")
|
||||
self.assertIsNone(result["latest"])
|
||||
self.assertFalse(result["update_available"])
|
||||
|
||||
def test_cache(self):
|
||||
with mock.patch.object(check_updates, "fetch_tags",
|
||||
return_value=["v1.0.0"]) as fetch:
|
||||
check_updates.check(current="1.0.0")
|
||||
check_updates.check(current="1.0.0")
|
||||
self.assertEqual(fetch.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Check the Gitea repository for newer tags (no auto-download).
|
||||
|
||||
python tools/check_updates.py
|
||||
python tools/check_updates.py --json
|
||||
python tools/check_updates.py --api https://gitea.example/api/v1/repos/owner/repo
|
||||
|
||||
The local version comes from the VERSION file. Only tags like ``v1.2.3`` or
|
||||
``1.2.3`` are compared; the check is read-only.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
VERSION_FILE = os.path.join(BASE_DIR, "VERSION")
|
||||
DEFAULT_API = "https://gitea.strsv.ru/api/v1/repos/strsv/SteamBase"
|
||||
DEFAULT_WEB = "https://gitea.strsv.ru/strsv/SteamBase"
|
||||
DEFAULT_REMOTE = "origin"
|
||||
DEFAULT_TIMEOUT = 15
|
||||
CACHE_TTL = 3600
|
||||
VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$")
|
||||
|
||||
_cache = {}
|
||||
|
||||
|
||||
def read_version(path=VERSION_FILE):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
value = handle.read().strip()
|
||||
except OSError:
|
||||
return "0.0.0"
|
||||
return value or "0.0.0"
|
||||
|
||||
|
||||
def parse_version(text):
|
||||
match = VERSION_RE.match((text or "").strip())
|
||||
if not match:
|
||||
return None
|
||||
return tuple(int(part) for part in match.groups())
|
||||
|
||||
|
||||
def fetch_tags_git(remote=DEFAULT_REMOTE, timeout=DEFAULT_TIMEOUT):
|
||||
"""Tags via the configured git remote (works for private repositories)."""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["git", "ls-remote", "--tags", remote],
|
||||
cwd=BASE_DIR, capture_output=True, text=True, timeout=timeout,
|
||||
encoding="utf-8", errors="replace")
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise RuntimeError(f"git ls-remote failed: {type(exc).__name__}") from None
|
||||
if proc.returncode != 0:
|
||||
detail = (proc.stderr or "").strip()[:200] or str(proc.returncode)
|
||||
raise RuntimeError(f"git ls-remote failed: {detail}")
|
||||
tags = []
|
||||
for line in proc.stdout.splitlines():
|
||||
parts = line.split("\t")
|
||||
if len(parts) != 2 or not parts[1].startswith("refs/tags/"):
|
||||
continue
|
||||
name = parts[1][len("refs/tags/"):]
|
||||
if name.endswith("^{}"):
|
||||
continue
|
||||
if name not in tags:
|
||||
tags.append(name)
|
||||
return tags
|
||||
|
||||
|
||||
def fetch_tags_api(api_url, timeout=DEFAULT_TIMEOUT):
|
||||
url = api_url.rstrip("/") + "/tags?limit=50"
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "SteamBase/1.0"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
data = json.load(response)
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise RuntimeError(f"Gitea API HTTP {exc.code}") from None
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise RuntimeError(f"Gitea API request failed: {type(exc).__name__}") from None
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("unexpected Gitea API response")
|
||||
return [str(item.get("name") or "") for item in data if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_tags(api_url=DEFAULT_API, remote=DEFAULT_REMOTE,
|
||||
timeout=DEFAULT_TIMEOUT, method="auto"):
|
||||
"""Fetch tags via git (default) and fall back to the Gitea API."""
|
||||
if method in ("auto", "git"):
|
||||
try:
|
||||
return fetch_tags_git(remote, timeout)
|
||||
except RuntimeError:
|
||||
if method == "git":
|
||||
raise
|
||||
if method in ("auto", "api"):
|
||||
return fetch_tags_api(api_url, timeout)
|
||||
raise RuntimeError(f"unknown update method: {method}")
|
||||
|
||||
|
||||
def latest_version(tags):
|
||||
best = None
|
||||
best_name = None
|
||||
for tag in tags:
|
||||
parsed = parse_version(tag)
|
||||
if parsed and (best is None or parsed > best):
|
||||
best = parsed
|
||||
best_name = tag
|
||||
return best_name, best
|
||||
|
||||
|
||||
def check(api_url=DEFAULT_API, web_url=DEFAULT_WEB, current=None,
|
||||
remote=DEFAULT_REMOTE, method="auto",
|
||||
timeout=DEFAULT_TIMEOUT, ttl=CACHE_TTL):
|
||||
current = current or read_version()
|
||||
cache_key = (api_url, remote, method, current, timeout)
|
||||
now = time.time()
|
||||
cached = _cache.get(cache_key)
|
||||
if cached and now - cached[0] < ttl:
|
||||
return cached[1]
|
||||
tags = fetch_tags(api_url, remote, timeout, method)
|
||||
latest, latest_parsed = latest_version(tags)
|
||||
current_parsed = parse_version(current)
|
||||
update_available = bool(
|
||||
latest_parsed and current_parsed and latest_parsed > current_parsed)
|
||||
result = {
|
||||
"current": current,
|
||||
"latest": latest,
|
||||
"update_available": update_available,
|
||||
"url": f"{web_url.rstrip('/')}/src/tag/{latest}" if latest else None,
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"tags": tags[:20],
|
||||
}
|
||||
_cache[cache_key] = (now, result)
|
||||
return result
|
||||
|
||||
|
||||
def clear_cache():
|
||||
_cache.clear()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Check Gitea tags for a newer version")
|
||||
ap.add_argument("--api", default=DEFAULT_API)
|
||||
ap.add_argument("--web", default=DEFAULT_WEB)
|
||||
ap.add_argument("--remote", default=DEFAULT_REMOTE)
|
||||
ap.add_argument("--method", choices=("auto", "git", "api"), default="auto")
|
||||
ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT)
|
||||
ap.add_argument("--json", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
try:
|
||||
result = check(api_url=args.api, web_url=args.web, remote=args.remote,
|
||||
method=args.method, timeout=args.timeout)
|
||||
except RuntimeError as exc:
|
||||
print(f"Update check failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
print(f"Current: {result['current']}")
|
||||
print(f"Latest: {result['latest'] or 'нет тегов'}")
|
||||
if result["update_available"]:
|
||||
print(f"Доступно обновление: {result['url']}")
|
||||
else:
|
||||
print("Обновлений нет")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -37,6 +37,7 @@ for stream in (sys.stdout, sys.stderr):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import check_updates
|
||||
import covers
|
||||
import db
|
||||
import reco
|
||||
@@ -1014,6 +1015,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._compare(qs)
|
||||
elif path == "/api/activity":
|
||||
self._activity(qs)
|
||||
elif path == "/api/update":
|
||||
self._update(qs)
|
||||
elif path == "/api/steam/friends":
|
||||
self._steam_friends()
|
||||
elif path.startswith("/api/steam/friends/"):
|
||||
@@ -1141,6 +1144,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
"signals": signals, "hltb_checked": hltb_checked,
|
||||
"hltb_matched": hltb_matched,
|
||||
"owned": ownership["owned"], "shared": ownership["shared"],
|
||||
"version": check_updates.read_version(),
|
||||
"steam_api": bool(steam_api.has_key() and steam_api.steam_id(con)),
|
||||
})
|
||||
finally:
|
||||
@@ -1508,6 +1512,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _update(self, qs):
|
||||
if qs.get("refresh", ["0"])[0] in ("1", "true", "yes"):
|
||||
check_updates.clear_cache()
|
||||
try:
|
||||
data = check_updates.check()
|
||||
except RuntimeError as exc:
|
||||
self._error(502, str(exc))
|
||||
return
|
||||
self._json(data)
|
||||
|
||||
def _activity(self, qs):
|
||||
year = (qs.get("year", [""])[0] or "").strip()
|
||||
if year and (len(year) != 4 or not year.isdigit()):
|
||||
|
||||
@@ -590,6 +590,7 @@ function bindMulti(container, key, summary) {
|
||||
async function loadMeta() {
|
||||
const meta = await api("/api/meta");
|
||||
state.meta = meta;
|
||||
$("#updateCurrent").textContent = meta.version || "—";
|
||||
$("#stats").innerHTML = [
|
||||
`<span class="stat"><b>${meta.total}</b> игр</span>`,
|
||||
`<span class="stat"><b>${meta.played}</b> играл</span>`,
|
||||
@@ -2261,6 +2262,27 @@ $("#hltbRefreshAll").addEventListener("click", () => {
|
||||
$("#backup").addEventListener("click", () => {
|
||||
window.location.href = "/api/backup";
|
||||
});
|
||||
$("#checkUpdates").addEventListener("click", async () => {
|
||||
const button = $("#checkUpdates");
|
||||
button.disabled = true;
|
||||
$("#updateNote").textContent = "проверка…";
|
||||
try {
|
||||
const data = await api("/api/update?refresh=1");
|
||||
$("#updateCurrent").textContent = data.current || "—";
|
||||
if (!data.latest) {
|
||||
$("#updateNote").textContent = "в репозитории пока нет тегов";
|
||||
} else if (data.update_available) {
|
||||
$("#updateNote").innerHTML =
|
||||
`доступна ${esc(data.latest)} · <a href="${esc(data.url)}" target="_blank" rel="noopener">открыть</a>`;
|
||||
} else {
|
||||
$("#updateNote").textContent = `актуально (последний тег ${data.latest})`;
|
||||
}
|
||||
} catch (err) {
|
||||
$("#updateNote").textContent = err.message;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function cancelJob(event) {
|
||||
event.currentTarget.disabled = true;
|
||||
|
||||
@@ -477,6 +477,13 @@ try {
|
||||
<button id="jobRetry" class="ghost" type="button" hidden>повторить</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="service-card">
|
||||
<h2>Обновления</h2>
|
||||
<div class="dp-head">Версия <span id="updateCurrent">—</span></div>
|
||||
<div class="dp-note" id="updateNote">проверка тегов Gitea</div>
|
||||
<button id="checkUpdates" class="ghost" type="button">проверить</button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Reference in new issue
Block a user