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
+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()
|
||||
|
||||
|
||||
Reference in new issue
Block a user