Добавлены 5 сериалов через Sonarr (The Expanse, Dark, Foundation, Westworld, Severance) — метаданные без скачивания. Новый вид карточки «сеть» (Netflix, HBO, Apple TV, Prime Video). Связи: сериал → жанр, сериал → сеть, сериал → эпоха, сериал ↔ сериал «похож», книга ↔ сериал «экранизация» (Foundation), серия книг ↔ сериал «общая вселенная». Итог: 449 карточек, 493 связи. Подбор и Агент понимают сериалы: «посмотреть сериалы», «агент найди сериалы про будущее». Ловушки: Sonarr хранит год в названии (Foundation (2021) → карточка Foundation (2021) (2021), связь с книгой не строилась); поиск по названию даёт не тот сериал — нужен tvdb:<id>; api.sonarr.tv недоступен, поэтому состава съёмочной группы у сериалов нет; «посмотреть сериалы» ломалось из-за порядка вырезания слов.
77 lines
2.9 KiB
Python
77 lines
2.9 KiB
Python
"""Добавляет сериалы в Sonarr по названию (метаданные, без скачивания)."""
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
SONARR = os.environ.get("SONARR_URL", "http://192.168.1.117:8989")
|
|
KEY = os.environ.get("SONARR_KEY", "")
|
|
TITLES = ["The Expanse", "Foundation", "Severance", "Dark", "Westworld"]
|
|
|
|
|
|
def call(path, method="GET", body=None, timeout=90):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(SONARR + path, data=data, method=method,
|
|
headers={"X-Api-Key": KEY, "Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
raw = r.read()
|
|
return r.status, (json.loads(raw) if raw else None)
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()[:200].decode("utf-8", "replace")
|
|
except Exception as e:
|
|
return 0, str(e)[:120]
|
|
|
|
|
|
def main():
|
|
if not KEY:
|
|
print("нет SONARR_KEY")
|
|
return 2
|
|
|
|
_, existing = call("/api/v3/series")
|
|
have = {s.get("title") for s in (existing or [])}
|
|
print("уже в Sonarr:", ", ".join(sorted(have)) or "нет")
|
|
|
|
added = []
|
|
for title in TITLES:
|
|
if title in have:
|
|
print(f" · {title} уже есть")
|
|
continue
|
|
code, res = call("/api/v3/series/lookup?term=" + urllib.parse.quote(title))
|
|
if code != 200 or not isinstance(res, list) or not res:
|
|
print(f" ❌ {title}: поиск {code}")
|
|
continue
|
|
best = next((r for r in res if r.get("title", "").lower() == title.lower()), res[0])
|
|
payload = {
|
|
"title": best.get("title"),
|
|
"tvdbId": best.get("tvdbId"),
|
|
"year": best.get("year"),
|
|
"qualityProfileId": 1,
|
|
"languageProfileId": 1,
|
|
"rootFolderPath": "/data/series",
|
|
"seasonFolder": True,
|
|
"monitored": True,
|
|
"addOptions": {"ignoreEpisodesWithFiles": False,
|
|
"ignoreEpisodesWithoutFiles": True,
|
|
"searchForMissingEpisodes": False},
|
|
}
|
|
code2, res2 = call("/api/v3/series", "POST", payload)
|
|
if code2 in (200, 201):
|
|
print(f" ✅ {title} ({best.get('year')}), сезонов: {len(best.get('seasons') or [])}")
|
|
added.append(title)
|
|
else:
|
|
print(f" ❌ {title}: {code2} {str(res2)[:80]}")
|
|
|
|
_, final = call("/api/v3/series")
|
|
print(f"\nсериалов в Sonarr: {len(final or [])}")
|
|
for s in (final or []):
|
|
seasons = len([x for x in (s.get("seasons") or []) if x.get("seasonNumber", 0) > 0])
|
|
print(f" • {s.get('title')} ({s.get('year')}) — сезонов: {seasons}, "
|
|
f"сеть: {s.get('network')}, статус: {s.get('status')}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|