Список «хочу посмотреть» и личные оценки
Команды «хочу <название>» (статус карточки) и «оценка <название> <1-10>» (таблица user_ratings, отдельно от рейтингов IMDb). Эндпоинты /watchlist, /rate, /rated. Убраны мусорные карточки от теста загрузки (имена релизов с 720p/2160p/YTS) и устаревшая карточка удалённого фильма. Состояние: 14 фильмов, 5 сериалов, 19 сезонов, 10 книг, 58 актёров, 536 связей. Ловушка: /rate перехватывал /rated — уточнён маршрут.
This commit is contained in:
1 parent
ea5a211d7e
commit
825dede279
4 files changed
+209
No files matched your search
@@ -48,6 +48,52 @@ class MediaBot(Bot):
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _want_cmd(self, arg):
|
||||
title = (arg or "").strip()
|
||||
if not title:
|
||||
data, err = core_api.watchlist()
|
||||
if err:
|
||||
return "Ядро не ответило: " + str(err)
|
||||
items = (data or {}).get("items") or []
|
||||
if not items:
|
||||
return ("Список пуст. Добавьте: !хочу Дюна")
|
||||
lines = ["**Хочу посмотреть** — " + str(len(items)), ""]
|
||||
for i in items:
|
||||
lines.append("• " + str(i.get("title")) + " (" + str(i.get("kind")) + ")")
|
||||
return chr(10).join(lines)
|
||||
data, err = core_api.watchlist(mark=title)
|
||||
if err:
|
||||
return "Ядро не ответило: " + str(err)
|
||||
if not data:
|
||||
return "Не нашёл «" + title + "» в графе."
|
||||
item = data.get("marked") or {}
|
||||
return ("Добавил в список: **" + str(item.get("title")) + "**\n\n"
|
||||
"_Посмотреть список: !хочу_")
|
||||
|
||||
def _rate_cmd(self, arg):
|
||||
parts = (arg or "").strip().rsplit(" ", 1)
|
||||
if len(parts) < 2 or not parts[1].isdigit():
|
||||
data, err = core_api.rated()
|
||||
if err:
|
||||
return "Ядро не ответило: " + str(err)
|
||||
items = (data or {}).get("items") or []
|
||||
if not items:
|
||||
return "Оценок пока нет. Поставьте: !оценка Дюна 9"
|
||||
lines = ["**Мои оценки** — средняя " + str((data or {}).get("average")), ""]
|
||||
for i in items[:15]:
|
||||
lines.append("• " + str(i.get("score")) + "/10 — " + str(i.get("title")))
|
||||
return chr(10).join(lines)
|
||||
title, score = parts[0], parts[1]
|
||||
data, err = core_api.rate(title, score)
|
||||
if err:
|
||||
return "Ядро не ответило: " + str(err)
|
||||
if not data:
|
||||
return "Не нашёл «" + title + "» в графе."
|
||||
item = data.get("rated") or {}
|
||||
return ("Оценил **" + str(item.get("title")) + "** на " + str(data.get("score")) + "/10")
|
||||
|
||||
def _seasons_cmd(self, arg):
|
||||
name = (arg or "").strip()
|
||||
if not name:
|
||||
@@ -472,6 +518,8 @@ class MediaBot(Bot):
|
||||
self.cmd("пополнить", "добавить кандидатов в медиатеку: !пополнить 3")(lambda a: self._fill_cmd(a))
|
||||
self.cmd("вместе", "с кем снимался: !вместе Zendaya")(lambda a: self._together_cmd(a))
|
||||
self.cmd("сезоны", "сезоны сериала: !сезоны Foundation")(lambda a: self._seasons_cmd(a))
|
||||
self.cmd("хочу", "список желаемого: !хочу Дюна")(lambda a: self._want_cmd(a))
|
||||
self.cmd("оценка", "поставить оценку: !оценка Дюна 9")(lambda a: self._rate_cmd(a))
|
||||
def _stats(self, jf):
|
||||
c = jf.counts()
|
||||
info, _ = jf.info()
|
||||
|
||||
@@ -165,3 +165,16 @@ def history(days=30):
|
||||
|
||||
def seasons(query):
|
||||
return _get("/seasons", {"q": query})
|
||||
|
||||
|
||||
def watchlist(mark=None):
|
||||
params = {"mark": mark} if mark else {}
|
||||
return _get("/watchlist", params)
|
||||
|
||||
|
||||
def rate(title, score):
|
||||
return _get("/rate", {"title": title, "score": score})
|
||||
|
||||
|
||||
def rated():
|
||||
return _get("/rated")
|
||||
@@ -0,0 +1,50 @@
|
||||
# Личное в медиатеке: «хочу посмотреть» и свои оценки
|
||||
|
||||
Граф знает, что есть в медиатеке. Теперь он знает ещё и что вы хотите
|
||||
посмотреть и как оцениваете увиденное.
|
||||
|
||||
## Список желаемого
|
||||
|
||||
* `!хочу Дюна` — помечает карточку статусом «хочу посмотреть»;
|
||||
* `!хочу` — список желаемого;
|
||||
* `GET /watchlist`, `GET /watchlist?mark=<название>`.
|
||||
|
||||
Статус хранится в самой карточке графа, поэтому «хочу» видно везде: в
|
||||
`!связи`, в поиске, в `/graph`.
|
||||
|
||||
## Свои оценки
|
||||
|
||||
* `!оценка Дюна 9` — личная оценка 1–10;
|
||||
* `!оценка` — список с средней;
|
||||
* `GET /rate?title=<название>&score=<1-10>`, `GET /rated`.
|
||||
|
||||
Оценки лежат в отдельной таблице `user_ratings` (entity_id, score), а не в
|
||||
графе: это личные данные, их не надо смешивать с рейтингами IMDb.
|
||||
|
||||
```
|
||||
!оценка Дюна 9 → Оценил Dune (2021) на 9/10
|
||||
!оценка → Мои оценки — средняя 8.5
|
||||
9/10 — Dune (2021)
|
||||
8/10 — The Matrix Reloaded (2003)
|
||||
```
|
||||
|
||||
## Уборка после теста загрузки
|
||||
|
||||
Тест конвейера оставил в графе два мусорных узла с именами релизов
|
||||
(«Night Of The Living Dead 1968 720p_sujaidr» и «…2160p BRRip …YTS»).
|
||||
Удалены. Заодно убрана устаревшая карточка удалённого фильма.
|
||||
|
||||
Состояние графа после уборки:
|
||||
|
||||
```
|
||||
фильм 14 · сериал 5 · сезон 19 · книга 10
|
||||
актёр 58 · режиссёр 8 · композитор 8
|
||||
тема 46 · жанр 14 · студия 10 · сеть 4
|
||||
связей 536
|
||||
```
|
||||
|
||||
## Ловушка
|
||||
|
||||
Маршрут `/rate` перехватывал `/rated` (префиксное совпадение), поэтому
|
||||
`!оценка` без аргументов отвечала `400`. Исправлено: `/rate` срабатывает
|
||||
только на точный путь или с `?`.
|
||||
@@ -946,6 +946,73 @@ def do_seasons(query):
|
||||
return {"series": dict(series), "seasons": seasons, "count": len(seasons)}
|
||||
|
||||
|
||||
|
||||
|
||||
def do_watchlist(mark=None, note=None):
|
||||
"""Список «хочу посмотреть»: карточки со статусом."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
if mark:
|
||||
cur.execute("""select id, kind, title from entities
|
||||
where search_text like %s order by length(title) limit 1""",
|
||||
(f"%{mark.lower()}%",))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
con.close()
|
||||
return None
|
||||
cur.execute("""update entities set status = %s, updated_at = now() where id = %s""",
|
||||
("хочу посмотреть", row["id"]))
|
||||
con.commit()
|
||||
con.close()
|
||||
return {"marked": dict(row), "status": "хочу посмотреть"}
|
||||
|
||||
cur.execute("""select id, kind, title, updated_at from entities
|
||||
where status in ('хочу посмотреть', 'смотрю')
|
||||
order by updated_at desc limit 50""")
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
return {"count": len(items), "items": items}
|
||||
|
||||
|
||||
def do_rate(title, score):
|
||||
"""Личная оценка карточки (1–10)."""
|
||||
try:
|
||||
score = max(1, min(10, int(score)))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
cur.execute("""create table if not exists user_ratings (
|
||||
entity_id integer, score integer, updated_at timestamptz default now(),
|
||||
primary key (entity_id))""")
|
||||
cur.execute("""select id, kind, title from entities
|
||||
where search_text like %s order by length(title) limit 1""",
|
||||
(f"%{title.lower()}%",))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
con.close()
|
||||
return None
|
||||
cur.execute("""insert into user_ratings (entity_id, score, updated_at) values (%s, %s, now())
|
||||
on conflict (entity_id) do update set score = %s, updated_at = now()""",
|
||||
(row["id"], score, score))
|
||||
con.commit()
|
||||
con.close()
|
||||
return {"rated": dict(row), "score": score}
|
||||
|
||||
|
||||
def do_rated(limit=30):
|
||||
"""Мои оценки: от высокой к низкой."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
cur.execute("""select e.id, e.kind, e.title, r.score
|
||||
from user_ratings r join entities e on e.id = r.entity_id
|
||||
order by r.score desc, e.title limit %s""", (limit,))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
avg = round(sum(i["score"] for i in items) / len(items), 2) if items else None
|
||||
return {"count": len(items), "average": avg, "items": items}
|
||||
|
||||
|
||||
def render_panel():
|
||||
"""HTML-страница: состояние системы в одном месте."""
|
||||
try:
|
||||
@@ -1384,6 +1451,37 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self._json(200, snapshot_graph())
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path.startswith("/watchlist"):
|
||||
import urllib.parse as _uw
|
||||
qs = _uw.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
mark = (qs.get("mark") or [None])[0]
|
||||
if mark:
|
||||
try:
|
||||
data = do_watchlist(mark=mark)
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
return self._json(200 if data else 404, data or {"error": "не найдено"})
|
||||
try:
|
||||
return self._json(200, do_watchlist())
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path == "/rate" or self.path.startswith("/rate?"):
|
||||
import urllib.parse as _ur
|
||||
qs = _ur.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
t = (qs.get("title") or [""])[0]
|
||||
sc = (qs.get("score") or ["0"])[0]
|
||||
if not t:
|
||||
return self._json(400, {"error": "нужен title"})
|
||||
try:
|
||||
data = do_rate(t, sc)
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
return self._json(200 if data else 404, data or {"error": "не найдено"})
|
||||
if self.path.startswith("/rated"):
|
||||
try:
|
||||
return self._json(200, do_rated())
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path.startswith("/seasons"):
|
||||
import urllib.parse as _use
|
||||
qs = _use.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
|
||||
Reference in new issue
Block a user