CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
"""API do Publicador (127.0.0.1:4530, faixa 4500–4599 do CenaForge). Contrato: doc/publicacao/PLANO.md §3.
|
||||
|
||||
Toda rota exige `X-Service-Key` = PUBLISHER_SERVICE_KEY (publisher/.env), exceto `GET /health` e
|
||||
`GET /oauth/callback/{platform}` (essa é aberta pelo navegador do usuário e é validada pelo `state`).
|
||||
Erros: `{"detail": "<mensagem em pt-BR>"}`. Campos JSON em camelCase. Quem chama é o painel.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import html
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .acl import restrict_to_current_user
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .service import Publisher, UserError
|
||||
from .vault import Vault, VaultError
|
||||
from .worker import Worker
|
||||
|
||||
VERSION = "1.0.0"
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
# httpx/httpcore logam a URL inteira em INFO — e a Graph API do Instagram leva o token na query. Silenciar.
|
||||
for _noisy in ("httpx", "httpcore"):
|
||||
logging.getLogger(_noisy).setLevel(logging.WARNING)
|
||||
|
||||
Platform = Literal["youtube", "tiktok", "instagram"]
|
||||
OPEN_PATHS = ("/health", "/oauth/callback/")
|
||||
|
||||
|
||||
class AppIn(BaseModel):
|
||||
clientId: str = Field(min_length=1, max_length=300)
|
||||
clientSecret: str = Field(default="", max_length=500)
|
||||
|
||||
|
||||
class ConnectIn(BaseModel):
|
||||
platform: Platform
|
||||
mode: Literal["official", "session"]
|
||||
|
||||
|
||||
class TokenIn(BaseModel):
|
||||
accessToken: str = Field(min_length=20, max_length=4000)
|
||||
|
||||
|
||||
class StatsIn(BaseModel):
|
||||
ids: list[str] = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class JobIn(BaseModel):
|
||||
profileId: str = Field(min_length=3, max_length=100)
|
||||
platform: Platform
|
||||
file: str = Field(min_length=3, max_length=1000)
|
||||
cover: str | None = Field(default=None, max_length=1000)
|
||||
title: str = Field(default="", max_length=500)
|
||||
caption: str = Field(default="", max_length=2200)
|
||||
tags: list[str] = Field(default_factory=list, max_length=60)
|
||||
privacy: Literal["public", "unlisted", "private"] = "public"
|
||||
publishAt: str | None = Field(default=None, max_length=40)
|
||||
aiGenerated: bool = False
|
||||
madeForKids: bool = False
|
||||
tiktokMode: Literal["direct", "draft"] = "direct"
|
||||
# Idempotência: o mesmo clientRef devolve o job já criado (200) em vez de criar outro.
|
||||
clientRef: str | None = Field(default=None, min_length=1, max_length=80)
|
||||
|
||||
|
||||
FIELD_NAMES = {"clientId": "Client ID", "clientSecret": "Client Secret", "accessToken": "token", "file": "arquivo",
|
||||
"cover": "capa", "title": "título", "caption": "legenda", "tags": "tags", "privacy": "privacidade",
|
||||
"platform": "rede", "mode": "modo", "profileId": "perfil", "tiktokMode": "modo do TikTok"}
|
||||
|
||||
|
||||
def validation_message(exc: RequestValidationError) -> str:
|
||||
parts = []
|
||||
for error in exc.errors()[:3]:
|
||||
loc = [str(p) for p in error.get("loc", []) if p not in ("body", "query", "path")]
|
||||
field = FIELD_NAMES.get(loc[0], loc[0]) if loc else "corpo"
|
||||
kind = error.get("type", "")
|
||||
if kind == "missing":
|
||||
parts.append(f"falta o campo {field}")
|
||||
elif kind in ("string_too_long", "too_long"):
|
||||
parts.append(f"{field} é longo demais (máx. {error.get('ctx', {}).get('max_length', '?')})")
|
||||
elif kind in ("string_too_short", "too_short"):
|
||||
parts.append(f"{field} é curto demais")
|
||||
elif kind in ("literal_error", "enum"):
|
||||
parts.append(f"{field} com valor inválido (aceitos: {error.get('ctx', {}).get('expected', '?')})")
|
||||
elif kind == "json_invalid":
|
||||
parts.append("o corpo não é um JSON válido")
|
||||
else:
|
||||
parts.append(f"{field} inválido")
|
||||
return "Pedido inválido: " + "; ".join(parts or ["formato inesperado"]) + "."
|
||||
|
||||
|
||||
def callback_page(title: str, message: str, ok: bool) -> str:
|
||||
# Página simples e acessível: lang pt-BR, contraste alto (texto #111 em #fff = 18:1), texto grande, sem script.
|
||||
color = "#0a6b2d" if ok else "#a4161a"
|
||||
return f"""<!doctype html>
|
||||
<html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{html.escape(title)} — CenaForge</title>
|
||||
<style>
|
||||
body{{margin:0;background:#fff;color:#111;font:18px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}}
|
||||
main{{max-width:36rem;margin:12vh auto;padding:0 16px}}
|
||||
h1{{font-size:1.6rem;color:{color};margin:0 0 .5rem}}
|
||||
p{{margin:.5rem 0}}
|
||||
@media (prefers-color-scheme: dark){{body{{background:#111;color:#f2f2f2}}h1{{color:{'#6fdc8c' if ok else '#ff8a8a'}}}}}
|
||||
</style></head>
|
||||
<body><main role="main"><h1>{"✔" if ok else "✖"} {html.escape(title)}</h1>
|
||||
<p role="status">{html.escape(message)}</p></main></body></html>"""
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, publisher: Publisher | None = None, start_worker: bool = True,
|
||||
worker: Worker | None = None) -> FastAPI:
|
||||
settings = settings or Settings.load()
|
||||
if not settings.service_key:
|
||||
raise ConfigError("PUBLISHER_SERVICE_KEY vazio: rode o setup.bat (ou preencha publisher/.env).")
|
||||
if publisher is None:
|
||||
if not settings.data_dir.exists():
|
||||
# Primeira subida: a pasta nasce acessível só ao usuário atual (cofre, banco, sessões, capturas).
|
||||
settings.data_dir.mkdir(parents=True)
|
||||
restrict_to_current_user(settings.data_dir)
|
||||
db = Database(settings.db_path)
|
||||
publisher = Publisher(settings, db, Vault(settings.vault_path))
|
||||
worker = worker or Worker(publisher.db, publisher.execute, publisher.maintenance)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
if start_worker:
|
||||
worker.start()
|
||||
yield
|
||||
worker.stop()
|
||||
publisher.close()
|
||||
|
||||
app = FastAPI(title="CenaForge Publicador", version=VERSION, docs_url=None, redoc_url=None, openapi_url=None,
|
||||
lifespan=lifespan)
|
||||
app.state.publisher, app.state.worker = publisher, worker
|
||||
|
||||
@app.middleware("http")
|
||||
async def auth(request: Request, call_next):
|
||||
path = request.url.path
|
||||
if not (path == "/health" or (request.method == "GET" and path.startswith("/oauth/callback/"))):
|
||||
given = request.headers.get("X-Service-Key", "")
|
||||
if not hmac.compare_digest(given.encode(), settings.service_key.encode()):
|
||||
return JSONResponse({"detail": "Chave do serviço ausente ou inválida."}, status_code=401)
|
||||
return await call_next(request)
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
async def user_error(_request: Request, exc: UserError):
|
||||
return JSONResponse({"detail": exc.message}, status_code=exc.status)
|
||||
|
||||
@app.exception_handler(VaultError)
|
||||
async def vault_error(_request: Request, exc: VaultError):
|
||||
return JSONResponse({"detail": str(exc)}, status_code=500)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid(_request: Request, exc: RequestValidationError):
|
||||
return JSONResponse({"detail": validation_message(exc)}, status_code=422)
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/v1/status")
|
||||
def status():
|
||||
return {"browser": publisher.browser_status(), "worker": "busy" if worker.busy else "idle",
|
||||
"queue": publisher.queue_size()}
|
||||
|
||||
# ---------- apps das redes (Client ID/Secret; o segredo nunca volta)
|
||||
@app.get("/v1/apps")
|
||||
def apps():
|
||||
return {p: publisher.app_state(p) for p in ("youtube", "tiktok", "instagram")}
|
||||
|
||||
@app.put("/v1/apps/{platform}")
|
||||
def put_app(platform: str, body: AppIn):
|
||||
return publisher.set_app(platform, body.clientId, body.clientSecret)
|
||||
|
||||
@app.delete("/v1/apps/{platform}")
|
||||
def delete_app(platform: str):
|
||||
return publisher.delete_app(platform)
|
||||
|
||||
# ---------- perfis
|
||||
@app.get("/v1/profiles/{profile_id}")
|
||||
def get_profile(profile_id: str):
|
||||
return publisher.profile(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/connect")
|
||||
def connect(profile_id: str, body: ConnectIn):
|
||||
return publisher.connect(profile_id, body.platform, body.mode)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/token")
|
||||
def token(profile_id: str, body: TokenIn):
|
||||
return publisher.paste_token(profile_id, body.accessToken)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/session/check")
|
||||
def session_check(profile_id: str):
|
||||
return publisher.session_check(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/session/open")
|
||||
def session_open(profile_id: str):
|
||||
return publisher.session_open(profile_id)
|
||||
|
||||
@app.delete("/v1/profiles/{profile_id}")
|
||||
def disconnect(profile_id: str):
|
||||
return publisher.disconnect(profile_id)
|
||||
|
||||
@app.post("/v1/profiles/{profile_id}/stats")
|
||||
def post_stats(profile_id: str, body: StatsIn):
|
||||
return publisher.post_stats(profile_id, body.ids)
|
||||
|
||||
@app.get("/v1/profiles/{profile_id}/tiktok/creator-info")
|
||||
def creator_info(profile_id: str):
|
||||
return publisher.tiktok_creator_info(profile_id)
|
||||
|
||||
# ---------- jobs
|
||||
@app.post("/v1/jobs", status_code=201)
|
||||
def create_job(body: JobIn, response: Response):
|
||||
job, created = publisher.create_job(body.model_dump())
|
||||
if created:
|
||||
worker.wake()
|
||||
else:
|
||||
response.status_code = 200 # já existia com este clientRef: nada novo foi criado
|
||||
return job
|
||||
|
||||
@app.get("/v1/jobs/{job_id}")
|
||||
def get_job(job_id: str):
|
||||
return publisher.job(job_id)
|
||||
|
||||
@app.post("/v1/jobs/{job_id}/cancel")
|
||||
def cancel_job(job_id: str):
|
||||
return publisher.cancel_job(job_id)
|
||||
|
||||
# ---------- OAuth (aberta: validada pelo state de uso único)
|
||||
@app.get("/oauth/callback/{platform}", response_class=HTMLResponse)
|
||||
def oauth_callback(platform: str, request: Request):
|
||||
try:
|
||||
message = publisher.oauth_callback(platform, dict(request.query_params))
|
||||
except UserError as exc:
|
||||
return HTMLResponse(callback_page("Não deu para conectar", exc.message, False), status_code=exc.status)
|
||||
return HTMLResponse(callback_page("Conta conectada", message, True))
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def build() -> FastAPI: # pragma: no cover - ponto de entrada do uvicorn (--factory)
|
||||
return create_app()
|
||||
Reference in New Issue
Block a user