Метаданные через VPS + граф контента: франшизы, экранизации, серии
Главное: медиатека не могла пополняться. Radarr ходит за метаданными на api.radarr.video, а с домашнего IP этот адрес отдаёт 403 Cloudflare; с VPS — 200. На VPS уже был tinyproxy, разрешающий Tailscale-сеть. Поднят проброс socat на узле (192.168.1.10:8888 → 100.64.0.2:8888), Radarr и Sonarr переключены на него. После этого добавлены 5 фильмов с коллекциями. Второе: граф контента. content_graph.py строит карточки и связи: фильм → коллекция, книга → автор, книга → серия, книга ↔ фильм (экранизация), коллекция ↔ книжная серия (общая вселенная). На реальных данных: 21 карточка, 19 связей, включая Matrix-трилогию, Dune-дилогию, экранизацию Dune и связь коллекции Dune с книжной серией. Добавлен GET /links в ядро (сводка по типам и список), блок «Связи контента» в Медиа Хабе, расписание 04:45. Ловушки: PUT /api/v3/config/host требует allowedHosts (и не принимает «*»); прокси на Tailscale-адрес из контейнера не работает — нужен проброс; успех сохранения отдаёт 202.
This commit is contained in:
1 parent
9074749e0f
commit
3ea974ce95
7 files changed
+802
No files matched your search
@@ -0,0 +1,180 @@
|
||||
"""Граф контента: связи между фильмами, книгами, коллекциями и авторами.
|
||||
|
||||
Строит карточки и связи в ядре:
|
||||
фильм → коллекция «входит в»
|
||||
книга → серия «входит в серию»
|
||||
книга → автор «написал»
|
||||
книга ↔ фильм «экранизация»
|
||||
коллекция ↔ серия книг «общая вселенная»
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
||||
RADARR = os.environ.get("RADARR_URL", "http://192.168.1.118:7878")
|
||||
RADARR_KEY = os.environ.get("RADARR_KEY", "")
|
||||
|
||||
|
||||
def get(url, headers=None, timeout=20):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers=headers or {})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def post(path, payload):
|
||||
req = urllib.request.Request(f"{CORE}{path}",
|
||||
data=json.dumps(payload, ensure_ascii=False).encode(),
|
||||
method="POST", headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").lower().replace("ё", "е")
|
||||
s = re.sub(r"[:!?.,'’\"()\[\]]", " ", s)
|
||||
s = re.sub(r"\b(part|chapter|часть|том|книга)\b", " ", s)
|
||||
return " ".join(s.split())
|
||||
|
||||
|
||||
# ─────────── источники ───────────
|
||||
|
||||
def movies():
|
||||
data, err = get(f"{RADARR}/api/v3/movie", {"X-Api-Key": RADARR_KEY})
|
||||
if err:
|
||||
print(f" Radarr: ошибка {err}")
|
||||
return []
|
||||
out = []
|
||||
for m in data or []:
|
||||
col = m.get("collection") or {}
|
||||
out.append({
|
||||
"title": m.get("title"), "year": m.get("year"),
|
||||
"tmdb": m.get("tmdbId"),
|
||||
"collection": col.get("title"), "collection_tmdb": col.get("tmdbId"),
|
||||
"genres": m.get("genres") or [],
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def books():
|
||||
script = """
|
||||
import json, sqlite3
|
||||
c = sqlite3.connect('/opt/books/library/metadata.db')
|
||||
q = '''select b.id, b.title, b.series_index, s.name
|
||||
from books b left join books_series_link l on l.book = b.id
|
||||
left join series s on s.id = l.series'''
|
||||
rows = []
|
||||
for bid, title, idx, series in c.execute(q):
|
||||
authors = [r[0] for r in c.execute(
|
||||
'select a.name from authors a join books_authors_link l on l.author = a.id where l.book = ?', (bid,))]
|
||||
rows.append({"id": bid, "title": title, "series": series,
|
||||
"series_index": idx, "authors": authors})
|
||||
print(json.dumps(rows, ensure_ascii=False))
|
||||
"""
|
||||
path = "/tmp/books.json"
|
||||
open(path, "w", encoding="utf-8").write(script)
|
||||
subprocess.run(["pct", "push", "111", path, path, "--perms", "644"],
|
||||
capture_output=True, timeout=30)
|
||||
out = subprocess.run(["pct", "exec", "111", "--", "python3", path],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
try:
|
||||
return json.loads(out.stdout or "[]")
|
||||
except Exception:
|
||||
print(" Calibre: не прочитал", (out.stderr or "")[:80])
|
||||
return []
|
||||
|
||||
|
||||
# ─────────── граф ───────────
|
||||
|
||||
def main():
|
||||
mv = movies()
|
||||
bk = books()
|
||||
print(f"фильмов: {len(mv)}, книг: {len(bk)}")
|
||||
|
||||
ids = {}
|
||||
made_cards = 0
|
||||
made_links = 0
|
||||
|
||||
def card(kind, key, title, status=None):
|
||||
nonlocal made_cards
|
||||
res, err = post("/entity", {"kind": kind, "key": key, "title": title, "status": status})
|
||||
if err or not res:
|
||||
return None
|
||||
made_cards += 1
|
||||
ids[key] = res.get("id")
|
||||
return res.get("id")
|
||||
|
||||
def link(a, b, relation):
|
||||
nonlocal made_links
|
||||
if not a or not b or a == b:
|
||||
return
|
||||
_, err = post("/link", {"from": a, "to": b, "relation": relation})
|
||||
if not err:
|
||||
made_links += 1
|
||||
|
||||
# фильмы
|
||||
for m in mv:
|
||||
card("фильм", f"tmdb:{m['tmdb']}", f"{m['title']} ({m['year']})", "в медиатеке")
|
||||
|
||||
# коллекции
|
||||
for m in mv:
|
||||
if m["collection"]:
|
||||
key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}"
|
||||
card("коллекция", key, m["collection"], "франшиза")
|
||||
link(ids.get(f"tmdb:{m['tmdb']}"), ids.get(key), "входит в")
|
||||
|
||||
# книги
|
||||
for b in bk:
|
||||
card("книга", f"calibre:{b['id']}", b["title"], "в библиотеке")
|
||||
for author in b.get("authors") or []:
|
||||
key = f"author:{norm(author)}"
|
||||
card("автор", key, author)
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(key), "написал")
|
||||
if b.get("series"):
|
||||
key = f"series:{norm(b['series'])}"
|
||||
card("серия книг", key, b["series"], "книжная серия")
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(key), "входит в серию")
|
||||
|
||||
# экранизации: книга ↔ фильм по названию
|
||||
by_title = {}
|
||||
for m in mv:
|
||||
by_title.setdefault(norm(m["title"]), []).append(("фильм", m["tmdb"]))
|
||||
for b in bk:
|
||||
for kind, ident in by_title.get(norm(b["title"]), []):
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(f"tmdb:{ident}"), "экранизация")
|
||||
|
||||
# общая вселенная: коллекция фильмов ↔ книжная серия с тем же названием
|
||||
for m in mv:
|
||||
if not m["collection"]:
|
||||
continue
|
||||
col_key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}"
|
||||
col_norm = norm(m["collection"]).replace("collection", "").strip()
|
||||
for b in bk:
|
||||
if b.get("series") and norm(b["series"]) == col_norm:
|
||||
link(ids.get(col_key), ids.get(f"series:{norm(b['series'])}"), "общая вселенная")
|
||||
|
||||
print(f"карточек создано/обновлено: {made_cards}, связей: {made_links}")
|
||||
|
||||
# сводка по типам связей
|
||||
from collections import Counter
|
||||
try:
|
||||
import urllib.request as u
|
||||
with u.urlopen(f"{CORE}/entity/{list(ids.values())[0]}", timeout=20) as r:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -406,6 +406,26 @@ def jobs_status():
|
||||
return rows
|
||||
|
||||
|
||||
|
||||
|
||||
def do_links(limit=200):
|
||||
"""Связи контента: список и сводка по типам."""
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
cur.execute("select relation, count(*) as n from entity_links group by relation order by n desc")
|
||||
summary = {r["relation"]: r["n"] for r in cur.fetchall()}
|
||||
|
||||
cur.execute("""select a.title as from_title, a.kind as from_kind,
|
||||
b.title as to_title, b.kind as to_kind, l.relation
|
||||
from entity_links l
|
||||
join entities a on a.id = l.from_id
|
||||
join entities b on b.id = l.to_id
|
||||
order by l.relation, a.title limit %s""", (limit,))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
return {"total": sum(summary.values()), "by_relation": summary, "items": items}
|
||||
|
||||
|
||||
def render_panel():
|
||||
"""HTML-страница: состояние системы в одном месте."""
|
||||
try:
|
||||
@@ -653,6 +673,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if self.path.startswith("/links"):
|
||||
try:
|
||||
return self._json(200, do_links())
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path == "/services":
|
||||
try:
|
||||
return self._json(200, do_services())
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Медиа Хаб: единая картина медиатеки и всех процессов вокруг неё.
|
||||
|
||||
Собирает: что смотрят, что добавилось, что заказано и на какой стадии,
|
||||
что качается, чего не хватает, сколько места, здоровье служб.
|
||||
Отдаёт в ядро (коллекция `media`) и в бота Медиа.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
||||
JELLYFIN = os.environ.get("JELLYFIN_URL", "http://192.168.1.103:8096")
|
||||
JELLYFIN_KEY = os.environ.get("JELLYFIN_KEY", "")
|
||||
SONARR = os.environ.get("SONARR_URL", "http://192.168.1.117:8989")
|
||||
SONARR_KEY = os.environ.get("SONARR_KEY", "")
|
||||
RADARR = os.environ.get("RADARR_URL", "http://192.168.1.118:7878")
|
||||
RADARR_KEY = os.environ.get("RADARR_KEY", "")
|
||||
SEERR = os.environ.get("SEERR_URL", "http://192.168.1.121:5055")
|
||||
SEERR_KEY = os.environ.get("SEERR_KEY", "")
|
||||
|
||||
SEERR_STATUS = {
|
||||
1: "ожидает", 2: "одобрено", 3: "отклонено", 4: "качается", 5: "готово",
|
||||
}
|
||||
|
||||
|
||||
def get(url, headers=None, timeout=15):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers=headers or {})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def jf(path):
|
||||
return get(f"{JELLYFIN}{path}",
|
||||
{"Authorization": f'MediaBrowser Token="{JELLYFIN_KEY}"'})
|
||||
|
||||
|
||||
def human_size(n):
|
||||
n = float(n or 0)
|
||||
for unit in ("Б", "КБ", "МБ", "ГБ", "ТБ"):
|
||||
if n < 1024:
|
||||
return f"{n:.0f} {unit}"
|
||||
n /= 1024
|
||||
return f"{n:.1f} ПБ"
|
||||
|
||||
|
||||
# ────────────────── блоки ──────────────────
|
||||
|
||||
def continue_watching():
|
||||
"""Что не досмотрено: все пользователи."""
|
||||
users, err = jf("/Users")
|
||||
if err:
|
||||
return {"error": err, "items": []}
|
||||
items = []
|
||||
for u in users or []:
|
||||
if not u.get("Name"):
|
||||
continue
|
||||
resume, e2 = jf(f"/Users/{u.get('Id')}/Items/Resume?Limit=6&MediaTypes=Video")
|
||||
if e2:
|
||||
continue
|
||||
for it in (resume or {}).get("Items", []):
|
||||
pos = it.get("UserData", {}).get("PlaybackPositionTicks", 0)
|
||||
total = it.get("RunTimeTicks") or 0
|
||||
pct = int(100 * pos / total) if total else 0
|
||||
left_min = int((total - pos) / 10_000_000 / 60) if total else 0
|
||||
items.append({"user": u.get("Name"), "title": it.get("Name"),
|
||||
"pct": pct, "left_min": left_min})
|
||||
return {"items": items[:10]}
|
||||
|
||||
|
||||
def recently_added(limit=10):
|
||||
data, err = jf("/Items?Recursive=true&IncludeItemTypes=Movie,Series"
|
||||
f"&SortBy=DateCreated&SortOrder=Descending&Limit={limit}")
|
||||
if err:
|
||||
return {"error": err, "items": []}
|
||||
items = [{"title": i.get("Name"), "type": i.get("Type"),
|
||||
"year": i.get("ProductionYear")} for i in (data or {}).get("Items", [])]
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def requests():
|
||||
"""Заявки и их стадия — конвейер «заказал → смотрю»."""
|
||||
data, err = get(f"{SEERR}/api/v1/request?take=50&filter=all&sort=added",
|
||||
{"X-Api-Key": SEERR_KEY})
|
||||
if err:
|
||||
return {"error": err, "by_status": {}, "items": []}
|
||||
items, by_status = [], {}
|
||||
for r in (data or {}).get("results", []):
|
||||
media = r.get("media") or {}
|
||||
title = media.get("title") or media.get("name") or "заявка"
|
||||
status = SEERR_STATUS.get(r.get("status"), str(r.get("status")))
|
||||
by_status[status] = by_status.get(status, 0) + 1
|
||||
items.append({"title": title, "status": status,
|
||||
"type": media.get("mediaType") or "?",
|
||||
"requested_by": (r.get("requestedBy") or {}).get("displayName")})
|
||||
return {"by_status": by_status, "items": items[:15], "total": len(items)}
|
||||
|
||||
|
||||
def sonarr_queue():
|
||||
data, err = get(f"{SONARR}/api/v3/queue?pageSize=20&includeUnknownSeriesItems=true",
|
||||
{"X-Api-Key": SONARR_KEY})
|
||||
if err:
|
||||
return {"error": err, "items": []}
|
||||
items = []
|
||||
for r in (data or {}).get("records", []):
|
||||
items.append({"title": r.get("title"), "size": r.get("size"),
|
||||
"left": r.get("timeleft"), "status": r.get("status")})
|
||||
return {"items": items, "total": (data or {}).get("totalRecords", 0)}
|
||||
|
||||
|
||||
def radarr_queue():
|
||||
data, err = get(f"{RADARR}/api/v3/queue?pageSize=20&includeUnknownMovieItems=true",
|
||||
{"X-Api-Key": RADARR_KEY})
|
||||
if err:
|
||||
return {"error": err, "items": []}
|
||||
items = []
|
||||
for r in (data or {}).get("records", []):
|
||||
items.append({"title": r.get("title"), "size": r.get("size"),
|
||||
"left": r.get("timeleft"), "status": r.get("status")})
|
||||
return {"items": items, "total": (data or {}).get("totalRecords", 0)}
|
||||
|
||||
|
||||
def missing():
|
||||
"""Чего не хватает в библиотеках."""
|
||||
out = {}
|
||||
data, err = get(f"{SONARR}/api/v3/wanted/missing?pageSize=1",
|
||||
{"X-Api-Key": SONARR_KEY})
|
||||
out["сериалы"] = (data or {}).get("totalRecords", 0) if not err else None
|
||||
data, err = get(f"{RADARR}/api/v3/wanted/missing?pageSize=1",
|
||||
{"X-Api-Key": RADARR_KEY})
|
||||
out["фильмы"] = (data or {}).get("totalRecords", 0) if not err else None
|
||||
return out
|
||||
|
||||
|
||||
def disks():
|
||||
data, err = get(f"{SONARR}/api/v3/diskspace", {"X-Api-Key": SONARR_KEY})
|
||||
if err:
|
||||
return {"error": err, "items": []}
|
||||
items = []
|
||||
for d in data or []:
|
||||
total = d.get("totalSpace") or 0
|
||||
free = d.get("freeSpace") or 0
|
||||
pct = round(100 * (total - free) / total) if total else 0
|
||||
items.append({"path": d.get("path"), "free": human_size(free),
|
||||
"total": human_size(total), "used_pct": pct})
|
||||
return {"items": items}
|
||||
|
||||
|
||||
def health():
|
||||
"""Предупреждения Sonarr и Radarr."""
|
||||
out = []
|
||||
for name, base, key in (("Sonarr", SONARR, SONARR_KEY), ("Radarr", RADARR, RADARR_KEY)):
|
||||
data, err = get(f"{base}/api/v3/health", {"X-Api-Key": key})
|
||||
if err:
|
||||
out.append({"service": name, "error": err})
|
||||
continue
|
||||
for h in data or []:
|
||||
out.append({"service": name, "type": h.get("type"),
|
||||
"message": h.get("message"),
|
||||
"wiki": h.get("wikiUrl")})
|
||||
return {"items": out}
|
||||
|
||||
|
||||
|
||||
|
||||
def content_links():
|
||||
"""Связи контента: сводка из ядра."""
|
||||
data, err = get(f"{CORE}/links")
|
||||
if err:
|
||||
return {"total": 0, "by_relation": {}}
|
||||
return {"total": (data or {}).get("total", 0),
|
||||
"by_relation": (data or {}).get("by_relation") or {}}
|
||||
|
||||
def collect():
|
||||
return {
|
||||
"continue": continue_watching(),
|
||||
"recent": recently_added(),
|
||||
"requests": requests(),
|
||||
"queue": {"sonarr": sonarr_queue(), "radarr": radarr_queue()},
|
||||
"missing": missing(),
|
||||
"disks": disks(),
|
||||
"health": health(),
|
||||
"content": content_links(),
|
||||
}
|
||||
|
||||
|
||||
# ────────────────── вывод ──────────────────
|
||||
|
||||
def render_markdown(m):
|
||||
lines = ["# Медиа Хаб", ""]
|
||||
|
||||
cont = m["continue"].get("items") or []
|
||||
lines.append("## Продолжить просмотр")
|
||||
if cont:
|
||||
for c in cont:
|
||||
lines.append(f"* {c['title']} — {c['pct']}%, осталось {c['left_min']} мин ({c['user']})")
|
||||
else:
|
||||
lines.append("_сейчас ничего не досмотрено_")
|
||||
lines.append("")
|
||||
|
||||
req = m["requests"]
|
||||
lines.append("## Заявки")
|
||||
if req.get("by_status"):
|
||||
parts = ", ".join(f"{k}: {v}" for k, v in req["by_status"].items())
|
||||
lines.append(f"всего {req.get('total', 0)} — {parts}")
|
||||
for r in (req.get("items") or [])[:8]:
|
||||
lines.append(f"* {r['title']} — {r['status']}")
|
||||
else:
|
||||
lines.append("_заявок нет_")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Качается")
|
||||
q = m["queue"]
|
||||
for name in ("sonarr", "radarr"):
|
||||
block = q[name]
|
||||
if block.get("error"):
|
||||
lines.append(f"* {name}: ошибка ({block['error']})")
|
||||
continue
|
||||
total = block.get("total", 0)
|
||||
if total:
|
||||
lines.append(f"* {name}: {total} в очереди")
|
||||
for i in (block.get("items") or [])[:3]:
|
||||
lines.append(f" - {i['title']} ({i.get('left') or '?'})")
|
||||
else:
|
||||
lines.append(f"* {name}: пусто")
|
||||
lines.append("")
|
||||
|
||||
miss = m["missing"]
|
||||
lines.append("## Не хватает")
|
||||
lines.append(f"* сериалы: {miss.get('сериалы')} · фильмы: {miss.get('фильмы')}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Место")
|
||||
for d in m["disks"].get("items") or []:
|
||||
lines.append(f"* {d['path']}: свободно {d['free']} из {d['total']} ({d['used_pct']}%)")
|
||||
lines.append("")
|
||||
|
||||
content = m.get("content") or {}
|
||||
if content.get("total"):
|
||||
lines.append("## Связи контента")
|
||||
parts = ", ".join(f"{k}: {v}" for k, v in content["by_relation"].items())
|
||||
lines.append(f"всего {content['total']} — {parts}")
|
||||
lines.append("")
|
||||
|
||||
health_items = m["health"].get("items") or []
|
||||
if health_items:
|
||||
lines.append("## Здоровье служб")
|
||||
for h in health_items[:6]:
|
||||
lines.append(f"* {h.get('service')}: {h.get('message') or h.get('error')}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
data = collect()
|
||||
text = render_markdown(data)
|
||||
print(text)
|
||||
|
||||
payload = {"key": "snapshot", "payload": {"markdown": text, "data": data},
|
||||
"tags": ["медиа"]}
|
||||
try:
|
||||
req = urllib.request.Request(f"{CORE}/data/media",
|
||||
data=json.dumps(payload, ensure_ascii=False).encode(),
|
||||
method="POST", headers={"Content-Type": "application/json"})
|
||||
urllib.request.urlopen(req, timeout=15).read()
|
||||
except Exception as e:
|
||||
print("\nне сохранил в ядро:", str(e)[:80])
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,63 @@
|
||||
# Граф контента
|
||||
|
||||
Связи между фильмами, книгами, сериями и авторами — то, что превращает
|
||||
список файлов в медиатеку.
|
||||
|
||||
## Что строится
|
||||
|
||||
| Связь | Как определяется |
|
||||
|---|---|
|
||||
| фильм → коллекция («входит в») | `collection` из Radarr (TMDB-франшиза) |
|
||||
| книга → автор («написал») | авторы из Calibre |
|
||||
| книга → серия («входит в серию») | серия из Calibre |
|
||||
| книга ↔ фильм («экранизация») | нормализованное название совпадает |
|
||||
| коллекция ↔ книжная серия («общая вселенная») | название коллекции без слова Collection = название серии |
|
||||
|
||||
Нормализация названий: нижний регистр, без знаков, без слов «часть»,
|
||||
«chapter», «том», «книга».
|
||||
|
||||
## Результат на реальных данных
|
||||
|
||||
Наполнение: 5 фильмов (Radarr) + 4 книги (Calibre, созданы как EPUB
|
||||
с метаданными).
|
||||
|
||||
```
|
||||
фильмов: 5, книг: 4
|
||||
карточек создано/обновлено: 21, связей: 19
|
||||
|
||||
Связи по типам:
|
||||
входит в: 5
|
||||
написал: 4
|
||||
входит в серию: 3
|
||||
общая вселенная: 1
|
||||
экранизация: 1
|
||||
```
|
||||
|
||||
Граф:
|
||||
|
||||
```
|
||||
Dune Collection ← Dune (2021)
|
||||
Dune Collection ← Dune: Part Two (2024)
|
||||
The Matrix Collection ← The Matrix (1999)
|
||||
The Matrix Collection ← The Matrix Reloaded (2003)
|
||||
The Matrix Collection ← The Matrix Revolutions (2003)
|
||||
|
||||
Dune → Frank Herbert (написал)
|
||||
Dune Messiah → Dune (входит в серию)
|
||||
Dune ↔ Dune (2021) (экранизация)
|
||||
Dune Collection ⇄ Dune (общая вселенная)
|
||||
```
|
||||
|
||||
## Куда попадает
|
||||
|
||||
* ядро: карточки и связи (`GET /links` — сводка и список);
|
||||
* Медиа Хаб: блок «Связи контента»;
|
||||
* бот Медиа: команда `хаб`;
|
||||
* расписание: ежедневно 04:45.
|
||||
|
||||
## Что это даёт
|
||||
|
||||
* «есть ли книга, по которой снят фильм» — связь `экранизация`;
|
||||
* «что ещё из этой франшизы» — `входит в`;
|
||||
* «какие книги того же автора» — `написал`;
|
||||
* «вся вселенная» — коллекция фильмов ↔ книжная серия.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Почему не добавлялся контент: метаданные через VPS
|
||||
|
||||
## Симптом
|
||||
|
||||
Radarr отвечал `500: Site responded with browser content instead of api data`
|
||||
на любую попытку добавить фильм. Библиотеки были пусты, добавлять было
|
||||
нечего.
|
||||
|
||||
## Диагноз
|
||||
|
||||
* `api.themoviedb.org` с узла отвечает **401 «Invalid API key»** — сеть есть,
|
||||
это нормальный ответ без ключа.
|
||||
* Radarr использует не TMDB напрямую, а **SkyHook**: `api.radarr.video`.
|
||||
* С домашнего IP `api.radarr.video` отдаёт **403** со страницей Cloudflare
|
||||
(«Performance & security by Cloudflare»).
|
||||
* **С VPS тот же запрос отдаёт 200.**
|
||||
|
||||
То есть блокировка по IP: домашний адрес в чёрном списке Cloudflare,
|
||||
адрес VPS — нет.
|
||||
|
||||
## Решение
|
||||
|
||||
На VPS уже работал `tinyproxy` (порт 8888), но он разрешал только
|
||||
`100.64.0.0/10` и `172.16.0.0/12` — то есть Tailscale-сеть.
|
||||
|
||||
1. Проверка: `curl -x http://100.64.0.2:8888 https://api.radarr.video/...`
|
||||
→ **200**.
|
||||
2. Контейнеры Radarr/Sonarr не видят Tailscale-адрес, поэтому на узле
|
||||
поднят проброс: `socat TCP-LISTEN:8888,fork TCP:100.64.0.2:8888`
|
||||
(служба `tmdb-proxy`).
|
||||
3. В Radarr и Sonarr включён прокси `192.168.1.10:8888` с обходом
|
||||
`localhost,127.0.0.1` — чтобы локальные вызовы шли напрямую.
|
||||
|
||||
## Результат
|
||||
|
||||
```
|
||||
curl -x http://192.168.1.10:8888 https://api.radarr.video/... → 200
|
||||
radarr: прокси=True 192.168.1.10:8888
|
||||
sonarr: прокси=True 192.168.1.10:8888
|
||||
|
||||
✅ The Matrix
|
||||
✅ The Matrix Reloaded
|
||||
✅ The Matrix Revolutions
|
||||
✅ Dune
|
||||
✅ Dune: Part Two
|
||||
```
|
||||
|
||||
## Ловушки
|
||||
|
||||
* `PUT /api/v3/config/host` требует `allowedHosts` — без него 400
|
||||
«Allowed Hosts is required when Authentication Required is not Enabled»,
|
||||
а значение `*` не принимается: нужен список хостов через запятую.
|
||||
* Прокси на Tailscale-адрес из контейнера не работает — нужен проброс
|
||||
через IP узла.
|
||||
* Успешное сохранение возвращает **202**, а не 200 — это нормально.
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Граф контента: связи между фильмами, книгами, коллекциями и авторами.
|
||||
|
||||
Строит карточки и связи в ядре:
|
||||
фильм → коллекция «входит в»
|
||||
книга → серия «входит в серию»
|
||||
книга → автор «написал»
|
||||
книга ↔ фильм «экранизация»
|
||||
коллекция ↔ серия книг «общая вселенная»
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
||||
RADARR = os.environ.get("RADARR_URL", "http://192.168.1.118:7878")
|
||||
RADARR_KEY = os.environ.get("RADARR_KEY", "")
|
||||
|
||||
|
||||
def get(url, headers=None, timeout=20):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers=headers or {})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def post(path, payload):
|
||||
req = urllib.request.Request(f"{CORE}{path}",
|
||||
data=json.dumps(payload, ensure_ascii=False).encode(),
|
||||
method="POST", headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").lower().replace("ё", "е")
|
||||
s = re.sub(r"[:!?.,'’\"()\[\]]", " ", s)
|
||||
s = re.sub(r"\b(part|chapter|часть|том|книга)\b", " ", s)
|
||||
return " ".join(s.split())
|
||||
|
||||
|
||||
# ─────────── источники ───────────
|
||||
|
||||
def movies():
|
||||
data, err = get(f"{RADARR}/api/v3/movie", {"X-Api-Key": RADARR_KEY})
|
||||
if err:
|
||||
print(f" Radarr: ошибка {err}")
|
||||
return []
|
||||
out = []
|
||||
for m in data or []:
|
||||
col = m.get("collection") or {}
|
||||
out.append({
|
||||
"title": m.get("title"), "year": m.get("year"),
|
||||
"tmdb": m.get("tmdbId"),
|
||||
"collection": col.get("title"), "collection_tmdb": col.get("tmdbId"),
|
||||
"genres": m.get("genres") or [],
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def books():
|
||||
script = """
|
||||
import json, sqlite3
|
||||
c = sqlite3.connect('/opt/books/library/metadata.db')
|
||||
q = '''select b.id, b.title, b.series_index, s.name
|
||||
from books b left join books_series_link l on l.book = b.id
|
||||
left join series s on s.id = l.series'''
|
||||
rows = []
|
||||
for bid, title, idx, series in c.execute(q):
|
||||
authors = [r[0] for r in c.execute(
|
||||
'select a.name from authors a join books_authors_link l on l.author = a.id where l.book = ?', (bid,))]
|
||||
rows.append({"id": bid, "title": title, "series": series,
|
||||
"series_index": idx, "authors": authors})
|
||||
print(json.dumps(rows, ensure_ascii=False))
|
||||
"""
|
||||
path = "/tmp/books.json"
|
||||
open(path, "w", encoding="utf-8").write(script)
|
||||
subprocess.run(["pct", "push", "111", path, path, "--perms", "644"],
|
||||
capture_output=True, timeout=30)
|
||||
out = subprocess.run(["pct", "exec", "111", "--", "python3", path],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
try:
|
||||
return json.loads(out.stdout or "[]")
|
||||
except Exception:
|
||||
print(" Calibre: не прочитал", (out.stderr or "")[:80])
|
||||
return []
|
||||
|
||||
|
||||
# ─────────── граф ───────────
|
||||
|
||||
def main():
|
||||
mv = movies()
|
||||
bk = books()
|
||||
print(f"фильмов: {len(mv)}, книг: {len(bk)}")
|
||||
|
||||
ids = {}
|
||||
made_cards = 0
|
||||
made_links = 0
|
||||
|
||||
def card(kind, key, title, status=None):
|
||||
nonlocal made_cards
|
||||
res, err = post("/entity", {"kind": kind, "key": key, "title": title, "status": status})
|
||||
if err or not res:
|
||||
return None
|
||||
made_cards += 1
|
||||
ids[key] = res.get("id")
|
||||
return res.get("id")
|
||||
|
||||
def link(a, b, relation):
|
||||
nonlocal made_links
|
||||
if not a or not b or a == b:
|
||||
return
|
||||
_, err = post("/link", {"from": a, "to": b, "relation": relation})
|
||||
if not err:
|
||||
made_links += 1
|
||||
|
||||
# фильмы
|
||||
for m in mv:
|
||||
card("фильм", f"tmdb:{m['tmdb']}", f"{m['title']} ({m['year']})", "в медиатеке")
|
||||
|
||||
# коллекции
|
||||
for m in mv:
|
||||
if m["collection"]:
|
||||
key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}"
|
||||
card("коллекция", key, m["collection"], "франшиза")
|
||||
link(ids.get(f"tmdb:{m['tmdb']}"), ids.get(key), "входит в")
|
||||
|
||||
# книги
|
||||
for b in bk:
|
||||
card("книга", f"calibre:{b['id']}", b["title"], "в библиотеке")
|
||||
for author in b.get("authors") or []:
|
||||
key = f"author:{norm(author)}"
|
||||
card("автор", key, author)
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(key), "написал")
|
||||
if b.get("series"):
|
||||
key = f"series:{norm(b['series'])}"
|
||||
card("серия книг", key, b["series"], "книжная серия")
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(key), "входит в серию")
|
||||
|
||||
# экранизации: книга ↔ фильм по названию
|
||||
by_title = {}
|
||||
for m in mv:
|
||||
by_title.setdefault(norm(m["title"]), []).append(("фильм", m["tmdb"]))
|
||||
for b in bk:
|
||||
for kind, ident in by_title.get(norm(b["title"]), []):
|
||||
link(ids.get(f"calibre:{b['id']}"), ids.get(f"tmdb:{ident}"), "экранизация")
|
||||
|
||||
# общая вселенная: коллекция фильмов ↔ книжная серия с тем же названием
|
||||
for m in mv:
|
||||
if not m["collection"]:
|
||||
continue
|
||||
col_key = f"collection:{m['collection_tmdb'] or norm(m['collection'])}"
|
||||
col_norm = norm(m["collection"]).replace("collection", "").strip()
|
||||
for b in bk:
|
||||
if b.get("series") and norm(b["series"]) == col_norm:
|
||||
link(ids.get(col_key), ids.get(f"series:{norm(b['series'])}"), "общая вселенная")
|
||||
|
||||
print(f"карточек создано/обновлено: {made_cards}, связей: {made_links}")
|
||||
|
||||
# сводка по типам связей
|
||||
from collections import Counter
|
||||
try:
|
||||
import urllib.request as u
|
||||
with u.urlopen(f"{CORE}/entity/{list(ids.values())[0]}", timeout=20) as r:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -169,6 +169,16 @@ def health():
|
||||
return {"items": out}
|
||||
|
||||
|
||||
|
||||
|
||||
def content_links():
|
||||
"""Связи контента: сводка из ядра."""
|
||||
data, err = get(f"{CORE}/links")
|
||||
if err:
|
||||
return {"total": 0, "by_relation": {}}
|
||||
return {"total": (data or {}).get("total", 0),
|
||||
"by_relation": (data or {}).get("by_relation") or {}}
|
||||
|
||||
def collect():
|
||||
return {
|
||||
"continue": continue_watching(),
|
||||
@@ -178,6 +188,7 @@ def collect():
|
||||
"missing": missing(),
|
||||
"disks": disks(),
|
||||
"health": health(),
|
||||
"content": content_links(),
|
||||
}
|
||||
|
||||
|
||||
@@ -232,6 +243,13 @@ def render_markdown(m):
|
||||
lines.append(f"* {d['path']}: свободно {d['free']} из {d['total']} ({d['used_pct']}%)")
|
||||
lines.append("")
|
||||
|
||||
content = m.get("content") or {}
|
||||
if content.get("total"):
|
||||
lines.append("## Связи контента")
|
||||
parts = ", ".join(f"{k}: {v}" for k, v in content["by_relation"].items())
|
||||
lines.append(f"всего {content['total']} — {parts}")
|
||||
lines.append("")
|
||||
|
||||
health_items = m["health"].get("items") or []
|
||||
if health_items:
|
||||
lines.append("## Здоровье служб")
|
||||
|
||||
Reference in new issue
Block a user