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,93 @@
|
||||
// Ponte do painel com o Clipador (clipper/, 127.0.0.1:4520): cortes de live (Twitch, YouTube, Kick).
|
||||
// O serviço grava, lê o chat, transcreve (serviço de voz), pede o veredito da IA (Codex/Claude pela CLI)
|
||||
// e renderiza. O painel lê a chave e a porta de clipper/.env e repassa as chamadas da página /clipper.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { REPO_ROOT } from "./paths";
|
||||
import { UserError } from "./stories";
|
||||
|
||||
const ENV_FILE = path.join(REPO_ROOT, "clipper", ".env");
|
||||
|
||||
function readClipperEnv(): Record<string, string> {
|
||||
if (!fs.existsSync(ENV_FILE)) return {};
|
||||
const env: Record<string, string> = {};
|
||||
for (const line of fs.readFileSync(ENV_FILE, "utf8").split(/\r?\n/)) {
|
||||
const at = line.indexOf("=");
|
||||
if (at <= 0 || line.trimStart().startsWith("#")) continue;
|
||||
env[line.slice(0, at).trim()] = line.slice(at + 1).trim();
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
function serviceUrl(pathname: string): { url: string; key: string } {
|
||||
const env = readClipperEnv();
|
||||
if (!env.CLIPPER_SERVICE_KEY) throw new UserError("Clipador não instalado: rode o setup.bat.");
|
||||
return { url: `http://127.0.0.1:${env.CLIPPER_PORT || "4520"}${pathname}`, key: env.CLIPPER_SERVICE_KEY };
|
||||
}
|
||||
|
||||
/**
|
||||
* Caminhos que o navegador pode pedir (sempre sob /v1/). Qualquer outro é recusado aqui, antes do serviço.
|
||||
* status · judge · emotes · games[/id[/research|refine|notes/n]] · channels[/id[/check|settings]]
|
||||
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]]
|
||||
* editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest)
|
||||
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
|
||||
*/
|
||||
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest))?))?)$/;
|
||||
|
||||
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
|
||||
const METHODS: [RegExp, string[]][] = [
|
||||
[/^clips\/delete$/, ["POST"]],
|
||||
[/^clips\/\d{1,9}$/, ["GET", "PATCH", "DELETE"]],
|
||||
];
|
||||
|
||||
export async function clipperFetch(pathname: string, init: RequestInit = {}, timeoutMs = 30_000): Promise<Response> {
|
||||
const { url, key } = serviceUrl(pathname);
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set("X-Service-Key", key);
|
||||
try {
|
||||
return await fetch(url, { ...init, headers, signal: AbortSignal.timeout(timeoutMs), cache: "no-store" });
|
||||
} catch {
|
||||
throw new UserError("Clipador fora do ar (127.0.0.1:4520). Suba com start.bat ou pnpm dev.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Repassa uma chamada da página para o serviço, só nos caminhos permitidos. Erros do serviço voltam como estão. */
|
||||
export async function proxy(request: Request, segments: string[]): Promise<Response> {
|
||||
const sub = segments.join("/");
|
||||
if (!ALLOWED.test(sub)) return Response.json({ error: "Caminho do Clipador não permitido." }, { status: 404 });
|
||||
const search = new URL(request.url).search;
|
||||
const method = request.method.toUpperCase();
|
||||
const methods = METHODS.find(([pattern]) => pattern.test(sub))?.[1];
|
||||
if (methods && !methods.includes(method)) return Response.json({ error: "Método não permitido neste caminho do Clipador." }, { status: 405 });
|
||||
const body = method === "GET" || method === "DELETE" ? undefined : await request.text();
|
||||
// Rotas que chamam a IA pela CLI ou o Streamlink demoram: pesquisa de jogo na web até 8 min (o serviço corta em 7);
|
||||
// achar câmera/prévia/checar live até 3 min (a câmera local baixa o modelo na 1ª vez); editor (proxy de até 10 min
|
||||
// de vídeo, prévia real, Whisper, TTS, IA) até 5 min; série do rosto (só leitura do banco) e reset, 30 s; o resto, 2 min.
|
||||
const timeoutMs = /^games\/[^/]+\/(research|refine)$/.test(sub) ? 480_000
|
||||
: /^clips\/\d+\/(proxy|preview-render|retranscribe|tts|suggest|waveform)$/.test(sub) ? 300_000
|
||||
: /\/(detect-cam|preview|check)$/.test(sub) ? 180_000
|
||||
: /^sessions\/\d+\/face(\/reset)?$/.test(sub) ? 30_000 : 120_000;
|
||||
const response = await clipperFetch(`/v1/${sub}${search}`, {
|
||||
method,
|
||||
body,
|
||||
headers: body ? { "Content-Type": "application/json" } : undefined,
|
||||
}, timeoutMs);
|
||||
const text = await response.text();
|
||||
return new Response(response.status === 204 ? null : text, {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
export type ClipperOnline = { online: true; status: Record<string, unknown> } | { online: false; reason: string };
|
||||
|
||||
/** Estado do serviço sem falhar: fora do ar vira `online: false` com o motivo. */
|
||||
export async function clipperStatus(): Promise<ClipperOnline> {
|
||||
try {
|
||||
const response = await clipperFetch("/v1/status", {}, 5_000);
|
||||
if (!response.ok) return { online: false, reason: `Clipador respondeu ${response.status}.` };
|
||||
return { online: true, status: (await response.json()) as Record<string, unknown> };
|
||||
} catch (error) {
|
||||
return { online: false, reason: error instanceof UserError ? error.message : "Clipador fora do ar." };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user