feat: import and export mood profiles
Add GET /api/moods/export (custom-only filter) and POST /api/moods/import with skip reporting, plus export/import controls in the recommendations panel.
This commit is contained in:
1 parent
987e52931f
commit
49a7ab9918
9 files changed
+220
-43
No files matched your search
@@ -103,6 +103,9 @@
|
||||
(`STEAMBASE_COVER_MAINTENANCE_HOURS`, `STEAMBASE_COVER_MAX_MB`).
|
||||
- Редактор пользовательских профилей: `POST /api/moods`, `DELETE /api/moods/{name}`,
|
||||
форма «+ свой профиль» с жанрами и весами тегов.
|
||||
- Импорт/экспорт профилей настроений: `GET /api/moods/export?custom=1`,
|
||||
`POST /api/moods/import`, кнопки «экспорт»/«импорт»; встроенные имена
|
||||
и некорректные записи при импорте пропускаются.
|
||||
- Опциональный HLTB: `requirements-hltb.txt`, `tools/fetch_hltb.py`, поля
|
||||
`hltb_main/hltb_extra/hltb_complete` (схема v6); точные совпадения названий.
|
||||
- HLTB в интерфейсе: кнопка в «База игр», `POST /api/hltb`, счётчик
|
||||
@@ -124,6 +127,9 @@
|
||||
полной отмены; кнопки есть на вкладках HLTB и «Сервисы».
|
||||
- «Повторить промахи» теперь берёт только уже проверенные игры без совпадения;
|
||||
для небольших пачек HLTB показывает каждую игру в логе и прогресс с ETA.
|
||||
- Кэш HLTB-запросов в `hltb_cache` (схема v8): TTL 7 дней, повторные прогоны и
|
||||
промахи не дёргают HLTB заново; флаги `--cache-ttl`, `--no-cache`,
|
||||
`--clear-cache`.
|
||||
- Сортировка таблицы по жанру и избранному; опции в селекторе сортировки.
|
||||
- Демо-скриншоты текущего UI в README.
|
||||
|
||||
|
||||
+9
-3
@@ -5,11 +5,11 @@
|
||||
|
||||
## 1. Снимок
|
||||
|
||||
- Дата снимка: **2026-11-06**
|
||||
- Дата снимка: **2026-11-07**
|
||||
- Версия: **1.0.0**
|
||||
- Ветка: `main`
|
||||
- HEAD перед текущей итерацией: `ccc1f62` (`feat: split HLTB and service controls into pages`)
|
||||
- Текущая итерация: пауза/продолжение задач и улучшенный матчинг HLTB.
|
||||
- HEAD перед текущей итерацией: `e82d0e0` (`fix: retry only HLTB misses and show progress`)
|
||||
- Текущая итерация: кэш HLTB-запросов и импорт/экспорт профилей настроений.
|
||||
- Репозиторий: <https://gitea.strsv.ru/strsv/SteamBase>
|
||||
- Remote: `origin`, SSH, ветка `main`
|
||||
- Рабочая копия: корень проекта `SteamBase/` (в текущем workspace —
|
||||
@@ -66,6 +66,8 @@
|
||||
- Время суток: `time_of_day=morning|day|evening|night`, бонус по тегам и причина.
|
||||
- Кэш обложек: фоновая очистка `.missing` и prune (24 ч, 500 МБ по умолчанию).
|
||||
- Редактор профилей: `POST /api/moods`, `DELETE /api/moods/{name}`, UI-форма.
|
||||
- Импорт/экспорт профилей: `GET /api/moods/export`, `POST /api/moods/import`,
|
||||
кнопки «экспорт»/«импорт»; встроенные профили при импорте пропускаются.
|
||||
- HLTB (опционально): `requirements-hltb.txt`, `fetch_hltb.py`, поля `hltb_*` (схема v6).
|
||||
- HLTB в UI: кнопка в «База игр», `POST /api/hltb`, метки `hltb_checked_at`/`hltb_match` (v7).
|
||||
- Закреплённые фильтры сохраняются при переключении вкладок; состояние задачи
|
||||
@@ -76,6 +78,8 @@
|
||||
- Задачи: пауза (`NtSuspendProcess`/`SIGSTOP`), продолжение, полная отмена.
|
||||
- HLTB-матчинг: регистр, римские цифры, издания, годы; примеры SOMA/Republic
|
||||
Commando/Nightmares 2/Divinity 2 теперь находятся.
|
||||
- Кэш HLTB-запросов (`hltb_cache`, схема v8): TTL 7 дней, `--cache-ttl`,
|
||||
`--no-cache`, `--clear-cache`; промахи тоже кэшируются.
|
||||
- Инкремент: установки обновляются у всех, установленные вне `librarycache` тоже
|
||||
добавляются (метаданные существующих не перечитываются).
|
||||
- Компактный список библиотеки с сохранением режима в `localStorage`.
|
||||
@@ -282,6 +286,8 @@ Invoke-RestMethod http://127.0.0.1:8765/api/meta
|
||||
45. HLTB-страница и инкрементальное обновление установок.
|
||||
46. Вкладки HLTB/Сервисы и перенос служебных кнопок.
|
||||
47. Пауза/продолжение задач и улучшенный матчинг HLTB.
|
||||
48. Кэш HLTB-запросов (схема v8, TTL и очистка).
|
||||
49. Импорт/экспорт профилей настроений (JSON, API и UI).
|
||||
|
||||
Дальше — ручной screen reader, Steam API, новые версии appinfo.
|
||||
|
||||
|
||||
+4
-2
@@ -70,9 +70,11 @@
|
||||
- время суток в рекомендациях (утро/день/вечер/ночь);
|
||||
- фоновое обслуживание кэша обложек по расписанию;
|
||||
- редактор пользовательских профилей настроений;
|
||||
- импорт/экспорт профилей настроений (JSON, API и UI);
|
||||
- опциональный HLTB через `howlongtobeatpy` (`requirements-hltb.txt`);
|
||||
- HLTB-кнопка в UI и метки `hltb_checked_at`/`hltb_match`;
|
||||
- HLTB-матчинг с нормализацией названий и запросами по году;
|
||||
- кэш HLTB-запросов (`hltb_cache`, TTL 7 дней, `--clear-cache`);
|
||||
- пауза/продолжение фоновых задач отдельно от полной отмены;
|
||||
- служебная вкладка HLTB со статусом, данными и датами проверки;
|
||||
- документация и AGENTS.md.
|
||||
@@ -292,5 +294,5 @@
|
||||
6. Добавить сравнение пресетов в UI.
|
||||
7. Добавить несколько профилей вкуса (соло/с друзьями).
|
||||
8. Добавить тепловую карту активности по времени.
|
||||
9. Добавить импорт/экспорт профилей настроений.
|
||||
10. Добавить кэш HLTB-запросов.
|
||||
9. [x] Импорт/экспорт профилей настроений (JSON, API и UI).
|
||||
10. [x] Кэш HLTB-запросов (`hltb_cache`, TTL, `--clear-cache`).
|
||||
+18
@@ -13,7 +13,9 @@
|
||||
| GET | `/api/hltb/status` | проверенные HLTB игры, статус и даты |
|
||||
| GET | `/api/game/{appid}` | карточка игры, похожие, атрибуты |
|
||||
| GET | `/api/moods` | профили настроений (с флагом `builtin`) |
|
||||
| GET | `/api/moods/export` | экспорт профилей (`?custom=1` — только свои) |
|
||||
| POST | `/api/moods` | создать/изменить пользовательский профиль |
|
||||
| POST | `/api/moods/import` | импорт профилей из JSON |
|
||||
| DELETE | `/api/moods/{name}` | удалить пользовательский профиль |
|
||||
| GET | `/api/descriptions?ids=1,2` | кэш описаний по appid |
|
||||
| GET | `/api/job` | состояние фоновой задачи |
|
||||
@@ -211,6 +213,20 @@ Invoke-RestMethod "http://127.0.0.1:8765/api/export?format=json&min_year=2020"
|
||||
(без жанров и тегов) → 400. Ответ: `{"mood": {...}, "builtin": false}`.
|
||||
DELETE → `{"deleted": true}`.
|
||||
|
||||
## `GET /api/moods/export` и `POST /api/moods/import`
|
||||
|
||||
`GET /api/moods/export` возвращает `{"version": 1, "exported_at": "...",
|
||||
"moods": [...]}`. Параметр `custom=1` оставляет только пользовательские профили
|
||||
(без встроенных).
|
||||
|
||||
`POST /api/moods/import` принимает тот же объект или просто массив профилей.
|
||||
Новые профили добавляются, существующие пользовательские обновляются, встроенные
|
||||
имена и некорректные записи пропускаются. Ответ:
|
||||
|
||||
```json
|
||||
{"imported": 1, "updated": 1, "skipped": [{"name": "dark-fantasy", "reason": "builtin profile"}]}
|
||||
```
|
||||
|
||||
## `GET /api/descriptions?ids=1,2`
|
||||
|
||||
```json
|
||||
@@ -418,6 +434,8 @@ Invoke-RestMethod "http://127.0.0.1:8765/api/hltb/status?status=match&q=hades&li
|
||||
ещё не проверялись (`hltb_checked_at IS NULL`). `retry_missed` добавляет игры без
|
||||
совпадения, `refresh` — все. Если `howlongtobeatpy` не установлен: 400 с командой
|
||||
установки. Ответ: `{"started": true, "limit": 200}`; прогресс — `/api/job`.
|
||||
Ответы поиска кэшируются в `hltb_cache` (TTL 7 дней), поэтому повторный запуск
|
||||
или `retry_missed` не дёргает HLTB заново.
|
||||
|
||||
## `POST /api/refresh`
|
||||
|
||||
|
||||
@@ -153,6 +153,8 @@ python web/server.py --port 9000
|
||||
- 21 профиль настроения (чипы) или свободный текст на русском/английском;
|
||||
- «+ свой профиль»: имя, описание, жанры и теги с весами; свои профили можно
|
||||
редактировать и удалять (встроенные — нельзя);
|
||||
- «экспорт» сохраняет свои профили в JSON, «импорт» загружает их обратно:
|
||||
новые добавляются, существующие обновляются, встроенные имена пропускаются;
|
||||
- фильтры: только неигранное, учитывать `tribute`, учитывать `nostalgia`,
|
||||
минимальный процент отзывов, доступное время (30 минут / вечер / выходные),
|
||||
время суток (утро/день/вечер/ночь);
|
||||
@@ -356,8 +358,15 @@ pip install -r requirements-hltb.txt
|
||||
python tools/fetch_hltb.py --limit 100
|
||||
python tools/fetch_hltb.py --refresh --limit 50
|
||||
python tools/fetch_hltb.py --all --delay 0.6
|
||||
python tools/fetch_hltb.py --retry-missed --limit 200
|
||||
python tools/fetch_hltb.py --clear-cache
|
||||
```
|
||||
|
||||
Ответы поиска кэшируются в `hltb_cache` на 7 дней: повторные прогоны и
|
||||
«повторить промахи» не дёргают HLTB заново. TTL меняется через `--cache-ttl`
|
||||
(в днях, `0` отключает чтение), полностью обойти кэш — `--no-cache`,
|
||||
очистить — `--clear-cache`. Записи старше 90 дней удаляются автоматически.
|
||||
|
||||
Используется `howlongtobeatpy`. Совпадение проверяется с нормализацией: регистр,
|
||||
римские цифры (`2`/`II`), издания (`GOTY`, `HD`, `Classic`, `RHCP`), год в скобках
|
||||
и варианты запроса с годом. Время main story записывается в `estimated_hours`,
|
||||
|
||||
@@ -445,6 +445,48 @@ class ApiTests(unittest.TestCase):
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def test_mood_export_import(self):
|
||||
try:
|
||||
self.post("/api/moods", {
|
||||
"name": "export-one", "description": "Экспорт",
|
||||
"genres": ["RPG"], "tags": {"Cozy": 1.5}})
|
||||
data = self.get("/api/moods/export")
|
||||
self.assertEqual(data["version"], 1)
|
||||
names = {mood["name"] for mood in data["moods"]}
|
||||
self.assertIn("export-one", names)
|
||||
self.assertIn("dark-fantasy", names)
|
||||
|
||||
custom = self.get("/api/moods/export?custom=1")
|
||||
custom_names = {mood["name"] for mood in custom["moods"]}
|
||||
self.assertIn("export-one", custom_names)
|
||||
self.assertNotIn("dark-fantasy", custom_names)
|
||||
|
||||
result = self.post("/api/moods/import", {"moods": [
|
||||
{"name": "import-one", "description": "Импорт",
|
||||
"genres": ["RPG"], "tags": {"Cozy": 1.2}},
|
||||
{"name": "export-one", "description": "Обновлён",
|
||||
"genres": [], "tags": {"Relaxing": 1.0}},
|
||||
{"name": "dark-fantasy", "tags": {"Cozy": 1.0}},
|
||||
{"name": "Bad Name", "tags": {"Cozy": 1.0}},
|
||||
"not-a-dict",
|
||||
]})
|
||||
self.assertEqual(result["imported"], 1)
|
||||
self.assertEqual(result["updated"], 1)
|
||||
self.assertEqual(len(result["skipped"]), 3)
|
||||
|
||||
moods = {mood["name"]: mood for mood in self.get("/api/moods")["moods"]}
|
||||
self.assertIn("import-one", moods)
|
||||
self.assertEqual(moods["export-one"]["description"], "Обновлён")
|
||||
self.assertEqual(self.post("/api/moods/import", {"not": "a list"},
|
||||
expect=400)["error"], "expected list of moods")
|
||||
finally:
|
||||
con = db.connect(self.db_path)
|
||||
try:
|
||||
con.execute("DELETE FROM moods WHERE name IN ('export-one', 'import-one')")
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def test_recommend_unknown_mood(self):
|
||||
data = self.post("/api/recommend", {"preset": "no-such-mood"}, expect=400)
|
||||
self.assertEqual(data["error"], "unknown mood")
|
||||
|
||||
+100
-38
@@ -690,6 +690,34 @@ def game_filters(qs):
|
||||
MOOD_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,39}$")
|
||||
|
||||
|
||||
def normalize_mood_payload(body):
|
||||
"""Validate and normalize a mood profile payload."""
|
||||
name = str(body.get("name") or "").strip().lower()
|
||||
if name in db.MOOD_PRESETS:
|
||||
raise ValueError("builtin profile")
|
||||
if not MOOD_NAME_RE.match(name):
|
||||
raise ValueError("invalid name")
|
||||
description = str(body.get("description") or "").strip()[:200]
|
||||
genres = []
|
||||
for genre in body.get("genres") or []:
|
||||
value = str(genre).strip()
|
||||
if value and value not in genres:
|
||||
genres.append(value)
|
||||
tags = {}
|
||||
for tag, weight in (body.get("tags") or {}).items():
|
||||
try:
|
||||
value = float(weight)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
tag = str(tag).strip()
|
||||
if tag and 0.1 <= value <= 5.0:
|
||||
tags[tag] = round(value, 2)
|
||||
tags = dict(list(tags.items())[:30])
|
||||
if not genres and not tags:
|
||||
raise ValueError("empty profile")
|
||||
return {"name": name, "description": description, "genres": genres, "tags": tags}
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "SteamBase/1.0"
|
||||
|
||||
@@ -759,6 +787,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._feedback(self._body())
|
||||
elif path == "/api/moods":
|
||||
self._save_mood(self._body())
|
||||
elif path == "/api/moods/import":
|
||||
self._import_moods(self._body())
|
||||
elif path == "/api/prefetch":
|
||||
body = self._body()
|
||||
ids = self._missing_ids(body.get("limit", 200), bool(body.get("retry_missing")))
|
||||
@@ -973,6 +1003,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._hltb_status(qs)
|
||||
elif path == "/api/moods":
|
||||
self._moods()
|
||||
elif path == "/api/moods/export":
|
||||
self._export_moods(qs)
|
||||
elif path == "/api/descriptions":
|
||||
ids = [int(x) for x in (qs.get("ids", [""])[0] or "").split(",") if x.isdigit()]
|
||||
con = connect()
|
||||
@@ -1295,47 +1327,77 @@ class Handler(BaseHTTPRequestHandler):
|
||||
con.close()
|
||||
|
||||
def _save_mood(self, body):
|
||||
name = str(body.get("name") or "").strip().lower()
|
||||
if name in db.MOOD_PRESETS:
|
||||
self._error(400, "builtin profile")
|
||||
return
|
||||
if not MOOD_NAME_RE.match(name):
|
||||
self._error(400, "invalid name")
|
||||
return
|
||||
description = str(body.get("description") or "").strip()[:200]
|
||||
genres = []
|
||||
for genre in body.get("genres") or []:
|
||||
value = str(genre).strip()
|
||||
if value and value not in genres:
|
||||
genres.append(value)
|
||||
tags = {}
|
||||
for tag, weight in (body.get("tags") or {}).items():
|
||||
try:
|
||||
value = float(weight)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
tag = str(tag).strip()
|
||||
if tag and 0.1 <= value <= 5.0:
|
||||
tags[tag] = round(value, 2)
|
||||
tags = dict(list(tags.items())[:30])
|
||||
if not genres and not tags:
|
||||
self._error(400, "empty profile")
|
||||
try:
|
||||
mood = normalize_mood_payload(body)
|
||||
except ValueError as exc:
|
||||
self._error(400, str(exc))
|
||||
return
|
||||
con = connect()
|
||||
try:
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
con.execute(
|
||||
"""INSERT INTO moods (name, description, genres, tags, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(name) DO UPDATE SET
|
||||
description = excluded.description,
|
||||
genres = excluded.genres,
|
||||
tags = excluded.tags,
|
||||
updated_at = excluded.updated_at""",
|
||||
(name, description, json.dumps(genres), json.dumps(tags), now))
|
||||
con.commit()
|
||||
self._json({"mood": {"name": name, "description": description,
|
||||
"genres": genres, "tags": tags}, "builtin": False})
|
||||
self._store_mood(con, mood)
|
||||
self._json({"mood": mood, "builtin": False})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
@staticmethod
|
||||
def _store_mood(con, mood):
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
con.execute(
|
||||
"""INSERT INTO moods (name, description, genres, tags, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(name) DO UPDATE SET
|
||||
description = excluded.description,
|
||||
genres = excluded.genres,
|
||||
tags = excluded.tags,
|
||||
updated_at = excluded.updated_at""",
|
||||
(mood["name"], mood["description"], json.dumps(mood["genres"]),
|
||||
json.dumps(mood["tags"]), now))
|
||||
con.commit()
|
||||
|
||||
def _export_moods(self, qs):
|
||||
custom_only = (qs.get("custom", ["0"])[0] or "").lower() in ("1", "true", "yes")
|
||||
con = connect()
|
||||
try:
|
||||
moods = [{"name": r["name"], "description": r["description"],
|
||||
"genres": json.loads(r["genres"]), "tags": json.loads(r["tags"]),
|
||||
"builtin": r["name"] in db.MOOD_PRESETS}
|
||||
for r in con.execute("SELECT * FROM moods ORDER BY name")]
|
||||
if custom_only:
|
||||
moods = [mood for mood in moods if not mood["builtin"]]
|
||||
self._json({
|
||||
"version": 1,
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"moods": moods,
|
||||
})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _import_moods(self, body):
|
||||
items = body.get("moods") if isinstance(body, dict) else body
|
||||
if not isinstance(items, list):
|
||||
self._error(400, "expected list of moods")
|
||||
return
|
||||
imported = updated = 0
|
||||
skipped = []
|
||||
con = connect()
|
||||
try:
|
||||
existing = {r["name"] for r in con.execute("SELECT name FROM moods")}
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
skipped.append({"name": None, "reason": "invalid item"})
|
||||
continue
|
||||
try:
|
||||
mood = normalize_mood_payload(item)
|
||||
except ValueError as exc:
|
||||
skipped.append({"name": item.get("name"), "reason": str(exc)})
|
||||
continue
|
||||
if mood["name"] in existing:
|
||||
updated += 1
|
||||
else:
|
||||
imported += 1
|
||||
existing.add(mood["name"])
|
||||
self._store_mood(con, mood)
|
||||
self._json({"imported": imported, "updated": updated, "skipped": skipped})
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
@@ -944,6 +944,35 @@ $("#moodDelete").addEventListener("click", async () => {
|
||||
toast(err.message);
|
||||
}
|
||||
});
|
||||
$("#moodExport").addEventListener("click", () => {
|
||||
const link = document.createElement("a");
|
||||
link.href = "/api/moods/export?custom=1";
|
||||
link.download = "steambase-moods.json";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
});
|
||||
$("#moodImport").addEventListener("click", () => $("#moodImportFile").click());
|
||||
$("#moodImportFile").addEventListener("change", async () => {
|
||||
const input = $("#moodImportFile");
|
||||
const file = input.files && input.files[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
const payload = JSON.parse(await file.text());
|
||||
const data = await api("/api/moods/import", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
await loadMoods();
|
||||
const skipped = (data.skipped || []).length;
|
||||
toast(`Импорт: добавлено ${data.imported}, обновлено ${data.updated}` +
|
||||
(skipped ? `, пропущено ${skipped}` : ""));
|
||||
} catch (err) {
|
||||
toast(err.message);
|
||||
} finally {
|
||||
input.value = "";
|
||||
}
|
||||
});
|
||||
$("#meSave").addEventListener("click", async () => {
|
||||
const name = $("#meName").value.trim().toLowerCase();
|
||||
const tags = {};
|
||||
|
||||
@@ -251,6 +251,9 @@ try {
|
||||
<button id="moodCreate" class="link" type="button">+ свой профиль</button>
|
||||
<button id="moodEdit" class="link hidden" type="button">редактировать</button>
|
||||
<button id="moodDelete" class="link hidden" type="button">удалить</button>
|
||||
<button id="moodExport" class="link" type="button">экспорт</button>
|
||||
<button id="moodImport" class="link" type="button">импорт</button>
|
||||
<input id="moodImportFile" type="file" accept="application/json,.json" hidden>
|
||||
</div>
|
||||
<div id="moodEditor" class="mood-editor hidden">
|
||||
<div class="me-grid">
|
||||
|
||||
Reference in new issue
Block a user