The core API keys page (backend/apikeys/, business/apiKeys/) and the host
sidecar's /homelab-env writer are retired: a managed plugin that declares
managed.keyHealth gets the same page on its Settings page, generic.
Manifest
- settings.links[]: {label, url} https:// links with {{config.<field>}}
placeholders (URL-quoted; a link whose field is empty is left out).
- managed.keyHealth: alertLimit + currency (alertLimitEur still reads),
secretKey (default: the first hub secret), legacyLedgerTool (a core ledger
tool whose rows count as the plugin's spend: nanobanana → plugin:nanobanana).
Store / metering
- set_secret keeps a non-secret last-4 hint (installed.json → secretHints);
secrets stored before hints get theirs on first read.
- Runtime key settings per plugin (alertLimit, currency, pushAtPct,
pushOnBreak) over the manifest defaults.
- Key health: ok / broken states set the state, other failures are listed
only; a break pushes once (type error), the recovery once ("✅ <Plugin> key
works again", type success); the month pushes at pushAtPct and at 100 %,
each once per month; spend merges the legacy ledger tool.
Routes
- GET /api/plugins/{pid}/spend (plugins.manage): health + hint, settings,
month, byCaller, byModel, 30 days with failures, recent successes +
failures with session links, the links filled in (plugins/keyspend.py).
- PUT /api/plugins/{pid}/key-settings (plugins.manage).
- POST /api/plugins/{pid}/test records the testAction's verdict (its _meter
billed as via "test", or a structured _error whose kind is a key state).
- PUT /api/plugins/{pid}/secrets/{key} on the watched hub key: checked with
testAction before saving — the run's handler token carries the candidate in
memory (plugins.proxy.register_candidate) so its proxy calls use it;
invalid / denied → 400, no-credit / capped → saved, anything else → 502.
- /proxy/tools/nanobanana/<model> (the cli hub edition) reads the plugin's hub
key and feeds its health; Gemini's classify moves to toolproxy/catalog.
Frontend
- PluginKeyHealthSection (status + hint + Test / Replace + links, month with
progress, threshold marker and the limit / currency / alerts form, by caller
/ model + 30-day bars with failure dots, recent calls) on PluginSettingsPage
for the owner; /settings/api-keys redirects to /settings/plugin/nanobanana;
the settings entry, mock, lazy page and unused French strings go.
openapi.json is not re-dumped here (the coordinator does it after Batch 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
735 lines
33 KiB
Python
735 lines
33 KiB
Python
"""
|
||
``/proxy/tools/…`` — the lab's paid tools for guests (their lab runs and
|
||
their own computers) and for the owner's workers, with every key kept here.
|
||
|
||
Outside ``/api`` like the Claude proxy: no Authelia, no trusted-caller gate.
|
||
The bearer is the whole auth (``access.resolve``): a guest's run token or a
|
||
worker's proxy token. Traefik serves it on ``ai-agent.gabvdl.xyz`` (guests) and on
|
||
``ai-agent.lab`` (``/proxy/``, the owner's workers over the tailnet).
|
||
|
||
* ``POST nanobanana/<model>`` — a Gemini ``generateContent`` request (the
|
||
older hub edition of the skill; the ``nanobanana`` plugin's own action is
|
||
the way now), sent upstream with the Nano Banana plugin's hub key; priced
|
||
from the reply's ``usageMetadata`` into the tool ledger (the guest's tools
|
||
budget, tool ``nanobanana`` — the plugin's ``legacyLedgerTool``), every
|
||
reply's outcome noted on the plugin's key health (its pushes);
|
||
* ``3d-gen/<api path>`` — an allowlist of the 3d-gen service's API, as
|
||
``guest-<uid>`` (``Remote-User``), on that guest's own jobs and models only;
|
||
* ``video-extract/…`` and ``3d-render`` — run on the lab by the host sidecar
|
||
(``sidecar/tools.py``), a guest's videos in a library of their own;
|
||
* ``movies/<op>`` — movie (owner: series) requests through the lab's Seerr
|
||
(``media.py``), and ``movies/webhook`` — Seerr telling the hub back;
|
||
* ``matomo/<op>`` — the lab's Matomo for the guest's own sites (``matomo.py``);
|
||
* ``meta/<op>`` — a guest's own Meta Business, read-only, with the key they
|
||
connected (``meta.py``);
|
||
* ``whoami`` — what the caller may use, and what is left of their budget.
|
||
|
||
The lab's own jobs (EVOX2 / CPU) are free but counted (``usd: 0``).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import hmac
|
||
import json
|
||
import os
|
||
import re
|
||
import time
|
||
|
||
import httpx
|
||
from fastapi import APIRouter, Request
|
||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||
from starlette.background import BackgroundTask
|
||
from starlette.concurrency import run_in_threadpool
|
||
|
||
from core.config import SIDECAR_TOKEN, SIDECAR_URL
|
||
from users.caller import on_public_surface
|
||
from workers import guests
|
||
from . import access, catalog, matomo, media, meta
|
||
from .ledger import LEDGER, month_of
|
||
from .owned import OWNED
|
||
|
||
router = APIRouter()
|
||
|
||
GEMINI_UPSTREAM = catalog.GEMINI_UPSTREAM
|
||
NB_PLUGIN = "nanobanana"
|
||
THREEDGEN_URL = os.environ.get("THREEDGEN_URL", "http://3d-gen:8080").rstrip("/")
|
||
OWNER_3D_USER = os.environ.get("THREEDGEN_OWNER_USER", "claude")
|
||
MAX_JSON = 48 * 1024 ** 2 # a Gemini request with a few input images
|
||
MAX_3D_UPLOAD = 120 * 1024 ** 2 # 1–8 pictures of one object
|
||
MAX_GLB = 300 * 1024 ** 2
|
||
|
||
_client: httpx.AsyncClient | None = None
|
||
|
||
|
||
def _http() -> httpx.AsyncClient:
|
||
global _client
|
||
if _client is None:
|
||
_client = httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=300.0),
|
||
limits=httpx.Limits(max_connections=32))
|
||
return _client
|
||
|
||
|
||
def _error(status: int, message: str, kind: str = "error") -> JSONResponse:
|
||
return JSONResponse({"error": {"message": message, "kind": kind}}, status_code=status)
|
||
|
||
|
||
def _bearer(request: Request) -> str:
|
||
auth = request.headers.get("authorization") or ""
|
||
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
|
||
|
||
|
||
def _deps(request: Request):
|
||
return request.app.state.ai
|
||
|
||
|
||
def _who(request: Request):
|
||
if guests.ip_locked(request):
|
||
return None, _error(429, "too many bad tokens from this address — try again in an hour",
|
||
"locked")
|
||
deps = _deps(request)
|
||
who = access.resolve(deps, _bearer(request), guest_surface=on_public_surface(request))
|
||
if who is None:
|
||
guests.bad_token(deps, request, "/proxy/tools")
|
||
return None, _error(401, "unknown or expired tool token — the hub mints a new one "
|
||
"with each run", "auth")
|
||
return who, None
|
||
|
||
|
||
_last_refusal: dict[tuple[str, str], float] = {}
|
||
|
||
|
||
def _refused(deps, who: access.Who, tool: str, no: tuple) -> JSONResponse:
|
||
status, message, kind = no
|
||
key = (who.key, kind)
|
||
if not who.is_owner and time.time() - _last_refusal.get(key, 0) > 600:
|
||
_last_refusal[key] = time.time()
|
||
try:
|
||
from security.service import record
|
||
record(deps, "guest_tool_refused", who=who.uid, detail=f"{tool}: {message}",
|
||
data={"tool": tool, "kind": kind,
|
||
**({"worker": who.worker["id"]} if who.worker else {})})
|
||
except Exception:
|
||
pass
|
||
return _error(status, message, kind)
|
||
|
||
|
||
async def _check(request: Request, tool: str, **kw):
|
||
"""``(who, None)`` when the call may go ahead, else ``(None, error)``."""
|
||
who, err = _who(request)
|
||
if err:
|
||
return None, err
|
||
deps = _deps(request)
|
||
no = await run_in_threadpool(access.refusal, deps, who, tool, **kw)
|
||
if no:
|
||
return None, _refused(deps, who, tool, no)
|
||
return who, None
|
||
|
||
|
||
def _record(request: Request, who: access.Who, tool: str, *, usd: float = 0.0,
|
||
units: dict | None = None, **extra) -> None:
|
||
sid = access.session_of(_deps(request), who,
|
||
request.headers.get("x-claude-code-session-id"))
|
||
LEDGER.record({"tool": tool, **who.row(), "usd": round(usd, 6), "units": units or {},
|
||
**({"session": sid} if sid else {}),
|
||
**{k: v for k, v in extra.items() if v is not None}})
|
||
if sid:
|
||
# The conversation's tools chip (meta.tools → the card).
|
||
try:
|
||
deps = _deps(request)
|
||
deps.meta_store.update(sid, {"tools": LEDGER.session(sid)})
|
||
deps.hub.publish({"type": "meta", "id": sid})
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
async def _body(request: Request, cap: int) -> bytes | None:
|
||
"""The request body, or None past ``cap`` bytes."""
|
||
chunks, size = [], 0
|
||
async for chunk in request.stream():
|
||
size += len(chunk)
|
||
if size > cap:
|
||
return None
|
||
chunks.append(chunk)
|
||
return b"".join(chunks)
|
||
|
||
|
||
# ── whoami ───────────────────────────────────────────────────────────────────
|
||
@router.get("/proxy/tools/whoami", include_in_schema=False)
|
||
async def whoami(request: Request):
|
||
who, err = _who(request)
|
||
if err:
|
||
return err
|
||
deps = _deps(request)
|
||
cfg = access.config(deps, who)
|
||
tools = [t for t, g in catalog.GROUP_OF.items() if g in cfg["groups"]]
|
||
models = [m for m, p in catalog.NB_MODELS.items()
|
||
if "images" in cfg["groups"] and (cfg["pro"] or not p["pro"])]
|
||
name = "owner"
|
||
if not who.is_owner:
|
||
name = (deps.users.get(who.uid) or {}).get("name") or who.uid
|
||
return {"who": who.key, "name": name, "via": who.via,
|
||
"worker": (who.worker or {}).get("name"), "groups": cfg["groups"],
|
||
"tools": tools, "models": models, "defaultModel": catalog.NB_DEFAULT,
|
||
"pro": cfg["pro"], "budgetUsd": cfg["budgetUsd"],
|
||
"spentUsd": round(LEDGER.spent(who.key), 4)}
|
||
|
||
|
||
# ── Nano Banana ──────────────────────────────────────────────────────────────
|
||
def _nb_key(deps) -> tuple[dict | None, str]:
|
||
"""The Nano Banana plugin's owner record and its hub key ('' when the
|
||
plugin isn't installed or its key isn't set)."""
|
||
try:
|
||
rec = deps.plugin_store.get_raw("owner", NB_PLUGIN)
|
||
except Exception:
|
||
rec = None
|
||
if not rec:
|
||
return None, ""
|
||
spec = ((rec.get("manifest") or {}).get("managed") or {}).get("keyHealth") or {}
|
||
secret = spec.get("secretKey") or "api_key"
|
||
return rec, deps.plugin_store.get_secret("owner", NB_PLUGIN, secret, scope="hub") or ""
|
||
|
||
|
||
def _nb_observe(deps, rec: dict | None, kind: str, msg: str, who, model: str,
|
||
status: int) -> None:
|
||
if not rec:
|
||
return
|
||
from plugins import metering
|
||
metering.observe_key_health(
|
||
deps, NB_PLUGIN, rec["manifest"], kind if kind in metering.KEY_STATES else "error",
|
||
msg, who_row=who.row(), model=model, http_status=status)
|
||
|
||
|
||
@router.post("/proxy/tools/nanobanana/{model}", include_in_schema=False)
|
||
async def nanobanana(request: Request, model: str):
|
||
who, err = await _check(request, "nanobanana", model=model, paid=True)
|
||
if err:
|
||
return err
|
||
deps = _deps(request)
|
||
rec, key = _nb_key(deps)
|
||
if not key:
|
||
return _error(503, "the hub has no Gemini key — set it on Settings → Plugins → Nano Banana",
|
||
"config")
|
||
body = await _body(request, MAX_JSON)
|
||
if body is None:
|
||
return _error(413, f"a request over {MAX_JSON // 1024 ** 2} MB", "size")
|
||
try:
|
||
req = json.loads(body)
|
||
except ValueError:
|
||
return _error(400, "the body is a Gemini generateContent request (JSON)", "body")
|
||
if not isinstance(req, dict) or not isinstance(req.get("contents"), list):
|
||
return _error(400, "the body is a Gemini generateContent request ({contents: […]})", "body")
|
||
name = (catalog.nb_model(model) or (model,))[0]
|
||
access.enter(who, "nanobanana")
|
||
try:
|
||
resp = await _http().post(f"{GEMINI_UPSTREAM}/models/{model}:generateContent",
|
||
params={"key": key}, json=req,
|
||
timeout=httpx.Timeout(30.0, read=300.0))
|
||
except httpx.HTTPError as e:
|
||
await run_in_threadpool(_nb_observe, deps, rec, "error",
|
||
f"couldn't reach Google: {type(e).__name__}", who, name, 0)
|
||
return _error(502, f"the hub couldn't reach Gemini: {type(e).__name__}", "upstream")
|
||
finally:
|
||
access.leave(who, "nanobanana")
|
||
text = resp.text.replace(key, "***")
|
||
try:
|
||
reply = json.loads(text)
|
||
except ValueError:
|
||
await run_in_threadpool(_nb_observe, deps, rec, "error",
|
||
f"HTTP {resp.status_code} without JSON", who, name,
|
||
resp.status_code)
|
||
return _error(502, f"Gemini answered {resp.status_code} without JSON", "upstream")
|
||
kind, msg = catalog.nb_classify(resp.status_code, reply)
|
||
await run_in_threadpool(_nb_observe, deps, rec, kind, msg, who, name, resp.status_code)
|
||
if resp.status_code == 200 and isinstance(reply, dict):
|
||
usd = catalog.nb_cost(model, reply.get("usageMetadata"))
|
||
_record(request, who, "nanobanana", usd=usd,
|
||
units={"images": catalog.count_images(reply)}, model=name)
|
||
if rec:
|
||
from plugins import metering
|
||
await run_in_threadpool(metering.check_spend, deps, NB_PLUGIN, rec["manifest"])
|
||
return JSONResponse(reply, status_code=resp.status_code)
|
||
|
||
|
||
# ── 3d-gen ───────────────────────────────────────────────────────────────────
|
||
_J = r"[0-9a-f]{12}"
|
||
_F = r"[A-Za-z0-9][A-Za-z0-9._-]{0,120}"
|
||
# (method, path, what): open = no owner check; create = a new job; job / folder
|
||
# = on the caller's own job / model folder.
|
||
_3D_ROUTES = [
|
||
("GET", re.compile(r"^api/(config|brain-status|image/models|edits/operations)$"), "open"),
|
||
("POST", re.compile(r"^api/jobs$"), "create"),
|
||
("POST", re.compile(r"^api/jobs/image$"), "create"),
|
||
("GET", re.compile(r"^api/jobs$"), "list"),
|
||
("GET", re.compile(rf"^api/jobs/(?P<job>{_J})$"), "job"),
|
||
("GET", re.compile(rf"^api/jobs/(?P<job>{_J})/source$"), "job"),
|
||
("POST", re.compile(rf"^api/jobs/(?P<job>{_J})/(cancel|retry)$"), "job"),
|
||
("GET", re.compile(rf"^api/models/(?P<folder>{_F})/(rig|retopo|close)$"), "folder"),
|
||
("POST", re.compile(rf"^api/models/(?P<folder>{_F})/(rig|retopo|close)$"), "folder-job"),
|
||
("POST", re.compile(rf"^api/models/(?P<folder>{_F})/(to3d|edit)$"), "folder-create"),
|
||
("GET", re.compile(rf"^api/models/(?P<folder>{_F})/(?P<name>[A-Za-z0-9._-]{{1,80}})$"), "folder"),
|
||
]
|
||
_DROP = {"host", "connection", "content-length", "transfer-encoding", "authorization",
|
||
"cookie", "remote-user", "remote-groups", "remote-email", "remote-name",
|
||
"x-claude-code-session-id", "accept-encoding"}
|
||
|
||
|
||
def _3d_user(who: access.Who) -> str:
|
||
return OWNER_3D_USER if who.is_owner else f"guest-{who.uid}"
|
||
|
||
|
||
async def _3d_get_json(path: str, who: access.Who) -> dict | None:
|
||
try:
|
||
r = await _http().get(f"{THREEDGEN_URL}/{path}",
|
||
headers={"Remote-User": _3d_user(who)}, timeout=20)
|
||
return r.json() if r.status_code == 200 else None
|
||
except (httpx.HTTPError, ValueError):
|
||
return None
|
||
|
||
|
||
async def _owns_folder(who: access.Who, folder: str) -> bool:
|
||
if OWNED.folder_of(folder) == who.uid:
|
||
return True
|
||
# A folder one of their jobs made that the proxy hasn't seen yet.
|
||
for jid in OWNED.jobs(who.uid, 30):
|
||
job = await _3d_get_json(f"api/jobs/{jid}", who)
|
||
if job and job.get("folder"):
|
||
OWNED.add_folder(who.uid, job["folder"])
|
||
if job["folder"] == folder:
|
||
return True
|
||
return False
|
||
|
||
|
||
async def _3d_list(request: Request, who: access.Who) -> JSONResponse:
|
||
ids = OWNED.jobs(who.uid, min(100, int(request.query_params.get("per_page") or 24)))
|
||
got = await asyncio.gather(*(_3d_get_json(f"api/jobs/{j}", who) for j in ids))
|
||
jobs = [j for j in got if j]
|
||
q = (request.query_params.get("q") or "").strip().lower()
|
||
if q:
|
||
jobs = [j for j in jobs if q in json.dumps(
|
||
[j.get("title"), j.get("description"), j.get("tags")]).lower()]
|
||
want = (request.query_params.get("type") or "").strip()
|
||
if want:
|
||
jobs = [j for j in jobs if (j.get("pipeline") or "model3d") == want]
|
||
for j in jobs:
|
||
if j.get("folder"):
|
||
OWNED.add_folder(who.uid, j["folder"])
|
||
return JSONResponse({"jobs": jobs, "total": len(jobs), "page": 1,
|
||
"per_page": len(jobs), "pages": 1, "types": []})
|
||
|
||
|
||
@router.api_route("/proxy/tools/3d-gen/{path:path}", methods=["GET", "POST"],
|
||
include_in_schema=False)
|
||
async def threedgen(request: Request, path: str):
|
||
route = next(((kind, m) for meth, rx, kind in _3D_ROUTES
|
||
if meth == request.method and (m := rx.match(path))), None)
|
||
if route is None:
|
||
return _error(404, "not a 3d-gen API path the proxy serves", "path")
|
||
kind, m = route
|
||
creates = kind in ("create", "folder-create")
|
||
who, err = await _check(request, "3d-gen", creates=creates)
|
||
if err:
|
||
return err
|
||
if not who.is_owner:
|
||
if kind == "list":
|
||
return await _3d_list(request, who)
|
||
if "job" in m.groupdict() and OWNED.job_of(m["job"]) != who.uid:
|
||
return _error(404, "job not found", "owner")
|
||
if "folder" in m.groupdict() and not await _owns_folder(who, m["folder"]):
|
||
return _error(404, "model not found", "owner")
|
||
body = await _body(request, MAX_3D_UPLOAD) if request.method == "POST" else None
|
||
if request.method == "POST" and body is None:
|
||
return _error(413, f"an upload over {MAX_3D_UPLOAD // 1024 ** 2} MB", "size")
|
||
headers = {k: v for k, v in request.headers.items()
|
||
if k.lower() not in _DROP and not k.lower().startswith("x-forwarded-")}
|
||
headers["Remote-User"] = _3d_user(who)
|
||
access.enter(who, "3d-gen")
|
||
try:
|
||
req = _http().build_request(request.method, f"{THREEDGEN_URL}/{path}",
|
||
params=request.query_params, headers=headers,
|
||
content=body)
|
||
resp = await _http().send(req, stream=True)
|
||
except httpx.HTTPError as e:
|
||
access.leave(who, "3d-gen")
|
||
return _error(502, f"the hub couldn't reach 3d-gen: {type(e).__name__}", "upstream")
|
||
if resp.status_code < 400 and (creates or kind == "job" or kind == "folder-job"):
|
||
# A JSON reply we need to read: the new job's id, the folder a job made.
|
||
raw = await resp.aread()
|
||
await resp.aclose()
|
||
access.leave(who, "3d-gen")
|
||
try:
|
||
data = json.loads(raw)
|
||
except ValueError:
|
||
data = None
|
||
if isinstance(data, dict):
|
||
if creates and data.get("id"):
|
||
if not who.is_owner:
|
||
OWNED.add_job(who.uid, str(data["id"]))
|
||
access.count_job(who, "3d-gen")
|
||
_record(request, who, "3d-gen", units={"jobs": 1}, job=str(data["id"]))
|
||
elif kind == "job" and data.get("folder") and not who.is_owner:
|
||
OWNED.add_folder(who.uid, str(data["folder"]))
|
||
return Response(raw, status_code=resp.status_code,
|
||
media_type=resp.headers.get("content-type"))
|
||
out_headers = {k: v for k, v in resp.headers.items()
|
||
if k.lower() in ("content-type", "content-length", "content-disposition",
|
||
"last-modified", "etag")}
|
||
|
||
async def _done():
|
||
await resp.aclose()
|
||
access.leave(who, "3d-gen")
|
||
return StreamingResponse(resp.aiter_raw(), status_code=resp.status_code,
|
||
headers=out_headers, background=BackgroundTask(_done))
|
||
|
||
|
||
# ── the host sidecar's tools: video-extract, 3d-render ──────────────────────
|
||
def _library(who: access.Who) -> str:
|
||
return "owner" if who.is_owner else f"guest-{who.uid}"
|
||
|
||
|
||
async def _sidecar(method: str, path: str, *, params: dict | None = None, json_body=None,
|
||
content=None, stream: bool = False, timeout: float = 60.0):
|
||
if not SIDECAR_TOKEN:
|
||
raise httpx.ConnectError("no SIDECAR_TOKEN")
|
||
req = _http().build_request(method, f"{SIDECAR_URL}{path}", params=params,
|
||
json=json_body, content=content,
|
||
headers={"Authorization": f"Bearer {SIDECAR_TOKEN}"},
|
||
timeout=httpx.Timeout(timeout, read=timeout))
|
||
return await _http().send(req, stream=stream)
|
||
|
||
|
||
def _relay(resp: httpx.Response) -> Response:
|
||
"""A sidecar JSON reply, its error as ours."""
|
||
try:
|
||
data = resp.json()
|
||
except ValueError:
|
||
data = None
|
||
if resp.status_code >= 400:
|
||
detail = (data or {}).get("detail") if isinstance(data, dict) else None
|
||
return _error(resp.status_code, str(detail or resp.text[:300] or "failed"), "tool")
|
||
return JSONResponse(data)
|
||
|
||
|
||
def _stream(resp: httpx.Response, who: access.Who, tool: str) -> Response:
|
||
headers = {k: v for k, v in resp.headers.items()
|
||
if k.lower() in ("content-type", "content-length", "content-disposition",
|
||
"x-render-stats")}
|
||
|
||
async def _done():
|
||
await resp.aclose()
|
||
access.leave(who, tool)
|
||
return StreamingResponse(resp.aiter_raw(), status_code=resp.status_code,
|
||
headers=headers, background=BackgroundTask(_done))
|
||
|
||
|
||
@router.post("/proxy/tools/video-extract/upload", include_in_schema=False)
|
||
async def vx_upload(request: Request, name: str = "video.mp4"):
|
||
who, err = await _check(request, "video-extract")
|
||
if err:
|
||
return err
|
||
access.enter(who, "video-extract")
|
||
try:
|
||
resp = await _sidecar("PUT", "/tools/video-extract/upload",
|
||
params={"library": _library(who), "name": name[:120]},
|
||
content=request.stream(), timeout=900)
|
||
except httpx.HTTPError as e:
|
||
return _error(502, f"the lab couldn't take the upload: {type(e).__name__}", "upstream")
|
||
finally:
|
||
access.leave(who, "video-extract")
|
||
return _relay(resp)
|
||
|
||
|
||
@router.post("/proxy/tools/video-extract/run", include_in_schema=False)
|
||
async def vx_run(request: Request):
|
||
who, err = await _check(request, "video-extract", creates=True)
|
||
if err:
|
||
return err
|
||
try:
|
||
body = json.loads(await _body(request, 64 * 1024) or b"{}")
|
||
except ValueError:
|
||
return _error(400, "a JSON body: {source, fps?, asr?, lang?, describe?, title?, force?}")
|
||
if not isinstance(body, dict) or not isinstance(body.get("source"), str):
|
||
return _error(400, "say which video: {source: <url or upload id>}")
|
||
keep = {k: body[k] for k in ("source", "fps", "asr", "lang", "describe", "title", "force")
|
||
if k in body}
|
||
try:
|
||
resp = await _sidecar("POST", "/tools/video-extract/jobs",
|
||
json_body={**keep, "library": _library(who)})
|
||
except httpx.HTTPError as e:
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}", "upstream")
|
||
out = _relay(resp)
|
||
if resp.status_code < 400:
|
||
access.count_job(who, "video-extract")
|
||
_record(request, who, "video-extract", units={"videos": 1},
|
||
job=(resp.json() or {}).get("job"))
|
||
return out
|
||
|
||
|
||
_VX_GET = [
|
||
(re.compile(r"^jobs/(?P<job>[a-f0-9]{16})$"), "/tools/video-extract/jobs/{job}"),
|
||
(re.compile(r"^videos$"), "/tools/video-extract/videos"),
|
||
(re.compile(rf"^videos/(?P<vid>{_F})$"), "/tools/video-extract/videos/{vid}"),
|
||
]
|
||
_VX_STREAM = [
|
||
(re.compile(rf"^videos/(?P<vid>{_F})/bundle$"), "/tools/video-extract/videos/{vid}/bundle"),
|
||
(re.compile(rf"^videos/(?P<vid>{_F})/file$"), "/tools/video-extract/videos/{vid}/file"),
|
||
]
|
||
|
||
|
||
@router.api_route("/proxy/tools/video-extract/{path:path}", methods=["GET", "DELETE"],
|
||
include_in_schema=False)
|
||
async def vx_read(request: Request, path: str):
|
||
who, err = await _check(request, "video-extract")
|
||
if err:
|
||
return err
|
||
params = {"library": _library(who)}
|
||
if request.method == "DELETE":
|
||
m = re.match(rf"^videos/(?P<vid>{_F})$", path)
|
||
if not m:
|
||
return _error(404, "not a video-extract path", "path")
|
||
try:
|
||
return _relay(await _sidecar("DELETE", f"/tools/video-extract/videos/{m['vid']}",
|
||
params=params))
|
||
except httpx.HTTPError as e:
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}", "upstream")
|
||
for rx, target in _VX_GET:
|
||
if m := rx.match(path):
|
||
try:
|
||
return _relay(await _sidecar("GET", target.format(**m.groupdict()),
|
||
params=params, timeout=180))
|
||
except httpx.HTTPError as e:
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}",
|
||
"upstream")
|
||
for rx, target in _VX_STREAM:
|
||
if m := rx.match(path):
|
||
if target.endswith("/file"):
|
||
params["path"] = (request.query_params.get("path") or "")[:300]
|
||
access.enter(who, "video-extract")
|
||
try:
|
||
resp = await _sidecar("GET", target.format(**m.groupdict()), params=params,
|
||
stream=True, timeout=600)
|
||
except httpx.HTTPError as e:
|
||
access.leave(who, "video-extract")
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}",
|
||
"upstream")
|
||
if resp.status_code >= 400:
|
||
await resp.aread()
|
||
await resp.aclose()
|
||
access.leave(who, "video-extract")
|
||
return _relay(resp)
|
||
return _stream(resp, who, "video-extract")
|
||
return _error(404, "not a video-extract path", "path")
|
||
|
||
|
||
@router.post("/proxy/tools/video-extract/search", include_in_schema=False)
|
||
async def vx_search(request: Request):
|
||
who, err = await _check(request, "video-extract")
|
||
if err:
|
||
return err
|
||
try:
|
||
body = json.loads(await _body(request, 16 * 1024) or b"{}")
|
||
except ValueError:
|
||
return _error(400, "a JSON body: {q, mode?, video?, k?}")
|
||
if not isinstance(body, dict) or not isinstance(body.get("q"), str):
|
||
return _error(400, "a JSON body: {q, mode?, video?, k?}")
|
||
keep = {k: body[k] for k in ("q", "mode", "video", "k") if k in body}
|
||
access.enter(who, "video-extract")
|
||
try:
|
||
resp = await _sidecar("POST", "/tools/video-extract/search",
|
||
json_body={**keep, "library": _library(who)}, timeout=600)
|
||
except httpx.HTTPError as e:
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}", "upstream")
|
||
finally:
|
||
access.leave(who, "video-extract")
|
||
return _relay(resp)
|
||
|
||
|
||
@router.post("/proxy/tools/3d-render", include_in_schema=False)
|
||
async def render(request: Request):
|
||
who, err = await _check(request, "3d-render")
|
||
if err:
|
||
return err
|
||
body = await _body(request, MAX_GLB)
|
||
if body is None:
|
||
return _error(413, f"a model over {MAX_GLB // 1024 ** 2} MB", "size")
|
||
keep = {k: v for k, v in request.query_params.items()
|
||
if k in ("views", "modes", "size", "ss", "bg", "ortho", "fov", "title")}
|
||
access.enter(who, "3d-render")
|
||
try:
|
||
resp = await _sidecar("POST", "/tools/3d-render", params=keep, content=body,
|
||
stream=True, timeout=240)
|
||
except httpx.HTTPError as e:
|
||
access.leave(who, "3d-render")
|
||
return _error(502, f"the lab's sidecar didn't answer: {type(e).__name__}", "upstream")
|
||
if resp.status_code >= 400:
|
||
await resp.aread()
|
||
await resp.aclose()
|
||
access.leave(who, "3d-render")
|
||
return _relay(resp)
|
||
_record(request, who, "3d-render", units={"renders": 1})
|
||
return _stream(resp, who, "3d-render")
|
||
|
||
|
||
# ── Matomo (analytics) ───────────────────────────────────────────────────────
|
||
@router.post("/proxy/tools/matomo/{op}", include_in_schema=False)
|
||
async def matomo_op(request: Request, op: str):
|
||
"""``sites`` · ``add-site {url, name?}`` · ``report {site, method, params}``
|
||
· ``tracking {site}`` · ``token {rotate?}`` — on the caller's own sites
|
||
(``matomo.py``); the owner's calls see every site."""
|
||
fn = matomo.OPS.get(op)
|
||
if fn is None:
|
||
return _error(404, f"unknown Matomo operation {op!r} — {', '.join(matomo.OPS)}", "op")
|
||
who, err = await _check(request, "matomo")
|
||
if err:
|
||
return err
|
||
if not matomo.admin_token():
|
||
return _error(503, "the hub has no Matomo token (MATOMO_TOKEN)", "config")
|
||
raw = await _body(request, 64 * 1024)
|
||
if raw is None:
|
||
return _error(413, "a request over 64 KB", "size")
|
||
try:
|
||
body = json.loads(raw or b"{}")
|
||
except ValueError:
|
||
return _error(400, "the body must be JSON", "body")
|
||
if not isinstance(body, dict):
|
||
return _error(400, "the body must be a JSON object", "body")
|
||
access.enter(who, "matomo")
|
||
try:
|
||
out = await fn(matomo.Matomo(_http()), _deps(request), who.uid, body)
|
||
except matomo.MatomoError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
finally:
|
||
access.leave(who, "matomo")
|
||
_record(request, who, "matomo", units={"calls": 1}, op=op,
|
||
site=str(body["site"])[:12] if body.get("site") is not None else None)
|
||
return JSONResponse(out)
|
||
|
||
|
||
# ── Meta Business (read-only) ────────────────────────────────────────────────
|
||
@router.post("/proxy/tools/meta/{op}", include_in_schema=False)
|
||
async def meta_op(request: Request, op: str):
|
||
"""``status`` · ``days {since, until, parts?}`` · ``media {since?, limit?}`` ·
|
||
``audience`` · ``history {since, until, parts?}`` · ``get {path, params,
|
||
all?}`` — on the caller's own Meta connection (``meta.py``); the owner
|
||
names a guest's with ``as`` (or gets the only one)."""
|
||
fn = meta.OPS.get(op)
|
||
if fn is None:
|
||
return _error(404, f"unknown Meta operation {op!r} — {', '.join(meta.OPS)}", "op")
|
||
who, err = await _check(request, "meta")
|
||
if err:
|
||
return err
|
||
raw = await _body(request, 64 * 1024)
|
||
if raw is None:
|
||
return _error(413, "a request over 64 KB", "size")
|
||
try:
|
||
body = json.loads(raw or b"{}")
|
||
except ValueError:
|
||
return _error(400, "the body must be JSON", "body")
|
||
if not isinstance(body, dict):
|
||
return _error(400, "the body must be a JSON object", "body")
|
||
try:
|
||
uid, rec = meta.connection_for(who.uid, body)
|
||
except meta.MetaError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
g = meta.Graph(_http(), rec)
|
||
access.enter(who, "meta")
|
||
try:
|
||
out = await fn(g, uid, rec, body)
|
||
except meta.MetaError as e:
|
||
if e.kind == "meta-token":
|
||
await run_in_threadpool(meta_key_died, _deps(request), uid, e.message)
|
||
return _error(e.status, e.message, e.kind)
|
||
finally:
|
||
access.leave(who, "meta")
|
||
_record(request, who, "meta", units={"calls": g.calls}, op=op,
|
||
of=uid if who.is_owner else None)
|
||
return JSONResponse(out)
|
||
|
||
|
||
def meta_key_died(deps, uid: str, message: str) -> None:
|
||
"""Meta says a connected key no longer works: note it on the connection
|
||
(the page shows it) and push the guest and the owner — once."""
|
||
rec = meta.STORE.get(uid)
|
||
if not rec.get("token") or rec.get("error"):
|
||
return
|
||
meta.STORE.update(uid, {"error": {"at": meta._now_iso(), "message": message,
|
||
"kind": "meta-token"}})
|
||
try:
|
||
from notifications.service import VIEW_URL, _create_notify
|
||
from users import deliver
|
||
url = f"{deliver.GUEST_PUBLIC_URL}/settings/meta" if deliver.GUEST_PUBLIC_URL else ""
|
||
deliver.to_guests(deps, [uid], "⚠️ Meta Business disconnected",
|
||
"Meta stopped accepting the key — make a new one and paste it in "
|
||
"Settings → Meta Business.", url, VIEW_URL, extra={"type": "warn"},
|
||
i18n={"fr": {"title": "⚠️ Meta Business déconnecté",
|
||
"message": "Meta n'accepte plus la clé — refais-en une et "
|
||
"colle-la dans Réglages → Meta Business."}})
|
||
_create_notify(deps, {"title": f"⚠️ {uid}'s Meta key stopped working",
|
||
"message": message[:200], "type": "warn", "sessionId": ""})
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ── Movies (Seerr) ───────────────────────────────────────────────────────────
|
||
@router.post("/proxy/tools/movies/webhook", include_in_schema=False)
|
||
async def movies_webhook(request: Request):
|
||
"""Seerr's webhook agent (``services/media``): a title the hub requested is
|
||
on Jellyfin, failed or was declined → push the requester. Lab-internal:
|
||
Seerr calls ``http://ai-agent:8080`` with its own token; never on the
|
||
guest host."""
|
||
if on_public_surface(request):
|
||
return _error(404, "not found", "route")
|
||
want = media.webhook_token()
|
||
if not want or not hmac.compare_digest(_bearer(request), want):
|
||
return _error(401, "bad webhook token", "auth")
|
||
raw = await _body(request, 64 * 1024)
|
||
try:
|
||
payload = json.loads(raw or b"{}")
|
||
except ValueError:
|
||
return _error(400, "the body must be JSON", "body")
|
||
if not isinstance(payload, dict):
|
||
return _error(400, "the body must be a JSON object", "body")
|
||
out = await run_in_threadpool(media.handle_webhook, _deps(request), payload)
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.post("/proxy/tools/movies/{op}", include_in_schema=False)
|
||
async def movies_op(request: Request, op: str):
|
||
"""``search {query, type?, year?}`` · ``info {type, tmdb}`` ·
|
||
``request {type, tmdb, seasons?}`` · ``requests`` — through Seerr as the
|
||
caller's Seerr user (``media.py``): guests movies only, within their quota."""
|
||
fn = media.OPS.get(op)
|
||
if fn is None:
|
||
return _error(404, f"unknown movies operation {op!r} — {', '.join(media.OPS)}", "op")
|
||
who, err = await _check(request, "movies")
|
||
if err:
|
||
return err
|
||
if not media.api_key():
|
||
return _error(503, "the hub has no Seerr key (SEERR_API_KEY)", "config")
|
||
raw = await _body(request, 16 * 1024)
|
||
if raw is None:
|
||
return _error(413, "a request over 16 KB", "size")
|
||
try:
|
||
body = json.loads(raw or b"{}")
|
||
except ValueError:
|
||
return _error(400, "the body must be JSON", "body")
|
||
if not isinstance(body, dict):
|
||
return _error(400, "the body must be a JSON object", "body")
|
||
deps = _deps(request)
|
||
sid = access.session_of(deps, who, request.headers.get("x-claude-code-session-id"))
|
||
ctx = media.ctx_for(deps, who.uid, sid)
|
||
access.enter(who, "movies")
|
||
try:
|
||
out = await fn(media.Seerr(_http()), ctx, body)
|
||
except media.MediaError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
finally:
|
||
access.leave(who, "movies")
|
||
units = {"calls": 1}
|
||
if op == "request" and isinstance(out, dict) and out.get("request"):
|
||
units["movies" if out.get("type") == "movie" else "series"] = 1
|
||
_record(request, who, "movies", units=units, op=op,
|
||
tmdb=str(body.get("tmdb"))[:12] if body.get("tmdb") is not None else None)
|
||
return JSONResponse(out)
|
||
|