Files
ai-agent/backend/toolproxy/metaroutes.py

163 lines
6.3 KiB
Python

"""
``/api/me/meta`` and ``/api/users/{uid}/meta`` — connecting a guest's Meta
Business (``meta.py``), on the app's own session.
* ``GET /api/me/meta`` — Settings → Meta Business: is the group on, what the
connection reaches, the last snapshot;
* ``PUT /api/me/meta {token}`` — connect (or replace) the key: Meta checks it
first (``meta.inspect``: it must work, read only, and reach an asset), then
the last 28 days are saved in the background;
* ``POST /api/me/meta/test`` — check the stored key again (and refresh what
it reaches);
* ``DELETE /api/me/meta`` — forget the key (the saved days stay);
* ``GET|DELETE /api/users/{uid}/meta`` — the owner's view of one guest's
(Settings → Users → <guest> → Access).
The key is write-only: no answer ever carries it.
"""
from __future__ import annotations
import asyncio
import logging
import threading
import httpx
from fastapi import APIRouter, Body, HTTPException
import schemas
from core.http import _r
from core.state import State
from users.caller import CallerDep
from . import access, meta
log = logging.getLogger("toolproxy.metaroutes")
router = APIRouter()
def _page(deps, uid: str) -> dict:
enabled = "meta" in access.config(deps, access.Who(uid))["groups"]
return {"enabled": enabled, "connection": meta.public(meta.STORE.get(uid)),
"scopesAsked": list(meta.SCOPES_ASKED), "graphVersion": meta.GRAPH_VERSION}
def _guest(deps, caller) -> str:
"""The caller's uid when they may connect Meta: a guest, active, with
the group on."""
if caller.is_owner:
raise HTTPException(403, "you read guests' Meta connections from Settings → Users")
if not deps.users.active(caller.id) or deps.security_state.guests_locked():
raise HTTPException(403, "not available")
if "meta" not in access.config(deps, access.Who(caller.id))["groups"]:
raise HTTPException(403, "Meta Business isn't switched on for you")
return caller.id
def _http() -> httpx.AsyncClient:
from .routes import _http as shared
return shared()
def _fail(e: meta.MetaError) -> HTTPException:
return HTTPException(e.status if e.status != 502 else 502, e.message)
def backfill(uid: str) -> None:
"""The last 28 days, saved in the background after a connect."""
def run() -> None:
async def go():
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=120.0)) as c:
return await meta.snapshot(c, uid, backfill=True)
try:
out = asyncio.run(go())
from .ledger import LEDGER
LEDGER.record({"tool": "meta", "who": uid, "guest": uid, "via": "snapshot",
"usd": 0, "units": {"calls": out.get("calls", 0)}, "op": "backfill"})
except Exception as e:
log.warning("meta backfill for %s failed: %s", uid, e)
threading.Thread(target=run, name=f"meta-backfill-{uid}", daemon=True).start()
@router.get("/api/me/meta", responses=_r(schemas.MetaPage))
async def my_meta(deps: State, caller: CallerDep):
"""The guest's own Meta Business page."""
if caller.is_owner:
raise HTTPException(403, "you read guests' Meta connections from Settings → Users")
return _page(deps, caller.id)
@router.put("/api/me/meta", responses=_r(schemas.MetaPage))
async def connect_meta(deps: State, caller: CallerDep, body: dict = Body(...)):
"""Connect (or replace) the key — checked with Meta before it is kept."""
uid = _guest(deps, caller)
token = str((body or {}).get("token") or "").strip()
try:
rec = await meta.inspect(_http(), token)
except meta.MetaError as e:
if e.kind == "meta-token":
# Not "no longer works": this key never did.
raise HTTPException(400, "Meta doesn't accept this key — copy it again from Meta, "
"all of it (it starts with EAA), or make a new one") from None
raise _fail(e) from None
old = meta.STORE.get(uid)
rec["connectedAt"] = meta._now_iso()
rec["snapshot"] = old.get("snapshot") or {}
meta.STORE.put(uid, rec)
try:
from security.service import record
record(deps, "guest_meta_connected", who=uid,
detail=f"{rec['user'].get('name') or 'system user'}: "
f"{len(rec['adAccounts'])} ad account(s), {len(rec['pages'])} Page(s), "
f"{len(rec['instagram'])} Instagram")
except Exception:
pass
backfill(uid)
return _page(deps, uid)
@router.post("/api/me/meta/test", responses=_r(schemas.MetaPage))
async def test_meta(deps: State, caller: CallerDep):
"""Check the stored key again; what it reaches is refreshed."""
uid = _guest(deps, caller)
cur = meta.STORE.get(uid)
if not cur.get("token"):
raise HTTPException(404, "nothing connected")
try:
rec = await meta.inspect(_http(), cur["token"])
except meta.MetaError as e:
if e.kind in ("meta-token", "scopes", "no-assets"):
meta.STORE.update(uid, {"error": {"at": meta._now_iso(), "message": e.message,
"kind": e.kind}})
raise _fail(e) from None
meta.STORE.update(uid, {k: rec[k] for k in ("pageTokens", "user", "scopes", "adAccounts",
"pages", "instagram", "expiresAt", "checkedAt")}
| {"error": None})
return _page(deps, uid)
@router.delete("/api/me/meta", responses=_r(schemas.MetaPage))
async def disconnect_meta(deps: State, caller: CallerDep):
"""Forget the key (the saved days stay, for a later reconnect)."""
if caller.is_owner:
raise HTTPException(403, "you read guests' Meta connections from Settings → Users")
meta.STORE.drop(caller.id)
return _page(deps, caller.id)
@router.get("/api/users/{uid}/meta", responses=_r(schemas.MetaPage))
async def user_meta(deps: State, caller: CallerDep, uid: str):
"""One guest's connection, for the owner's Access tab."""
if not deps.users.get(uid):
raise HTTPException(404, "no such user")
return _page(deps, uid)
@router.delete("/api/users/{uid}/meta", responses=_r(schemas.MetaPage))
async def drop_user_meta(deps: State, caller: CallerDep, uid: str):
"""The owner disconnects a guest's Meta."""
if not deps.users.get(uid):
raise HTTPException(404, "no such user")
meta.STORE.drop(uid)
return _page(deps, uid)