GET /candidates отдаёт кандидатов, отсортированных по числу рекомендаций (votes). Команда «пополнить N» добавляет первых N в Radarr с searchForMovie: false — карточки появляются, файлы не качаются. Проверено: «пополнить 2» добавил Terminator 2 и Terminator Salvation; в Radarr стало 14 фильмов, файлов нет ни у одного. После пересборки графа: 414 карточек, 455 связей. Повторное добавление ловится как «уже есть» и попадает в список неудачных.
150 lines
3.6 KiB
Python
150 lines
3.6 KiB
Python
"""Клиент API ядра для ботов."""
|
|
import json
|
|
import os
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
|
|
|
|
|
def _get(path, params=None, timeout=10):
|
|
url = f"{CORE}{path}"
|
|
if params:
|
|
url += "?" + urllib.parse.urlencode(params)
|
|
try:
|
|
with urllib.request.urlopen(url, 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)[:120]
|
|
|
|
|
|
def _post(path, payload, timeout=15):
|
|
req = urllib.request.Request(f"{CORE}{path}", data=json.dumps(payload).encode(),
|
|
method="POST", headers={"Content-Type": "application/json"})
|
|
try:
|
|
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)[:120]
|
|
|
|
|
|
def alive():
|
|
data, err = _get("/health", timeout=5)
|
|
return bool(data and data.get("ok")), err
|
|
|
|
|
|
def search(q, limit=20):
|
|
return _get("/search", {"q": q})
|
|
|
|
|
|
def card(eid):
|
|
return _get(f"/entity/{eid}")
|
|
|
|
|
|
def events(limit=30):
|
|
return _get("/events")
|
|
|
|
|
|
def stats():
|
|
return _get("/health")
|
|
|
|
|
|
def save_data(collection, key, payload, tags=None):
|
|
"""Сохранить документ в коллекцию."""
|
|
return _post(f"/data/{collection}", {"key": key, "payload": payload, "tags": tags or []})
|
|
|
|
|
|
def get_data(collection, limit=100, tag=None):
|
|
params = {"limit": limit}
|
|
if tag:
|
|
params["tag"] = tag
|
|
return _get(f"/data/{collection}", params)
|
|
|
|
|
|
def export_data(collection, fmt="md", filename=None):
|
|
"""Выгрузить коллекцию в папку проекта."""
|
|
body = {"collection": collection, "format": fmt}
|
|
if filename:
|
|
body["filename"] = filename
|
|
return _post("/export", body)
|
|
|
|
|
|
def services():
|
|
return _get("/services")
|
|
|
|
|
|
def service_history(name, limit=30):
|
|
return _get(f"/service/{name}", {"limit": limit})
|
|
|
|
|
|
def find_entity(text, kinds=None):
|
|
data, err = _get("/search", {"q": text, "limit": 20})
|
|
if err:
|
|
return None, err
|
|
items = (data or {}).get("items") or []
|
|
if kinds:
|
|
items = [i for i in items if i.get("kind") in kinds]
|
|
return (items[0] if items else None), None
|
|
|
|
|
|
def links_of(entity_id):
|
|
return _get("/entity/%s" % entity_id)
|
|
|
|
|
|
def entities(kind=None, limit=200):
|
|
data, err = _get("/entities", {"limit": limit})
|
|
if err:
|
|
return [], err
|
|
items = (data or {}).get("items") or []
|
|
if kind:
|
|
items = [i for i in items if i.get("kind") == kind]
|
|
return items, None
|
|
|
|
|
|
def similar(entity_id, limit=10):
|
|
return _get("/similar", {"id": entity_id, "limit": limit})
|
|
|
|
|
|
def person(query):
|
|
return _get("/person", {"q": query})
|
|
|
|
|
|
def pick(genre=None, theme=None, decade=None, limit=10):
|
|
params = {"limit": limit}
|
|
if genre:
|
|
params["genre"] = genre
|
|
if theme:
|
|
params["theme"] = theme
|
|
if decade:
|
|
params["decade"] = decade
|
|
return _get("/pick", params)
|
|
|
|
|
|
def timeline(query, kind="тема"):
|
|
return _get("/timeline", {"q": query, "kind": kind})
|
|
|
|
|
|
def cross_format():
|
|
return _get("/cross")
|
|
|
|
|
|
def top_persons(kind="актёр"):
|
|
return _get("/persons", {"kind": kind})
|
|
|
|
|
|
def graph_stats():
|
|
return _get("/graph")
|
|
|
|
|
|
def mood(word, limit=10):
|
|
return _get("/mood", {"mood": word, "limit": limit})
|
|
|
|
|
|
def candidates(limit=20):
|
|
return _get("/candidates", {"limit": limit})
|