[TOOLS] P0 продолжение: books.link/books.status работают (books.search упирается в DPI), media.request починен (HTTPError 400 -> already_exists + SeasonSearch 201), добавлен rate limit 60/мин на актора. Открыто: Jellyfin 401, media.recent, свет (неясная сущность), iGPU (render)
This commit is contained in:
1 parent
088f2629bd
commit
f5fd348304
3 files changed
+94
-2
No files matched your search
@@ -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).
|
||||
+59
-2
@@ -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:
|
||||
|
||||
@@ -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": {}}),
|
||||
|
||||
Reference in new issue
Block a user