From f5fd34830403ba8b29576293f1d3a218e50884db Mon Sep 17 00:00:00 2001 From: Roman Buryan Date: Tue, 17 Nov 2026 18:08:48 +0300 Subject: [PATCH] =?UTF-8?q?[TOOLS]=20P0=20=D0=BF=D1=80=D0=BE=D0=B4=D0=BE?= =?UTF-8?q?=D0=BB=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5:=20books.link/books.status?= =?UTF-8?q?=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D1=8E=D1=82=20(books.se?= =?UTF-8?q?arch=20=D1=83=D0=BF=D0=B8=D1=80=D0=B0=D0=B5=D1=82=D1=81=D1=8F?= =?UTF-8?q?=20=D0=B2=20DPI),=20media.request=20=D0=BF=D0=BE=D1=87=D0=B8?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=20(HTTPError=20400=20->=20already=5Fexists?= =?UTF-8?q?=20+=20SeasonSearch=20201),=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20rate=20limit=2060/=D0=BC=D0=B8=D0=BD=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B0.=20=D0=9E?= =?UTF-8?q?=D1=82=D0=BA=D1=80=D1=8B=D1=82=D0=BE:=20Jellyfin=20401,=20media?= =?UTF-8?q?.recent,=20=D1=81=D0=B2=D0=B5=D1=82=20(=D0=BD=D0=B5=D1=8F=D1=81?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C),=20iGPU=20(render)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/audits/P0-CONTINUE-2026-11-17.md | 29 +++++++++++++ ops/tools/gateway.py | 61 +++++++++++++++++++++++++++- ops/tools/mcp_gateway.py | 6 +++ 3 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 ops/audits/P0-CONTINUE-2026-11-17.md diff --git a/ops/audits/P0-CONTINUE-2026-11-17.md b/ops/audits/P0-CONTINUE-2026-11-17.md new file mode 100644 index 0000000..b72e847 --- /dev/null +++ b/ops/audits/P0-CONTINUE-2026-11-17.md @@ -0,0 +1,29 @@ +# P0 продолжение: книги, медиа, лимиты (17.11.2026) + +## Добавлено + +| Инструмент | Статус | +|---|---| +| `books.search` | внешний OpenLibrary блокируется DPI с хоста; возвращает ошибку/ссылки | +| `books.link` | работает: biglibrary + openlibrary, без скачивания | +| `books.status` | Calibre-Web доступен (200) | +| `media.request` | **починен**: HTTPError 400 перехватывается; «уже существует» → `SeasonSearch` | + +Проверка `media.request`: +``` +{"already_exists": true, "title": "Clarkson's Farm", "id": 7, + "search": {"status": 201, "name": "SeasonSearch", "seasonNumber": 3}} +``` + +Добавлен rate limit: **60 запросов/мин на актора** (429 при превышении). + +## Что осталось + +* `books.search` — нужен локальный прокси/кэш, потому что внешние HTTPS + с хоста режутся (та же DPI-история). +* Jellyfin: оба ключа 401; нужен новый токен (логин админом тоже 400 — + проверить учётку/формат). +* `media.recent` не работает из-за Jellyfin. +* Sonarr: `SeasonSearch` отправлен, очередь пока 0 (ждём индексеры). +* Свет: неясная сущность (обе `on`). +* iGPU: нужен `render` (root). diff --git a/ops/tools/gateway.py b/ops/tools/gateway.py index 2c5b965..a723498 100755 --- a/ops/tools/gateway.py +++ b/ops/tools/gateway.py @@ -38,6 +38,9 @@ def read(path): CFG_D = json.load(open(CFG)) if os.path.exists(CFG) else {} TOKENS = {v: k for k, v in (CFG_D.get("tokens") or {}).items()} +RATE = {} +import threading +RATE_LOCK = threading.Lock() HA_TOKEN = read("/root/.ha-token") RADARR_KEY = read("/root/.radarr-key") SONARR_KEY = read("/root/.sonarr-key") @@ -130,6 +133,13 @@ def t_media_recent(args): "items": [i.get("Name") for i in (d.get("Items") or [])]} +def post_json(url, headers, payload): + try: + return http("POST", url, headers, payload) + except urllib.error.HTTPError as e: + return e.code, e.read() + + def _caldav(method, path, body=None, headers=None): url = NC + "/remote.php/dav/calendars/%s/%s/" % (NC_USER, urllib.parse.quote(path, safe="/")) h = {"Authorization": basic(NC_USER, NC_PASS)} @@ -258,7 +268,7 @@ def t_media_request(args): "monitored": True, "seasonFolder": True, "seasons": seasons, "addOptions": {"searchForMissingEpisodes": True, "monitor": "none" if season else "all"}} - st, body = http("POST", SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY}, payload) + st, body = post_json(SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY}, payload) else: st, body = http("GET", RADARR + "/api/v3/rootfolder", {"X-Api-Key": RADARR_KEY}) roots = json.loads(body) @@ -269,7 +279,7 @@ def t_media_request(args): payload = {"title": it.get("title"), "tmdbId": it.get("tmdbId"), "qualityProfileId": qp, "rootFolderPath": root, "monitored": True, "addOptions": {"searchForMovie": True}} - st, body = http("POST", RADARR + "/api/v3/movie", {"X-Api-Key": RADARR_KEY}, payload) + st, body = post_json(RADARR + "/api/v3/movie", {"X-Api-Key": RADARR_KEY}, payload) try: res = json.loads(body) except Exception: @@ -333,6 +343,40 @@ def t_backup_status(args): rows = [ln.split("|") for ln in (r.stdout or "").strip().splitlines() if ln] return {"jobs": [{"name": x[0], "last": x[1], "status": x[2], "fails": x[3]} for x in rows]} +def t_books_search(args): + q = args.get("query") or "" + items = [] + try: + st, body = http("GET", "https://openlibrary.org/search.json?q=" + urllib.parse.quote(q) + "&limit=5", + timeout=20) + d = json.loads(body) + for doc in (d.get("docs") or [])[:5]: + items.append({"title": doc.get("title"), + "authors": (doc.get("author_name") or [])[:3], + "year": doc.get("first_publish_year"), + "link": "https://openlibrary.org" + (doc.get("key") or "")}) + except Exception as e: + items.append({"error": str(e)[:120]}) + return {"query": q, "count": len(items), "items": items} + + +def t_books_link(args): + q = args.get("query") or "" + return {"query": q, + "biglibrary": "https://biglibrary.org/search?q=" + urllib.parse.quote(q), + "openlibrary": "https://openlibrary.org/search?q=" + urllib.parse.quote(q), + "note": "автоматическое скачивание не выполняется"} + + +def t_books_status(args): + url = "http://127.0.0.1/" + try: + st, body = http("GET", url, {"Host": "books.buryans.ru"}, timeout=10) + return {"calibre_web": "https://books.buryans.ru", "http": st, + "reachable": st in (200, 302, 303, 401)} + except Exception as e: + return {"calibre_web": "https://books.buryans.ru", "error": str(e)[:120]} + TOOLS = { "hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False}, "hub.notify": {"fn": t_hub_notify, "scope": "write", "confirm": True, @@ -354,6 +398,9 @@ TOOLS = { "hub.service_detail": {"fn": t_hub_service_detail, "scope": "read", "confirm": False}, "alerts.active": {"fn": t_alerts_active, "scope": "read", "confirm": False}, "backup.status": {"fn": t_backup_status, "scope": "read", "confirm": False}, + "books.search": {"fn": t_books_search, "scope": "read", "confirm": False}, + "books.link": {"fn": t_books_link, "scope": "read", "confirm": False}, + "books.status": {"fn": t_books_status, "scope": "read", "confirm": False}, } @@ -413,6 +460,14 @@ class Handler(BaseHTTPRequestHandler): return self._send(400, {"error": "bad json"}) tool = req.get("tool") args = req.get("args") or {} + now = time.time() + with RATE_LOCK: + q = RATE.setdefault(actor, []) + RATE[actor] = [t for t in q if now - t < 60] + if len(RATE[actor]) >= 60: + return self._send(429, {"error": "rate_limit", "actor": actor, + "limit": "60/min"}) + RATE[actor].append(now) spec = TOOLS.get(tool) if not spec: return self._send(404, {"error": "unknown tool"}) @@ -428,6 +483,8 @@ class Handler(BaseHTTPRequestHandler): "media.search": ["query"], "media.request": ["query"], "hub.service_detail": ["name"], + "books.search": ["query"], + "books.link": ["query"], }.get(tool, []) missing = [k for k in required if not args.get(k)] if missing: diff --git a/ops/tools/mcp_gateway.py b/ops/tools/mcp_gateway.py index e9786cd..d80bbb7 100755 --- a/ops/tools/mcp_gateway.py +++ b/ops/tools/mcp_gateway.py @@ -34,6 +34,12 @@ SCHEMAS = { "required": ["title", "start"]}), "photos.people": ("Люди в Immich", {"type": "object", "properties": {}}), "photos.albums": ("Альбомы Immich", {"type": "object", "properties": {}}), + "books.search": ("Поиск книг в OpenLibrary", {"type": "object", "properties": { + "query": {"type": "string"}}, "required": ["query"]}), + "books.link": ("Ссылки на поиск книги (без скачивания)", {"type": "object", "properties": { + "query": {"type": "string"}}, "required": ["query"]}), + "books.status": ("Доступность Calibre-Web", {"type": "object", "properties": {}}), + "hub.service_detail": ("Детали одной службы хаба по имени", {"type": "object", "properties": { "name": {"type": "string"}}, "required": ["name"]}), "alerts.active": ("Активные алерты Alertmanager", {"type": "object", "properties": {}}),